Completed
Push — try/refactor-secrets-and-token... ( ad6cd9...9cdaa1 )
by
unknown
837:53 queued 825:50
created

Jetpack::disconnect_user()   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 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets;
4
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
5
use Automattic\Jetpack\Config;
6
use Automattic\Jetpack\Connection\Client;
7
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
8
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
9
use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
10
use Automattic\Jetpack\Connection\Secrets;
11
use Automattic\Jetpack\Connection\Tokens;
12
use Automattic\Jetpack\Connection\Webhooks as Connection_Webhooks;
13
use Automattic\Jetpack\Constants;
14
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
15
use Automattic\Jetpack\Licensing;
16
use Automattic\Jetpack\Partner;
17
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
18
use Automattic\Jetpack\Redirect;
19
use Automattic\Jetpack\Status;
20
use Automattic\Jetpack\Sync\Functions;
21
use Automattic\Jetpack\Sync\Health;
22
use Automattic\Jetpack\Sync\Sender;
23
use Automattic\Jetpack\Sync\Users;
24
use Automattic\Jetpack\Terms_Of_Service;
25
use Automattic\Jetpack\Tracking;
26
27
/*
28
Options:
29
jetpack_options (array)
30
	An array of options.
31
	@see Jetpack_Options::get_option_names()
32
33
jetpack_register (string)
34
	Temporary verification secrets.
35
36
jetpack_activated (int)
37
	1: the plugin was activated normally
38
	2: the plugin was activated on this site because of a network-wide activation
39
	3: the plugin was auto-installed
40
	4: the plugin was manually disconnected (but is still installed)
41
42
jetpack_active_modules (array)
43
	Array of active module slugs.
44
45
jetpack_do_activate (bool)
46
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
47
*/
48
49
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
50
51
class Jetpack {
52
	public $xmlrpc_server = null;
53
54
	/**
55
	 * @var array The handles of styles that are concatenated into jetpack.css.
56
	 *
57
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
58
	 */
59
	public $concatenated_style_handles = array(
60
		'jetpack-carousel',
61
		'grunion.css',
62
		'the-neverending-homepage',
63
		'jetpack_likes',
64
		'jetpack_related-posts',
65
		'sharedaddy',
66
		'jetpack-slideshow',
67
		'presentations',
68
		'quiz',
69
		'jetpack-subscriptions',
70
		'jetpack-responsive-videos-style',
71
		'jetpack-social-menu',
72
		'tiled-gallery',
73
		'jetpack_display_posts_widget',
74
		'gravatar-profile-widget',
75
		'goodreads-widget',
76
		'jetpack_social_media_icons_widget',
77
		'jetpack-top-posts-widget',
78
		'jetpack_image_widget',
79
		'jetpack-my-community-widget',
80
		'jetpack-authors-widget',
81
		'wordads',
82
		'eu-cookie-law-style',
83
		'flickr-widget-style',
84
		'jetpack-search-widget',
85
		'jetpack-simple-payments-widget-style',
86
		'jetpack-widget-social-icons-styles',
87
		'wpcom_instagram_widget',
88
	);
89
90
	/**
91
	 * Contains all assets that have had their URL rewritten to minified versions.
92
	 *
93
	 * @var array
94
	 */
95
	static $min_assets = array();
96
97
	public $plugins_to_deactivate = array(
98
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
99
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
100
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
101
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
102
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
103
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
104
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
105
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
106
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
107
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
108
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
109
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
110
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
111
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
112
	);
113
114
	/**
115
	 * Map of roles we care about, and their corresponding minimum capabilities.
116
	 *
117
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
118
	 *
119
	 * @access public
120
	 * @static
121
	 *
122
	 * @var array
123
	 */
124
	public static $capability_translations = array(
125
		'administrator' => 'manage_options',
126
		'editor'        => 'edit_others_posts',
127
		'author'        => 'publish_posts',
128
		'contributor'   => 'edit_posts',
129
		'subscriber'    => 'read',
130
	);
131
132
	/**
133
	 * Map of modules that have conflicts with plugins and should not be auto-activated
134
	 * if the plugins are active.  Used by filter_default_modules
135
	 *
136
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
137
	 * change `module-slug` and add this to your plugin:
138
	 *
139
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
140
	 * function my_jetpack_get_default_modules( $modules ) {
141
	 *     return array_diff( $modules, array( 'module-slug' ) );
142
	 * }
143
	 *
144
	 * @var array
145
	 */
146
	private $conflicting_plugins = array(
147
		'comments'           => array(
148
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
149
			'Disqus'                         => 'disqus-comment-system/disqus.php',
150
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
151
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
152
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
153
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
154
		),
155
		'comment-likes'      => array(
156
			'Epoch' => 'epoch/plugincore.php',
157
		),
158
		'contact-form'       => array(
159
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
160
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
161
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
162
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
163
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
164
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
165
		),
166
		'latex'              => array(
167
			'LaTeX for WordPress'     => 'latex/latex.php',
168
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
169
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
170
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
171
			'Enable Latex'            => 'enable-latex/enable-latex.php',
172
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
173
		),
174
		'protect'            => array(
175
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
176
			'Captcha'                           => 'captcha/captcha.php',
177
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
178
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
179
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
180
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
181
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
182
			'Security-protection'               => 'security-protection/security-protection.php',
183
			'Login Security'                    => 'login-security/login-security.php',
184
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
185
			'Wordfence Security'                => 'wordfence/wordfence.php',
186
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
187
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
188
		),
189
		'random-redirect'    => array(
190
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
191
		),
192
		'related-posts'      => array(
193
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
194
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
195
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
196
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
197
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
198
			'outbrain'                    => 'outbrain/outbrain.php',
199
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
200
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
201
		),
202
		'sharedaddy'         => array(
203
			'AddThis'     => 'addthis/addthis_social_widget.php',
204
			'Add To Any'  => 'add-to-any/add-to-any.php',
205
			'ShareThis'   => 'share-this/sharethis.php',
206
			'Shareaholic' => 'shareaholic/shareaholic.php',
207
		),
208
		'seo-tools'          => array(
209
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
210
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
211
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
212
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
213
			'The SEO Framework'              => 'autodescription/autodescription.php',
214
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
215
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
216
		),
217
		'verification-tools' => array(
218
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
219
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
220
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
221
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
222
			'The SEO Framework'              => 'autodescription/autodescription.php',
223
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
224
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
225
		),
226
		'widget-visibility'  => array(
227
			'Widget Logic'    => 'widget-logic/widget_logic.php',
228
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
229
		),
230
		'sitemaps'           => array(
231
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
232
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
233
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
234
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
235
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
236
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
237
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
238
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
239
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
240
			'The SEO Framework'                    => 'autodescription/autodescription.php',
241
			'Sitemap'                              => 'sitemap/sitemap.php',
242
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
243
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
244
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
245
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
246
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
247
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
248
		),
249
		'lazy-images'        => array(
250
			'Lazy Load'              => 'lazy-load/lazy-load.php',
251
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
252
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
253
		),
254
	);
255
256
	/**
257
	 * Plugins for which we turn off our Facebook OG Tags implementation.
258
	 *
259
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
260
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
261
	 *
262
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
263
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
264
	 */
265
	private $open_graph_conflicting_plugins = array(
266
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
267
		// 2 Click Social Media Buttons
268
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
269
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
270
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
271
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
272
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
273
		// Open Graph Meta Tags by Heateor
274
		'facebook/facebook.php',                                 // Facebook (official plugin)
275
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
276
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
277
		// Facebook Featured Image & OG Meta Tags
278
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
279
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
280
		// Facebook Open Graph Meta Tags for WordPress
281
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
282
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
283
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
284
		// Fedmich's Facebook Open Graph Meta
285
		'network-publisher/networkpub.php',                      // Network Publisher
286
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
287
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
288
		// NextScripts SNAP
289
		'og-tags/og-tags.php',                                   // OG Tags
290
		'opengraph/opengraph.php',                               // Open Graph
291
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
292
		// Open Graph Protocol Framework
293
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
294
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
295
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
296
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
297
		'sharepress/sharepress.php',                             // SharePress
298
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
299
		'social-discussions/social-discussions.php',             // Social Discussions
300
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
301
		'socialize/socialize.php',                               // Socialize
302
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
303
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
304
		// Tweet, Like, Google +1 and Share
305
		'wordbooker/wordbooker.php',                             // Wordbooker
306
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
307
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
308
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
309
		// WP Facebook Like Send & Open Graph Meta
310
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
311
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
312
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
313
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
314
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
315
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
316
		'slim-seo/slim-seo.php',                                 // Slim SEO
317
	);
318
319
	/**
320
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
321
	 */
322
	private $twitter_cards_conflicting_plugins = array(
323
		// 'twitter/twitter.php',                       // The official one handles this on its own.
324
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
325
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
326
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
327
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
328
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
329
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
330
		'twitter-cards/twitter-cards.php',           // Twitter Cards
331
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
332
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
333
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
334
		'seo-by-rank-math/rank-math.php',            // Rank Math.
335
		'slim-seo/slim-seo.php',                     // Slim SEO
336
	);
337
338
	/**
339
	 * Message to display in admin_notice
340
	 *
341
	 * @var string
342
	 */
343
	public $message = '';
344
345
	/**
346
	 * Error to display in admin_notice
347
	 *
348
	 * @var string
349
	 */
350
	public $error = '';
351
352
	/**
353
	 * Modules that need more privacy description.
354
	 *
355
	 * @var string
356
	 */
357
	public $privacy_checks = '';
358
359
	/**
360
	 * Stats to record once the page loads
361
	 *
362
	 * @var array
363
	 */
364
	public $stats = array();
365
366
	/**
367
	 * Jetpack_Sync object
368
	 */
369
	public $sync;
370
371
	/**
372
	 * Verified data for JSON authorization request
373
	 */
374
	public $json_api_authorization_request = array();
375
376
	/**
377
	 * @var Automattic\Jetpack\Connection\Manager
378
	 */
379
	protected $connection_manager;
380
381
	/**
382
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
383
	 */
384
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
385
386
	/**
387
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
388
	 *
389
	 * @var Automattic\Jetpack\A8c_Mc_Stats
390
	 */
391
	public $a8c_mc_stats_instance;
392
393
	/**
394
	 * Constant for login redirect key.
395
	 *
396
	 * @var string
397
	 * @since 8.4.0
398
	 */
399
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
400
401
	/**
402
	 * Holds the singleton instance of this class
403
	 *
404
	 * @since 2.3.3
405
	 * @var Jetpack
406
	 */
407
	static $instance = false;
408
409
	/**
410
	 * Singleton
411
	 *
412
	 * @static
413
	 */
414
	public static function init() {
415
		if ( ! self::$instance ) {
416
			self::$instance = new Jetpack();
417
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
418
		}
419
420
		return self::$instance;
421
	}
422
423
	/**
424
	 * Must never be called statically
425
	 */
426
	function plugin_upgrade() {
427
		if ( self::is_active() ) {
428
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
429
			if ( JETPACK__VERSION != $version ) {
430
				// Prevent multiple upgrades at once - only a single process should trigger
431
				// an upgrade to avoid stampedes
432
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
433
					return;
434
				}
435
436
				// Set a short lock to prevent multiple instances of the upgrade
437
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
438
439
				// check which active modules actually exist and remove others from active_modules list
440
				$unfiltered_modules = self::get_active_modules();
441
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
442
				if ( array_diff( $unfiltered_modules, $modules ) ) {
443
					self::update_active_modules( $modules );
444
				}
445
446
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
447
448
				// Upgrade to 4.3.0
449
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
450
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
451
				}
452
453
				// Make sure Markdown for posts gets turned back on
454
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
455
					update_option( 'wpcom_publish_posts_with_markdown', true );
456
				}
457
458
				/*
459
				 * Minileven deprecation. 8.3.0.
460
				 * Only delete options if not using
461
				 * the replacement standalone Minileven plugin.
462
				 */
463
				if (
464
					! self::is_plugin_active( 'minileven-master/minileven.php' )
465
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
466
				) {
467
					if ( get_option( 'wp_mobile_custom_css' ) ) {
468
						delete_option( 'wp_mobile_custom_css' );
469
					}
470
					if ( get_option( 'wp_mobile_excerpt' ) ) {
471
						delete_option( 'wp_mobile_excerpt' );
472
					}
473
					if ( get_option( 'wp_mobile_featured_images' ) ) {
474
						delete_option( 'wp_mobile_featured_images' );
475
					}
476
					if ( get_option( 'wp_mobile_app_promos' ) ) {
477
						delete_option( 'wp_mobile_app_promos' );
478
					}
479
				}
480
481
				// Upgrade to 8.4.0.
482
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
483
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
484
				}
485
486
				// Update to 8.8.x (WordPress 5.5 Compatibility).
487
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
488
					$updated = update_site_option(
489
						'auto_update_plugins',
490
						array_unique(
491
							array_merge(
492
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
493
								(array) get_site_option( 'auto_update_plugins', array() )
494
							)
495
						)
496
					);
497
498
					if ( $updated ) {
499
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
500
					} // Should we have some type of fallback if something fails here?
501
				}
502
503
				if ( did_action( 'wp_loaded' ) ) {
504
					self::upgrade_on_load();
505
				} else {
506
					add_action(
507
						'wp_loaded',
508
						array( __CLASS__, 'upgrade_on_load' )
509
					);
510
				}
511
			}
512
		}
513
	}
514
515
	/**
516
	 * Runs upgrade routines that need to have modules loaded.
517
	 */
518
	static function upgrade_on_load() {
519
520
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
521
		// This can happen in case Jetpack has been just upgraded and is
522
		// being initialized late during the page load. In this case we wait
523
		// until the next proper admin page load with Jetpack active.
524
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
525
			delete_transient( self::$plugin_upgrade_lock_key );
526
527
			return;
528
		}
529
530
		self::maybe_set_version_option();
531
532
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
533
			Jetpack_Widget_Conditions::migrate_post_type_rules();
534
		}
535
536
		if (
537
			class_exists( 'Jetpack_Sitemap_Manager' )
538
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
539
		) {
540
			do_action( 'jetpack_sitemaps_purge_data' );
541
		}
542
543
		// Delete old stats cache
544
		delete_option( 'jetpack_restapi_stats_cache' );
545
546
		delete_transient( self::$plugin_upgrade_lock_key );
547
	}
548
549
	/**
550
	 * Saves all the currently active modules to options.
551
	 * Also fires Action hooks for each newly activated and deactivated module.
552
	 *
553
	 * @param $modules Array Array of active modules to be saved in options.
554
	 *
555
	 * @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...
556
	 */
557
	static function update_active_modules( $modules ) {
558
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
559
		$active_modules       = self::get_active_modules();
560
		$new_active_modules   = array_diff( $modules, $current_modules );
561
		$new_inactive_modules = array_diff( $active_modules, $modules );
562
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
563
		$reindexed_modules    = array_values( $new_current_modules );
564
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
565
566
		foreach ( $new_active_modules as $module ) {
567
			/**
568
			 * Fires when a specific module is activated.
569
			 *
570
			 * @since 1.9.0
571
			 *
572
			 * @param string $module Module slug.
573
			 * @param boolean $success whether the module was activated. @since 4.2
574
			 */
575
			do_action( 'jetpack_activate_module', $module, $success );
576
			/**
577
			 * Fires when a module is activated.
578
			 * The dynamic part of the filter, $module, is the module slug.
579
			 *
580
			 * @since 1.9.0
581
			 *
582
			 * @param string $module Module slug.
583
			 */
584
			do_action( "jetpack_activate_module_$module", $module );
585
		}
586
587
		foreach ( $new_inactive_modules as $module ) {
588
			/**
589
			 * Fired after a module has been deactivated.
590
			 *
591
			 * @since 4.2.0
592
			 *
593
			 * @param string $module Module slug.
594
			 * @param boolean $success whether the module was deactivated.
595
			 */
596
			do_action( 'jetpack_deactivate_module', $module, $success );
597
			/**
598
			 * Fires when a module is deactivated.
599
			 * The dynamic part of the filter, $module, is the module slug.
600
			 *
601
			 * @since 1.9.0
602
			 *
603
			 * @param string $module Module slug.
604
			 */
605
			do_action( "jetpack_deactivate_module_$module", $module );
606
		}
607
608
		return $success;
609
	}
610
611
	static function delete_active_modules() {
612
		self::update_active_modules( array() );
613
	}
614
615
	/**
616
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
617
	 * available.
618
	 */
619
	public function add_configure_hook() {
620
		global $wp_filter;
621
622
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
623
		if ( false !== $current_priority ) {
624
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
625
		}
626
627
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
628
		sort( $taken_priorities );
629
630
		$first_priority = array_shift( $taken_priorities );
631
632
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
633
			$new_priority = - PHP_INT_MAX;
634
		} else {
635
			$new_priority = $first_priority - 1;
636
		}
637
638
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
639
	}
640
641
	/**
642
	 * Constructor.  Initializes WordPress hooks
643
	 */
644
	private function __construct() {
645
		/*
646
		 * Check for and alert any deprecated hooks
647
		 */
648
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
649
650
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
651
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
652
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
653
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
654
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
655
656
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
657
658
		add_filter(
659
			'jetpack_signature_check_token',
660
			array( __CLASS__, 'verify_onboarding_token' ),
661
			10,
662
			3
663
		);
664
665
		/**
666
		 * Prepare Gutenberg Editor functionality
667
		 */
668
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
669
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
670
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
671
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
672
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
673
674
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
675
676
		// Unlink user before deleting the user from WP.com.
677
		add_action( 'deleted_user', array( $this, 'disconnect_user' ), 10, 1 );
678
		add_action( 'remove_user_from_blog', array( $this, 'disconnect_user' ), 10, 1 );
679
680
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
681
682
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
683
		add_action( 'login_init', array( $this, 'login_init' ) );
684
685
		// Set up the REST authentication hooks.
686
		Connection_Rest_Authentication::init();
687
688
		add_action( 'admin_init', array( $this, 'admin_init' ) );
689
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
690
691
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
692
693
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
694
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
695
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
696
697
		// returns HTTPS support status
698
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
699
700
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
701
702
		add_action( 'wp_ajax_jetpack_recommendations_banner', array( 'Jetpack_Recommendations_Banner', 'ajax_callback' ) );
703
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
704
705
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
706
707
		/**
708
		 * These actions run checks to load additional files.
709
		 * They check for external files or plugins, so they need to run as late as possible.
710
		 */
711
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
712
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
713
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
714
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
715
716
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
717
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
718
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
719
720
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
721
722
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
723
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
724
725
		// A filter to control all just in time messages
726
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
727
728
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
729
730
		/*
731
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
732
		 * We should make sure to only do this for front end links.
733
		 */
734
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
735
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
736
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
737
738
			/*
739
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
740
			 * so they point moderation links on emails to Calypso.
741
			 */
742
			jetpack_require_lib( 'functions.wp-notify' );
743
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
744
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
745
		}
746
747
		add_action(
748
			'plugins_loaded',
749
			function () {
750
				if ( User_Agent_Info::is_mobile_app() ) {
751
					add_filter( 'get_edit_post_link', '__return_empty_string' );
752
				}
753
			}
754
		);
755
756
		// Update the site's Jetpack plan and products from API on heartbeats.
757
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
758
759
		/**
760
		 * This is the hack to concatenate all css files into one.
761
		 * For description and reasoning see the implode_frontend_css method.
762
		 *
763
		 * Super late priority so we catch all the registered styles.
764
		 */
765
		if ( ! is_admin() ) {
766
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
767
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
768
		}
769
770
		/**
771
		 * These are sync actions that we need to keep track of for jitms
772
		 */
773
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
774
775
		// Actually push the stats on shutdown.
776
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
777
			add_action( 'shutdown', array( $this, 'push_stats' ) );
778
		}
779
780
		// Actions for Manager::authorize().
781
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
782
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
783
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
784
785
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
786
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
787
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
788
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
789
790
		// Filters for the Manager::get_token() urls and request body.
791
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
792
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
793
794
		// Actions for successful reconnect.
795
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
796
797
		// Actions for licensing.
798
		Licensing::instance()->initialize();
799
800
		// Filters for Sync Callables.
801
		add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
802
803
		// Make resources use static domain when possible.
804
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
805
	}
806
807
	/**
808
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
809
	 * Config object.
810
	 */
811
	public function configure() {
812
		$config = new Config();
813
814
		foreach (
815
			array(
816
				'sync',
817
			)
818
			as $feature
819
		) {
820
			$config->ensure( $feature );
821
		}
822
823
		$config->ensure(
824
			'connection',
825
			array(
826
				'slug' => 'jetpack',
827
				'name' => 'Jetpack',
828
			)
829
		);
830
831
		if ( is_admin() ) {
832
			$config->ensure( 'jitm' );
833
		}
834
835
		if ( ! $this->connection_manager ) {
836
			$this->connection_manager = new Connection_Manager( 'jetpack' );
837
838
			/**
839
			 * Filter to activate Jetpack Connection UI.
840
			 * INTERNAL USE ONLY.
841
			 *
842
			 * @since 9.5.0
843
			 *
844
			 * @param bool false Whether to activate the Connection UI.
845
			 */
846
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
847
				Automattic\Jetpack\ConnectionUI\Admin::init();
848
			}
849
		}
850
851
		/*
852
		 * Load things that should only be in Network Admin.
853
		 *
854
		 * For now blow away everything else until a more full
855
		 * understanding of what is needed at the network level is
856
		 * available
857
		 */
858
		if ( is_multisite() ) {
859
			$network = Jetpack_Network::init();
860
			$network->set_connection( $this->connection_manager );
861
		}
862
863
		if ( $this->connection_manager->is_active() ) {
864
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
865
866
			Jetpack_Heartbeat::init();
867
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
868
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
869
				Jetpack_Search_Performance_Logger::init();
870
			}
871
		}
872
873
		// Initialize remote file upload request handlers.
874
		$this->add_remote_request_handlers();
875
876
		/*
877
		 * Enable enhanced handling of previewing sites in Calypso
878
		 */
879
		if ( self::is_active() ) {
880
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
881
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
882
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
883
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
884
		}
885
886
		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...
887
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
888
		} else {
889
			/**
890
			 * Initialize tracking right after the user agrees to the terms of service.
891
			 */
892
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
893
		}
894
	}
895
896
	/**
897
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
898
	 * initialization code.
899
	 *
900
	 * @action plugins_loaded
901
	 */
902
	public function late_initialization() {
903
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
904
905
		Partner::init();
906
907
		/**
908
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
909
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
910
		 *
911
		 * @since 8.1.0
912
		 *
913
		 * @param Jetpack $jetpack the main plugin class object.
914
		 */
915
		do_action( 'jetpack_loaded', $this );
916
917
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
918
	}
919
920
	/**
921
	 * Sets up the XMLRPC request handlers.
922
	 *
923
	 * @deprecated since 7.7.0
924
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
925
	 *
926
	 * @param array                 $request_params Incoming request parameters.
927
	 * @param Boolean               $is_active      Whether the connection is currently active.
928
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
929
	 * @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...
930
	 */
931 View Code Duplication
	public function setup_xmlrpc_handlers(
932
		$request_params,
933
		$is_active,
934
		$is_signed,
935
		Jetpack_XMLRPC_Server $xmlrpc_server = null
936
	) {
937
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
938
939
		if ( ! $this->connection_manager ) {
940
			$this->connection_manager = new Connection_Manager();
941
		}
942
943
		return $this->connection_manager->setup_xmlrpc_handlers(
944
			$request_params,
945
			$is_active,
946
			$is_signed,
947
			$xmlrpc_server
948
		);
949
	}
950
951
	/**
952
	 * Initialize REST API registration connector.
953
	 *
954
	 * @deprecated since 7.7.0
955
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
956
	 */
957 View Code Duplication
	public function initialize_rest_api_registration_connector() {
958
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
959
960
		if ( ! $this->connection_manager ) {
961
			$this->connection_manager = new Connection_Manager();
962
		}
963
964
		$this->connection_manager->initialize_rest_api_registration_connector();
965
	}
966
967
	/**
968
	 * This is ported over from the manage module, which has been deprecated and baked in here.
969
	 *
970
	 * @param $domains
971
	 */
972
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
973
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
974
	}
975
976
	/**
977
	 * Return $domains, with 'wordpress.com' appended.
978
	 * This is ported over from the manage module, which has been deprecated and baked in here.
979
	 *
980
	 * @param $domains
981
	 * @return array
982
	 */
983
	function allow_wpcom_domain( $domains ) {
984
		if ( empty( $domains ) ) {
985
			$domains = array();
986
		}
987
		$domains[] = 'wordpress.com';
988
		return array_unique( $domains );
989
	}
990
991
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
992
		$post = get_post( $post_id );
993
994
		if ( empty( $post ) ) {
995
			return $default_url;
996
		}
997
998
		$post_type = $post->post_type;
999
1000
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1001
		// https://en.support.wordpress.com/custom-post-types/
1002
		$allowed_post_types = array(
1003
			'post',
1004
			'page',
1005
			'jetpack-portfolio',
1006
			'jetpack-testimonial',
1007
		);
1008
1009
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1010
			return $default_url;
1011
		}
1012
1013
		return Redirect::get_url(
1014
			'calypso-edit-' . $post_type,
1015
			array(
1016
				'path' => $post_id,
1017
			)
1018
		);
1019
	}
1020
1021
	function point_edit_comment_links_to_calypso( $url ) {
1022
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1023
		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...
1024
1025
		return Redirect::get_url(
1026
			'calypso-edit-comment',
1027
			array(
1028
				'path' => $query_args['amp;c'],
1029
			)
1030
		);
1031
1032
	}
1033
1034
	/**
1035
	 * Extend callables with Jetpack Plugin functions.
1036
	 *
1037
	 * @param array $callables list of callables.
1038
	 *
1039
	 * @return array list of callables.
1040
	 */
1041
	public function filter_sync_callable_whitelist( $callables ) {
1042
1043
		// Jetpack Functions.
1044
		$jetpack_callables = array(
1045
			'single_user_site'         => array( 'Jetpack', 'is_single_user_site' ),
1046
			'updates'                  => array( 'Jetpack', 'get_updates' ),
1047
			'active_modules'           => array( 'Jetpack', 'get_active_modules' ),
1048
			'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1049
		);
1050
		$callables         = array_merge( $callables, $jetpack_callables );
1051
1052
		// Jetpack_SSO_Helpers.
1053
		if ( include_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php' ) {
1054
			$sso_helpers = array(
1055
				'sso_is_two_step_required'      => array( 'Jetpack_SSO_Helpers', 'is_two_step_required' ),
1056
				'sso_should_hide_login_form'    => array( 'Jetpack_SSO_Helpers', 'should_hide_login_form' ),
1057
				'sso_match_by_email'            => array( 'Jetpack_SSO_Helpers', 'match_by_email' ),
1058
				'sso_new_user_override'         => array( 'Jetpack_SSO_Helpers', 'new_user_override' ),
1059
				'sso_bypass_default_login_form' => array( 'Jetpack_SSO_Helpers', 'bypass_login_forward_wpcom' ),
1060
			);
1061
			$callables   = array_merge( $callables, $sso_helpers );
1062
		}
1063
1064
		return $callables;
1065
	}
1066
1067
	function jetpack_track_last_sync_callback( $params ) {
1068
		/**
1069
		 * Filter to turn off jitm caching
1070
		 *
1071
		 * @since 5.4.0
1072
		 *
1073
		 * @param bool false Whether to cache just in time messages
1074
		 */
1075
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1076
			return $params;
1077
		}
1078
1079
		if ( is_array( $params ) && isset( $params[0] ) ) {
1080
			$option = $params[0];
1081
			if ( 'active_plugins' === $option ) {
1082
				// use the cache if we can, but not terribly important if it gets evicted
1083
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1084
			}
1085
		}
1086
1087
		return $params;
1088
	}
1089
1090
	function jetpack_connection_banner_callback() {
1091
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1092
1093
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1094
		if (
1095
			isset( $_REQUEST['dismissBanner'] ) &&
1096
			! Jetpack_Connection_Banner::force_display()
1097
		) {
1098
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1099
			wp_send_json_success();
1100
		}
1101
1102
		wp_die();
1103
	}
1104
1105
	/**
1106
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1107
	 * Only used in our alternate XML-RPC endpoint, where we want to
1108
	 * ensure that Core and other plugins' methods are not exposed.
1109
	 *
1110
	 * @deprecated since 7.7.0
1111
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1112
	 *
1113
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1114
	 * @return array Filtered $methods
1115
	 */
1116 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1117
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1118
1119
		if ( ! $this->connection_manager ) {
1120
			$this->connection_manager = new Connection_Manager();
1121
		}
1122
1123
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1124
	}
1125
1126
	/**
1127
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1128
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1129
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1130
	 * which is accessible via a different URI. Most of the below is copied directly
1131
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1132
	 *
1133
	 * @deprecated since 7.7.0
1134
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1135
	 */
1136 View Code Duplication
	public function alternate_xmlrpc() {
1137
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1138
1139
		if ( ! $this->connection_manager ) {
1140
			$this->connection_manager = new Connection_Manager();
1141
		}
1142
1143
		$this->connection_manager->alternate_xmlrpc();
1144
	}
1145
1146
	/**
1147
	 * The callback for the JITM ajax requests.
1148
	 *
1149
	 * @deprecated since 7.9.0
1150
	 */
1151
	function jetpack_jitm_ajax_callback() {
1152
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1153
	}
1154
1155
	/**
1156
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1157
	 */
1158
	function push_stats() {
1159
		if ( ! empty( $this->stats ) ) {
1160
			$this->do_stats( 'server_side' );
1161
		}
1162
	}
1163
1164
	/**
1165
	 * Sets the Jetpack custom capabilities.
1166
	 *
1167
	 * @param string[] $caps    Array of the user's capabilities.
1168
	 * @param string   $cap     Capability name.
1169
	 * @param int      $user_id The user ID.
1170
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1171
	 */
1172
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1173
		$is_offline_mode = ( new Status() )->is_offline_mode();
1174
		switch ( $cap ) {
1175
			case 'jetpack_manage_modules':
1176
			case 'jetpack_activate_modules':
1177
			case 'jetpack_deactivate_modules':
1178
				$caps = array( 'manage_options' );
1179
				break;
1180
			case 'jetpack_configure_modules':
1181
				$caps = array( 'manage_options' );
1182
				break;
1183
			case 'jetpack_manage_autoupdates':
1184
				$caps = array(
1185
					'manage_options',
1186
					'update_plugins',
1187
				);
1188
				break;
1189
			case 'jetpack_network_admin_page':
1190
			case 'jetpack_network_settings_page':
1191
				$caps = array( 'manage_network_plugins' );
1192
				break;
1193
			case 'jetpack_network_sites_page':
1194
				$caps = array( 'manage_sites' );
1195
				break;
1196
			case 'jetpack_admin_page':
1197
				if ( $is_offline_mode ) {
1198
					$caps = array( 'manage_options' );
1199
					break;
1200
				} else {
1201
					$caps = array( 'read' );
1202
				}
1203
				break;
1204
		}
1205
		return $caps;
1206
	}
1207
1208
	/**
1209
	 * Require a Jetpack authentication.
1210
	 *
1211
	 * @deprecated since 7.7.0
1212
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1213
	 */
1214 View Code Duplication
	public function require_jetpack_authentication() {
1215
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1216
1217
		if ( ! $this->connection_manager ) {
1218
			$this->connection_manager = new Connection_Manager();
1219
		}
1220
1221
		$this->connection_manager->require_jetpack_authentication();
1222
	}
1223
1224
	/**
1225
	 * Register assets for use in various modules and the Jetpack admin page.
1226
	 *
1227
	 * @uses wp_script_is, wp_register_script, plugins_url
1228
	 * @action wp_loaded
1229
	 * @return null
1230
	 */
1231
	public function register_assets() {
1232 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1233
			wp_register_script(
1234
				'jetpack-gallery-settings',
1235
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1236
				array( 'media-views' ),
1237
				'20121225'
1238
			);
1239
		}
1240
1241
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1242
			wp_register_script(
1243
				'jetpack-twitter-timeline',
1244
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1245
				array( 'jquery' ),
1246
				'4.0.0',
1247
				true
1248
			);
1249
		}
1250
1251
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1252
			wp_register_script(
1253
				'jetpack-facebook-embed',
1254
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1255
				array(),
1256
				null,
1257
				true
1258
			);
1259
1260
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1261
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1262
			if ( ! is_numeric( $fb_app_id ) ) {
1263
				$fb_app_id = '';
1264
			}
1265
			wp_localize_script(
1266
				'jetpack-facebook-embed',
1267
				'jpfbembed',
1268
				array(
1269
					'appid'  => $fb_app_id,
1270
					'locale' => $this->get_locale(),
1271
				)
1272
			);
1273
		}
1274
1275
		/**
1276
		 * As jetpack_register_genericons is by default fired off a hook,
1277
		 * the hook may have already fired by this point.
1278
		 * So, let's just trigger it manually.
1279
		 */
1280
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1281
		jetpack_register_genericons();
1282
1283
		/**
1284
		 * Register the social logos
1285
		 */
1286
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1287
		jetpack_register_social_logos();
1288
1289 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1290
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1291
		}
1292
	}
1293
1294
	/**
1295
	 * Guess locale from language code.
1296
	 *
1297
	 * @param string $lang Language code.
1298
	 * @return string|bool
1299
	 */
1300 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1301
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1302
			return 'en_US';
1303
		}
1304
1305
		if ( ! class_exists( 'GP_Locales' ) ) {
1306
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1307
				return false;
1308
			}
1309
1310
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1311
		}
1312
1313
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1314
			// WP.com: get_locale() returns 'it'
1315
			$locale = GP_Locales::by_slug( $lang );
1316
		} else {
1317
			// Jetpack: get_locale() returns 'it_IT';
1318
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1319
		}
1320
1321
		if ( ! $locale ) {
1322
			return false;
1323
		}
1324
1325
		if ( empty( $locale->facebook_locale ) ) {
1326
			if ( empty( $locale->wp_locale ) ) {
1327
				return false;
1328
			} else {
1329
				// Facebook SDK is smart enough to fall back to en_US if a
1330
				// locale isn't supported. Since supported Facebook locales
1331
				// can fall out of sync, we'll attempt to use the known
1332
				// wp_locale value and rely on said fallback.
1333
				return $locale->wp_locale;
1334
			}
1335
		}
1336
1337
		return $locale->facebook_locale;
1338
	}
1339
1340
	/**
1341
	 * Get the locale.
1342
	 *
1343
	 * @return string|bool
1344
	 */
1345
	function get_locale() {
1346
		$locale = $this->guess_locale_from_lang( get_locale() );
1347
1348
		if ( ! $locale ) {
1349
			$locale = 'en_US';
1350
		}
1351
1352
		return $locale;
1353
	}
1354
1355
	/**
1356
	 * Return the network_site_url so that .com knows what network this site is a part of.
1357
	 *
1358
	 * @param  bool $option
1359
	 * @return string
1360
	 */
1361
	public function jetpack_main_network_site_option( $option ) {
1362
		return network_site_url();
1363
	}
1364
	/**
1365
	 * Network Name.
1366
	 */
1367
	static function network_name( $option = null ) {
1368
		global $current_site;
1369
		return $current_site->site_name;
1370
	}
1371
	/**
1372
	 * Does the network allow new user and site registrations.
1373
	 *
1374
	 * @return string
1375
	 */
1376
	static function network_allow_new_registrations( $option = null ) {
1377
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1378
	}
1379
	/**
1380
	 * Does the network allow admins to add new users.
1381
	 *
1382
	 * @return boolian
1383
	 */
1384
	static function network_add_new_users( $option = null ) {
1385
		return (bool) get_site_option( 'add_new_users' );
1386
	}
1387
	/**
1388
	 * File upload psace left per site in MB.
1389
	 *  -1 means NO LIMIT.
1390
	 *
1391
	 * @return number
1392
	 */
1393
	static function network_site_upload_space( $option = null ) {
1394
		// value in MB
1395
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1396
	}
1397
1398
	/**
1399
	 * Network allowed file types.
1400
	 *
1401
	 * @return string
1402
	 */
1403
	static function network_upload_file_types( $option = null ) {
1404
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1405
	}
1406
1407
	/**
1408
	 * Maximum file upload size set by the network.
1409
	 *
1410
	 * @return number
1411
	 */
1412
	static function network_max_upload_file_size( $option = null ) {
1413
		// value in KB
1414
		return get_site_option( 'fileupload_maxk', 300 );
1415
	}
1416
1417
	/**
1418
	 * Lets us know if a site allows admins to manage the network.
1419
	 *
1420
	 * @return array
1421
	 */
1422
	static function network_enable_administration_menus( $option = null ) {
1423
		return get_site_option( 'menu_items' );
1424
	}
1425
1426
	/**
1427
	 * If a user has been promoted to or demoted from admin, we need to clear the
1428
	 * jetpack_other_linked_admins transient.
1429
	 *
1430
	 * @since 4.3.2
1431
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1432
	 *
1433
	 * @param int    $user_id   The user ID whose role changed.
1434
	 * @param string $role      The new role.
1435
	 * @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...
1436
	 */
1437
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1438
		if ( 'administrator' == $role
1439
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1440
			|| is_null( $old_roles )
1441
		) {
1442
			delete_transient( 'jetpack_other_linked_admins' );
1443
		}
1444
	}
1445
1446
	/**
1447
	 * Checks to see if there are any other users available to become primary
1448
	 * Users must both:
1449
	 * - Be linked to wpcom
1450
	 * - Be an admin
1451
	 *
1452
	 * @return mixed False if no other users are linked, Int if there are.
1453
	 */
1454
	static function get_other_linked_admins() {
1455
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1456
1457
		if ( false === $other_linked_users ) {
1458
			$admins = get_users( array( 'role' => 'administrator' ) );
1459
			if ( count( $admins ) > 1 ) {
1460
				$available = array();
1461
				foreach ( $admins as $admin ) {
1462
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1463
						$available[] = $admin->ID;
1464
					}
1465
				}
1466
1467
				$count_connected_admins = count( $available );
1468
				if ( count( $available ) > 1 ) {
1469
					$other_linked_users = $count_connected_admins;
1470
				} else {
1471
					$other_linked_users = 0;
1472
				}
1473
			} else {
1474
				$other_linked_users = 0;
1475
			}
1476
1477
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1478
		}
1479
1480
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1481
	}
1482
1483
	/**
1484
	 * Return whether we are dealing with a multi network setup or not.
1485
	 * The reason we are type casting this is because we want to avoid the situation where
1486
	 * the result is false since when is_main_network_option return false it cases
1487
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1488
	 * database which could be set to anything as opposed to what this function returns.
1489
	 *
1490
	 * @param  bool $option
1491
	 *
1492
	 * @return boolean
1493
	 */
1494
	public function is_main_network_option( $option ) {
1495
		// return '1' or ''
1496
		return (string) (bool) self::is_multi_network();
1497
	}
1498
1499
	/**
1500
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1501
	 *
1502
	 * @param  string $option
1503
	 * @return boolean
1504
	 */
1505
	public function is_multisite( $option ) {
1506
		return (string) (bool) is_multisite();
1507
	}
1508
1509
	/**
1510
	 * Implemented since there is no core is multi network function
1511
	 * Right now there is no way to tell if we which network is the dominant network on the system
1512
	 *
1513
	 * @since  3.3
1514
	 * @return boolean
1515
	 */
1516 View Code Duplication
	public static function is_multi_network() {
1517
		global  $wpdb;
1518
1519
		// if we don't have a multi site setup no need to do any more
1520
		if ( ! is_multisite() ) {
1521
			return false;
1522
		}
1523
1524
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1525
		if ( $num_sites > 1 ) {
1526
			return true;
1527
		} else {
1528
			return false;
1529
		}
1530
	}
1531
1532
	/**
1533
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1534
	 *
1535
	 * @return null
1536
	 */
1537
	function update_jetpack_main_network_site_option() {
1538
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1539
	}
1540
	/**
1541
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1542
	 */
1543
	function update_jetpack_network_settings() {
1544
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1545
		// Only sync this info for the main network site.
1546
	}
1547
1548
	/**
1549
	 * Get back if the current site is single user site.
1550
	 *
1551
	 * @return bool
1552
	 */
1553 View Code Duplication
	public static function is_single_user_site() {
1554
		global $wpdb;
1555
1556
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1557
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1558
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1559
		}
1560
		return 1 === (int) $some_users;
1561
	}
1562
1563
	/**
1564
	 * Returns true if the site has file write access false otherwise.
1565
	 *
1566
	 * @return string ( '1' | '0' )
1567
	 **/
1568
	public static function file_system_write_access() {
1569
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1570
			require_once ABSPATH . 'wp-admin/includes/file.php';
1571
		}
1572
1573
		require_once ABSPATH . 'wp-admin/includes/template.php';
1574
1575
		$filesystem_method = get_filesystem_method();
1576
		if ( $filesystem_method === 'direct' ) {
1577
			return 1;
1578
		}
1579
1580
		ob_start();
1581
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1582
		ob_end_clean();
1583
		if ( $filesystem_credentials_are_stored ) {
1584
			return 1;
1585
		}
1586
		return 0;
1587
	}
1588
1589
	/**
1590
	 * Finds out if a site is using a version control system.
1591
	 *
1592
	 * @return string ( '1' | '0' )
1593
	 **/
1594
	public static function is_version_controlled() {
1595
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1596
		return (string) (int) Functions::is_version_controlled();
1597
	}
1598
1599
	/**
1600
	 * Determines whether the current theme supports featured images or not.
1601
	 *
1602
	 * @return string ( '1' | '0' )
1603
	 */
1604
	public static function featured_images_enabled() {
1605
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1606
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1607
	}
1608
1609
	/**
1610
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1611
	 *
1612
	 * @deprecated 4.7 use get_avatar_url instead.
1613
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1614
	 * @param int               $size Size of the avatar image
1615
	 * @param string            $default URL to a default image to use if no avatar is available
1616
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1617
	 *
1618
	 * @return array
1619
	 */
1620
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1621
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1622
		return get_avatar_url(
1623
			$id_or_email,
1624
			array(
1625
				'size'          => $size,
1626
				'default'       => $default,
1627
				'force_default' => $force_display,
1628
			)
1629
		);
1630
	}
1631
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1632
	/**
1633
	 * jetpack_updates is saved in the following schema:
1634
	 *
1635
	 * array (
1636
	 *      'plugins'                       => (int) Number of plugin updates available.
1637
	 *      'themes'                        => (int) Number of theme updates available.
1638
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1639
	 *      'translations'                  => (int) Number of translation updates available.
1640
	 *      'total'                         => (int) Total of all available updates.
1641
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1642
	 * )
1643
	 *
1644
	 * @return array
1645
	 */
1646
	public static function get_updates() {
1647
		$update_data = wp_get_update_data();
1648
1649
		// Stores the individual update counts as well as the total count.
1650
		if ( isset( $update_data['counts'] ) ) {
1651
			$updates = $update_data['counts'];
1652
		}
1653
1654
		// If we need to update WordPress core, let's find the latest version number.
1655 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1656
			$cur = get_preferred_from_update_core();
1657
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1658
				$updates['wp_update_version'] = $cur->current;
1659
			}
1660
		}
1661
		return isset( $updates ) ? $updates : array();
1662
	}
1663
	// phpcs:enable
1664
1665
	public static function get_update_details() {
1666
		$update_details = array(
1667
			'update_core'    => get_site_transient( 'update_core' ),
1668
			'update_plugins' => get_site_transient( 'update_plugins' ),
1669
			'update_themes'  => get_site_transient( 'update_themes' ),
1670
		);
1671
		return $update_details;
1672
	}
1673
1674
	public static function refresh_update_data() {
1675
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1676
1677
	}
1678
1679
	public static function refresh_theme_data() {
1680
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1681
	}
1682
1683
	/**
1684
	 * Is Jetpack active?
1685
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1686
	 *
1687
	 * @return bool
1688
	 */
1689
	public static function is_active() {
1690
		return self::connection()->is_active();
1691
	}
1692
1693
	/**
1694
	 * Make an API call to WordPress.com for plan status
1695
	 *
1696
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1697
	 *
1698
	 * @return bool True if plan is updated, false if no update
1699
	 */
1700
	public static function refresh_active_plan_from_wpcom() {
1701
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1702
		return Jetpack_Plan::refresh_from_wpcom();
1703
	}
1704
1705
	/**
1706
	 * Get the plan that this Jetpack site is currently using
1707
	 *
1708
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1709
	 * @return array Active Jetpack plan details.
1710
	 */
1711
	public static function get_active_plan() {
1712
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1713
		return Jetpack_Plan::get();
1714
	}
1715
1716
	/**
1717
	 * Determine whether the active plan supports a particular feature
1718
	 *
1719
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1720
	 * @return bool True if plan supports feature, false if not.
1721
	 */
1722
	public static function active_plan_supports( $feature ) {
1723
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1724
		return Jetpack_Plan::supports( $feature );
1725
	}
1726
1727
	/**
1728
	 * Deprecated: Is Jetpack in development (offline) mode?
1729
	 *
1730
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1731
	 * and themes still use it, and we do not want to flood them with notices.
1732
	 *
1733
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1734
	 *
1735
	 * @deprecated since 8.0.
1736
	 */
1737
	public static function is_development_mode() {
1738
		return ( new Status() )->is_offline_mode();
1739
	}
1740
1741
	/**
1742
	 * Whether the site is currently onboarding or not.
1743
	 * A site is considered as being onboarded if it currently has an onboarding token.
1744
	 *
1745
	 * @since 5.8
1746
	 *
1747
	 * @access public
1748
	 * @static
1749
	 *
1750
	 * @return bool True if the site is currently onboarding, false otherwise
1751
	 */
1752
	public static function is_onboarding() {
1753
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1754
	}
1755
1756
	/**
1757
	 * Determines reason for Jetpack offline mode.
1758
	 */
1759
	public static function development_mode_trigger_text() {
1760
		$status = new Status();
1761
1762
		if ( ! $status->is_offline_mode() ) {
1763
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1764
		}
1765
1766
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1767
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1768
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1769
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1770
		} elseif ( $status->is_local_site() ) {
1771
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1772
			/** This filter is documented in packages/status/src/class-status.php */
1773
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1774
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1775
		} else {
1776
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1777
		}
1778
1779
		return $notice;
1780
1781
	}
1782
	/**
1783
	 * Get Jetpack offline mode notice text and notice class.
1784
	 *
1785
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1786
	 */
1787
	public static function show_development_mode_notice() {
1788 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1789
			$notice = sprintf(
1790
				/* translators: %s is a URL */
1791
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1792
				Redirect::get_url( 'jetpack-support-development-mode' )
1793
			);
1794
1795
			$notice .= ' ' . self::development_mode_trigger_text();
1796
1797
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1798
		}
1799
1800
		// Throw up a notice if using a development version and as for feedback.
1801
		if ( self::is_development_version() ) {
1802
			/* translators: %s is a URL */
1803
			$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' ) );
1804
1805
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1806
		}
1807
		// Throw up a notice if using staging mode
1808 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1809
			/* translators: %s is a URL */
1810
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1811
1812
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1813
		}
1814
	}
1815
1816
	/**
1817
	 * Whether Jetpack's version maps to a public release, or a development version.
1818
	 */
1819
	public static function is_development_version() {
1820
		/**
1821
		 * Allows filtering whether this is a development version of Jetpack.
1822
		 *
1823
		 * This filter is especially useful for tests.
1824
		 *
1825
		 * @since 4.3.0
1826
		 *
1827
		 * @param bool $development_version Is this a develoment version of Jetpack?
1828
		 */
1829
		return (bool) apply_filters(
1830
			'jetpack_development_version',
1831
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1832
		);
1833
	}
1834
1835
	/**
1836
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1837
	 */
1838
	public static function is_user_connected( $user_id = false ) {
1839
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1840
		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...
1841
	}
1842
1843
	/**
1844
	 * Get the wpcom user data of the current|specified connected user.
1845
	 */
1846
	public static function get_connected_user_data( $user_id = null ) {
1847
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1848
		return self::connection()->get_connected_user_data( $user_id );
1849
	}
1850
1851
	/**
1852
	 * Get the wpcom email of the current|specified connected user.
1853
	 */
1854
	public static function get_connected_user_email( $user_id = null ) {
1855
		if ( ! $user_id ) {
1856
			$user_id = get_current_user_id();
1857
		}
1858
1859
		$xml = new Jetpack_IXR_Client(
1860
			array(
1861
				'user_id' => $user_id,
1862
			)
1863
		);
1864
		$xml->query( 'wpcom.getUserEmail' );
1865
		if ( ! $xml->isError() ) {
1866
			return $xml->getResponse();
1867
		}
1868
		return false;
1869
	}
1870
1871
	/**
1872
	 * Get the wpcom email of the master user.
1873
	 */
1874
	public static function get_master_user_email() {
1875
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1876
		if ( $master_user_id ) {
1877
			return self::get_connected_user_email( $master_user_id );
1878
		}
1879
		return '';
1880
	}
1881
1882
	/**
1883
	 * Whether the current user is the connection owner.
1884
	 *
1885
	 * @deprecated since 7.7
1886
	 *
1887
	 * @return bool Whether the current user is the connection owner.
1888
	 */
1889
	public function current_user_is_connection_owner() {
1890
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1891
		return self::connection()->is_connection_owner();
1892
	}
1893
1894
	/**
1895
	 * Gets current user IP address.
1896
	 *
1897
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1898
	 *
1899
	 * @return string                  Current user IP address.
1900
	 */
1901
	public static function current_user_ip( $check_all_headers = false ) {
1902
		if ( $check_all_headers ) {
1903
			foreach ( array(
1904
				'HTTP_CF_CONNECTING_IP',
1905
				'HTTP_CLIENT_IP',
1906
				'HTTP_X_FORWARDED_FOR',
1907
				'HTTP_X_FORWARDED',
1908
				'HTTP_X_CLUSTER_CLIENT_IP',
1909
				'HTTP_FORWARDED_FOR',
1910
				'HTTP_FORWARDED',
1911
				'HTTP_VIA',
1912
			) as $key ) {
1913
				if ( ! empty( $_SERVER[ $key ] ) ) {
1914
					return $_SERVER[ $key ];
1915
				}
1916
			}
1917
		}
1918
1919
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1920
	}
1921
1922
	/**
1923
	 * Synchronize connected user role changes
1924
	 */
1925
	function user_role_change( $user_id ) {
1926
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1927
		Users::user_role_change( $user_id );
1928
	}
1929
1930
	/**
1931
	 * Loads the currently active modules.
1932
	 */
1933
	public static function load_modules() {
1934
		$is_offline_mode = ( new Status() )->is_offline_mode();
1935
		if (
1936
			! self::is_active()
1937
			&& ! $is_offline_mode
1938
			&& ! self::is_onboarding()
1939
			&& (
1940
				! is_multisite()
1941
				|| ! get_site_option( 'jetpack_protect_active' )
1942
			)
1943
		) {
1944
			return;
1945
		}
1946
1947
		$version = Jetpack_Options::get_option( 'version' );
1948 View Code Duplication
		if ( ! $version ) {
1949
			$version = $old_version = JETPACK__VERSION . ':' . time();
1950
			/** This action is documented in class.jetpack.php */
1951
			do_action( 'updating_jetpack_version', $version, false );
1952
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1953
		}
1954
		list( $version ) = explode( ':', $version );
1955
1956
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1957
1958
		$modules_data = array();
1959
1960
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1961
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1962
			$updated_modules = array();
1963
			foreach ( $modules as $module ) {
1964
				$modules_data[ $module ] = self::get_module( $module );
1965
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1966
					continue;
1967
				}
1968
1969
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1970
					continue;
1971
				}
1972
1973
				$updated_modules[] = $module;
1974
			}
1975
1976
			$modules = array_diff( $modules, $updated_modules );
1977
		}
1978
1979
		foreach ( $modules as $index => $module ) {
1980
			// If we're in offline mode, disable modules requiring a connection.
1981
			if ( $is_offline_mode ) {
1982
				// Prime the pump if we need to
1983
				if ( empty( $modules_data[ $module ] ) ) {
1984
					$modules_data[ $module ] = self::get_module( $module );
1985
				}
1986
				// If the module requires a connection, but we're in local mode, don't include it.
1987
				if ( $modules_data[ $module ]['requires_connection'] ) {
1988
					continue;
1989
				}
1990
			}
1991
1992
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1993
				continue;
1994
			}
1995
1996
			if ( ! include_once self::get_module_path( $module ) ) {
1997
				unset( $modules[ $index ] );
1998
				self::update_active_modules( array_values( $modules ) );
1999
				continue;
2000
			}
2001
2002
			/**
2003
			 * Fires when a specific module is loaded.
2004
			 * The dynamic part of the hook, $module, is the module slug.
2005
			 *
2006
			 * @since 1.1.0
2007
			 */
2008
			do_action( 'jetpack_module_loaded_' . $module );
2009
		}
2010
2011
		/**
2012
		 * Fires when all the modules are loaded.
2013
		 *
2014
		 * @since 1.1.0
2015
		 */
2016
		do_action( 'jetpack_modules_loaded' );
2017
2018
		// 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.
2019
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2020
	}
2021
2022
	/**
2023
	 * Check if Jetpack's REST API compat file should be included
2024
	 *
2025
	 * @action plugins_loaded
2026
	 * @return null
2027
	 */
2028
	public function check_rest_api_compat() {
2029
		/**
2030
		 * Filters the list of REST API compat files to be included.
2031
		 *
2032
		 * @since 2.2.5
2033
		 *
2034
		 * @param array $args Array of REST API compat files to include.
2035
		 */
2036
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2037
2038
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2039
			require_once $_jetpack_rest_api_compat_include;
2040
		}
2041
	}
2042
2043
	/**
2044
	 * Gets all plugins currently active in values, regardless of whether they're
2045
	 * traditionally activated or network activated.
2046
	 *
2047
	 * @todo Store the result in core's object cache maybe?
2048
	 */
2049
	public static function get_active_plugins() {
2050
		$active_plugins = (array) get_option( 'active_plugins', array() );
2051
2052
		if ( is_multisite() ) {
2053
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2054
			// whereas active_plugins stores them in the values.
2055
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2056
			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...
2057
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2058
			}
2059
		}
2060
2061
		sort( $active_plugins );
2062
2063
		return array_unique( $active_plugins );
2064
	}
2065
2066
	/**
2067
	 * Gets and parses additional plugin data to send with the heartbeat data
2068
	 *
2069
	 * @since 3.8.1
2070
	 *
2071
	 * @return array Array of plugin data
2072
	 */
2073
	public static function get_parsed_plugin_data() {
2074
		if ( ! function_exists( 'get_plugins' ) ) {
2075
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2076
		}
2077
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2078
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2079
		$active_plugins = self::get_active_plugins();
2080
2081
		$plugins = array();
2082
		foreach ( $all_plugins as $path => $plugin_data ) {
2083
			$plugins[ $path ] = array(
2084
				'is_active' => in_array( $path, $active_plugins ),
2085
				'file'      => $path,
2086
				'name'      => $plugin_data['Name'],
2087
				'version'   => $plugin_data['Version'],
2088
				'author'    => $plugin_data['Author'],
2089
			);
2090
		}
2091
2092
		return $plugins;
2093
	}
2094
2095
	/**
2096
	 * Gets and parses theme data to send with the heartbeat data
2097
	 *
2098
	 * @since 3.8.1
2099
	 *
2100
	 * @return array Array of theme data
2101
	 */
2102
	public static function get_parsed_theme_data() {
2103
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2104
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2105
2106
		$themes = array();
2107
		foreach ( $all_themes as $slug => $theme_data ) {
2108
			$theme_headers = array();
2109
			foreach ( $header_keys as $header_key ) {
2110
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2111
			}
2112
2113
			$themes[ $slug ] = array(
2114
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2115
				'slug'            => $slug,
2116
				'theme_root'      => $theme_data->get_theme_root_uri(),
2117
				'parent'          => $theme_data->parent(),
2118
				'headers'         => $theme_headers,
2119
			);
2120
		}
2121
2122
		return $themes;
2123
	}
2124
2125
	/**
2126
	 * Checks whether a specific plugin is active.
2127
	 *
2128
	 * We don't want to store these in a static variable, in case
2129
	 * there are switch_to_blog() calls involved.
2130
	 */
2131
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2132
		return in_array( $plugin, self::get_active_plugins() );
2133
	}
2134
2135
	/**
2136
	 * Check if Jetpack's Open Graph tags should be used.
2137
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2138
	 *
2139
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2140
	 * @action plugins_loaded
2141
	 * @return null
2142
	 */
2143
	public function check_open_graph() {
2144
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2145
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2146
		}
2147
2148
		$active_plugins = self::get_active_plugins();
2149
2150
		if ( ! empty( $active_plugins ) ) {
2151
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2152
				if ( in_array( $plugin, $active_plugins ) ) {
2153
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2154
					break;
2155
				}
2156
			}
2157
		}
2158
2159
		/**
2160
		 * Allow the addition of Open Graph Meta Tags to all pages.
2161
		 *
2162
		 * @since 2.0.3
2163
		 *
2164
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2165
		 */
2166
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2167
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2168
		}
2169
	}
2170
2171
	/**
2172
	 * Check if Jetpack's Twitter tags should be used.
2173
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2174
	 *
2175
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2176
	 * @action plugins_loaded
2177
	 * @return null
2178
	 */
2179
	public function check_twitter_tags() {
2180
2181
		$active_plugins = self::get_active_plugins();
2182
2183
		if ( ! empty( $active_plugins ) ) {
2184
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2185
				if ( in_array( $plugin, $active_plugins ) ) {
2186
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2187
					break;
2188
				}
2189
			}
2190
		}
2191
2192
		/**
2193
		 * Allow Twitter Card Meta tags to be disabled.
2194
		 *
2195
		 * @since 2.6.0
2196
		 *
2197
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2198
		 */
2199
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2200
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2201
		}
2202
	}
2203
2204
	/**
2205
	 * Allows plugins to submit security reports.
2206
	 *
2207
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2208
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2209
	 * @param array  $args         See definitions above
2210
	 */
2211
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2212
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2213
	}
2214
2215
	/* Jetpack Options API */
2216
2217
	public static function get_option_names( $type = 'compact' ) {
2218
		return Jetpack_Options::get_option_names( $type );
2219
	}
2220
2221
	/**
2222
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2223
	 *
2224
	 * @param string $name    Option name
2225
	 * @param mixed  $default (optional)
2226
	 */
2227
	public static function get_option( $name, $default = false ) {
2228
		return Jetpack_Options::get_option( $name, $default );
2229
	}
2230
2231
	/**
2232
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2233
	 *
2234
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2235
	 * @param string $name  Option name
2236
	 * @param mixed  $value Option value
2237
	 */
2238
	public static function update_option( $name, $value ) {
2239
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2240
		return Jetpack_Options::update_option( $name, $value );
2241
	}
2242
2243
	/**
2244
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2245
	 *
2246
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2247
	 * @param array $array array( option name => option value, ... )
2248
	 */
2249
	public static function update_options( $array ) {
2250
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2251
		return Jetpack_Options::update_options( $array );
2252
	}
2253
2254
	/**
2255
	 * Deletes the given option.  May be passed multiple option names as an array.
2256
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2257
	 *
2258
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2259
	 * @param string|array $names
2260
	 */
2261
	public static function delete_option( $names ) {
2262
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2263
		return Jetpack_Options::delete_option( $names );
2264
	}
2265
2266
	/**
2267
	 * Enters a user token into the user_tokens option
2268
	 *
2269
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2270
	 *
2271
	 * @param int    $user_id The user id.
2272
	 * @param string $token The user token.
2273
	 * @param bool   $is_master_user Whether the user is the master user.
2274
	 * @return bool
2275
	 */
2276
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2277
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2278
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2279
	}
2280
2281
	/**
2282
	 * Returns an array of all PHP files in the specified absolute path.
2283
	 * Equivalent to glob( "$absolute_path/*.php" ).
2284
	 *
2285
	 * @param string $absolute_path The absolute path of the directory to search.
2286
	 * @return array Array of absolute paths to the PHP files.
2287
	 */
2288
	public static function glob_php( $absolute_path ) {
2289
		if ( function_exists( 'glob' ) ) {
2290
			return glob( "$absolute_path/*.php" );
2291
		}
2292
2293
		$absolute_path = untrailingslashit( $absolute_path );
2294
		$files         = array();
2295
		if ( ! $dir = @opendir( $absolute_path ) ) {
2296
			return $files;
2297
		}
2298
2299
		while ( false !== $file = readdir( $dir ) ) {
2300
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2301
				continue;
2302
			}
2303
2304
			$file = "$absolute_path/$file";
2305
2306
			if ( ! is_file( $file ) ) {
2307
				continue;
2308
			}
2309
2310
			$files[] = $file;
2311
		}
2312
2313
		closedir( $dir );
2314
2315
		return $files;
2316
	}
2317
2318
	public static function activate_new_modules( $redirect = false ) {
2319
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2320
			return;
2321
		}
2322
2323
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2324 View Code Duplication
		if ( ! $jetpack_old_version ) {
2325
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2326
			/** This action is documented in class.jetpack.php */
2327
			do_action( 'updating_jetpack_version', $version, false );
2328
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2329
		}
2330
2331
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2332
2333
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2334
			return;
2335
		}
2336
2337
		$active_modules     = self::get_active_modules();
2338
		$reactivate_modules = array();
2339
		foreach ( $active_modules as $active_module ) {
2340
			$module = self::get_module( $active_module );
2341
			if ( ! isset( $module['changed'] ) ) {
2342
				continue;
2343
			}
2344
2345
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2346
				continue;
2347
			}
2348
2349
			$reactivate_modules[] = $active_module;
2350
			self::deactivate_module( $active_module );
2351
		}
2352
2353
		$new_version = JETPACK__VERSION . ':' . time();
2354
		/** This action is documented in class.jetpack.php */
2355
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2356
		Jetpack_Options::update_options(
2357
			array(
2358
				'version'     => $new_version,
2359
				'old_version' => $jetpack_old_version,
2360
			)
2361
		);
2362
2363
		self::state( 'message', 'modules_activated' );
2364
2365
		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...
2366
2367
		if ( $redirect ) {
2368
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2369
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2370
				$page = $_GET['page'];
2371
			}
2372
2373
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2374
			exit;
2375
		}
2376
	}
2377
2378
	/**
2379
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2380
	 * Make sure to tuck away module "library" files in a sub-directory.
2381
	 */
2382
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2383
		static $modules = null;
2384
2385
		if ( ! isset( $modules ) ) {
2386
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2387
			// Use the cache if we're on the front-end and it's available...
2388
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2389
				$modules = $available_modules_option[ JETPACK__VERSION ];
2390
			} else {
2391
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2392
2393
				$modules = array();
2394
2395
				foreach ( $files as $file ) {
2396
					if ( ! $headers = self::get_module( $file ) ) {
2397
						continue;
2398
					}
2399
2400
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2401
				}
2402
2403
				Jetpack_Options::update_option(
2404
					'available_modules',
2405
					array(
2406
						JETPACK__VERSION => $modules,
2407
					)
2408
				);
2409
			}
2410
		}
2411
2412
		/**
2413
		 * Filters the array of modules available to be activated.
2414
		 *
2415
		 * @since 2.4.0
2416
		 *
2417
		 * @param array $modules Array of available modules.
2418
		 * @param string $min_version Minimum version number required to use modules.
2419
		 * @param string $max_version Maximum version number required to use modules.
2420
		 */
2421
		$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...
2422
2423
		if ( ! $min_version && ! $max_version ) {
2424
			return array_keys( $mods );
2425
		}
2426
2427
		$r = array();
2428
		foreach ( $mods as $slug => $introduced ) {
2429
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2430
				continue;
2431
			}
2432
2433
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2434
				continue;
2435
			}
2436
2437
			$r[] = $slug;
2438
		}
2439
2440
		return $r;
2441
	}
2442
2443
	/**
2444
	 * Default modules loaded on activation.
2445
	 */
2446
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2447
		$return = array();
2448
2449
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2450
			$module_data = self::get_module( $module );
2451
2452
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2453
				case 'yes':
2454
					$return[] = $module;
2455
					break;
2456
				case 'public':
2457
					if ( Jetpack_Options::get_option( 'public' ) ) {
2458
						$return[] = $module;
2459
					}
2460
					break;
2461
				case 'no':
2462
				default:
2463
					break;
2464
			}
2465
		}
2466
		/**
2467
		 * Filters the array of default modules.
2468
		 *
2469
		 * @since 2.5.0
2470
		 *
2471
		 * @param array $return Array of default modules.
2472
		 * @param string $min_version Minimum version number required to use modules.
2473
		 * @param string $max_version Maximum version number required to use modules.
2474
		 */
2475
		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...
2476
	}
2477
2478
	/**
2479
	 * Checks activated modules during auto-activation to determine
2480
	 * if any of those modules are being deprecated.  If so, close
2481
	 * them out, and add any replacement modules.
2482
	 *
2483
	 * Runs at priority 99 by default.
2484
	 *
2485
	 * This is run late, so that it can still activate a module if
2486
	 * the new module is a replacement for another that the user
2487
	 * currently has active, even if something at the normal priority
2488
	 * would kibosh everything.
2489
	 *
2490
	 * @since 2.6
2491
	 * @uses jetpack_get_default_modules filter
2492
	 * @param array $modules
2493
	 * @return array
2494
	 */
2495
	function handle_deprecated_modules( $modules ) {
2496
		$deprecated_modules = array(
2497
			'debug'            => null,  // Closed out and moved to the debugger library.
2498
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2499
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2500
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2501
		);
2502
2503
		// Don't activate SSO if they never completed activating WPCC.
2504
		if ( self::is_module_active( 'wpcc' ) ) {
2505
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2506
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2507
				$deprecated_modules['wpcc'] = null;
2508
			}
2509
		}
2510
2511
		foreach ( $deprecated_modules as $module => $replacement ) {
2512
			if ( self::is_module_active( $module ) ) {
2513
				self::deactivate_module( $module );
2514
				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...
2515
					$modules[] = $replacement;
2516
				}
2517
			}
2518
		}
2519
2520
		return array_unique( $modules );
2521
	}
2522
2523
	/**
2524
	 * Checks activated plugins during auto-activation to determine
2525
	 * if any of those plugins are in the list with a corresponding module
2526
	 * that is not compatible with the plugin. The module will not be allowed
2527
	 * to auto-activate.
2528
	 *
2529
	 * @since 2.6
2530
	 * @uses jetpack_get_default_modules filter
2531
	 * @param array $modules
2532
	 * @return array
2533
	 */
2534
	function filter_default_modules( $modules ) {
2535
2536
		$active_plugins = self::get_active_plugins();
2537
2538
		if ( ! empty( $active_plugins ) ) {
2539
2540
			// For each module we'd like to auto-activate...
2541
			foreach ( $modules as $key => $module ) {
2542
				// If there are potential conflicts for it...
2543
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2544
					// For each potential conflict...
2545
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2546
						// If that conflicting plugin is active...
2547
						if ( in_array( $plugin, $active_plugins ) ) {
2548
							// Remove that item from being auto-activated.
2549
							unset( $modules[ $key ] );
2550
						}
2551
					}
2552
				}
2553
			}
2554
		}
2555
2556
		return $modules;
2557
	}
2558
2559
	/**
2560
	 * Extract a module's slug from its full path.
2561
	 */
2562
	public static function get_module_slug( $file ) {
2563
		return str_replace( '.php', '', basename( $file ) );
2564
	}
2565
2566
	/**
2567
	 * Generate a module's path from its slug.
2568
	 */
2569
	public static function get_module_path( $slug ) {
2570
		/**
2571
		 * Filters the path of a modules.
2572
		 *
2573
		 * @since 7.4.0
2574
		 *
2575
		 * @param array $return The absolute path to a module's root php file
2576
		 * @param string $slug The module slug
2577
		 */
2578
		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...
2579
	}
2580
2581
	/**
2582
	 * Load module data from module file. Headers differ from WordPress
2583
	 * plugin headers to avoid them being identified as standalone
2584
	 * plugins on the WordPress plugins page.
2585
	 */
2586
	public static function get_module( $module ) {
2587
		$headers = array(
2588
			'name'                      => 'Module Name',
2589
			'description'               => 'Module Description',
2590
			'sort'                      => 'Sort Order',
2591
			'recommendation_order'      => 'Recommendation Order',
2592
			'introduced'                => 'First Introduced',
2593
			'changed'                   => 'Major Changes In',
2594
			'deactivate'                => 'Deactivate',
2595
			'free'                      => 'Free',
2596
			'requires_connection'       => 'Requires Connection',
2597
			'auto_activate'             => 'Auto Activate',
2598
			'module_tags'               => 'Module Tags',
2599
			'feature'                   => 'Feature',
2600
			'additional_search_queries' => 'Additional Search Queries',
2601
			'plan_classes'              => 'Plans',
2602
		);
2603
2604
		$file = self::get_module_path( self::get_module_slug( $module ) );
2605
2606
		$mod = self::get_file_data( $file, $headers );
2607
		if ( empty( $mod['name'] ) ) {
2608
			return false;
2609
		}
2610
2611
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2612
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2613
		$mod['deactivate']           = empty( $mod['deactivate'] );
2614
		$mod['free']                 = empty( $mod['free'] );
2615
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2616
2617
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2618
			$mod['auto_activate'] = 'No';
2619
		} else {
2620
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2621
		}
2622
2623
		if ( $mod['module_tags'] ) {
2624
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2625
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2626
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2627
		} else {
2628
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2629
		}
2630
2631 View Code Duplication
		if ( $mod['plan_classes'] ) {
2632
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2633
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2634
		} else {
2635
			$mod['plan_classes'] = array( 'free' );
2636
		}
2637
2638 View Code Duplication
		if ( $mod['feature'] ) {
2639
			$mod['feature'] = explode( ',', $mod['feature'] );
2640
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2641
		} else {
2642
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2643
		}
2644
2645
		/**
2646
		 * Filters the feature array on a module.
2647
		 *
2648
		 * This filter allows you to control where each module is filtered: Recommended,
2649
		 * and the default "Other" listing.
2650
		 *
2651
		 * @since 3.5.0
2652
		 *
2653
		 * @param array   $mod['feature'] The areas to feature this module:
2654
		 *     'Recommended' shows on the main Jetpack admin screen.
2655
		 *     'Other' should be the default if no other value is in the array.
2656
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2657
		 * @param array   $mod All the currently assembled module data.
2658
		 */
2659
		$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...
2660
2661
		/**
2662
		 * Filter the returned data about a module.
2663
		 *
2664
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2665
		 * so please be careful.
2666
		 *
2667
		 * @since 3.6.0
2668
		 *
2669
		 * @param array   $mod    The details of the requested module.
2670
		 * @param string  $module The slug of the module, e.g. sharedaddy
2671
		 * @param string  $file   The path to the module source file.
2672
		 */
2673
		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...
2674
	}
2675
2676
	/**
2677
	 * Like core's get_file_data implementation, but caches the result.
2678
	 */
2679
	public static function get_file_data( $file, $headers ) {
2680
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2681
		$file_name = basename( $file );
2682
2683
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2684
2685
		$file_data_option = get_transient( $cache_key );
2686
2687
		if ( ! is_array( $file_data_option ) ) {
2688
			delete_transient( $cache_key );
2689
			$file_data_option = false;
2690
		}
2691
2692
		if ( false === $file_data_option ) {
2693
			$file_data_option = array();
2694
		}
2695
2696
		$key           = md5( $file_name . serialize( $headers ) );
2697
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2698
2699
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2700
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2701
			return $file_data_option[ $key ];
2702
		}
2703
2704
		$data = get_file_data( $file, $headers );
2705
2706
		$file_data_option[ $key ] = $data;
2707
2708
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2709
2710
		return $data;
2711
	}
2712
2713
	/**
2714
	 * Return translated module tag.
2715
	 *
2716
	 * @param string $tag Tag as it appears in each module heading.
2717
	 *
2718
	 * @return mixed
2719
	 */
2720
	public static function translate_module_tag( $tag ) {
2721
		return jetpack_get_module_i18n_tag( $tag );
2722
	}
2723
2724
	/**
2725
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2726
	 *
2727
	 * @since 3.9.2
2728
	 *
2729
	 * @param array $modules
2730
	 *
2731
	 * @return string|void
2732
	 */
2733
	public static function get_translated_modules( $modules ) {
2734
		foreach ( $modules as $index => $module ) {
2735
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2736
			if ( isset( $module['name'] ) ) {
2737
				$modules[ $index ]['name'] = $i18n_module['name'];
2738
			}
2739
			if ( isset( $module['description'] ) ) {
2740
				$modules[ $index ]['description']       = $i18n_module['description'];
2741
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2742
			}
2743
		}
2744
		return $modules;
2745
	}
2746
2747
	/**
2748
	 * Get a list of activated modules as an array of module slugs.
2749
	 */
2750
	public static function get_active_modules() {
2751
		$active = Jetpack_Options::get_option( 'active_modules' );
2752
2753
		if ( ! is_array( $active ) ) {
2754
			$active = array();
2755
		}
2756
2757
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2758
			$active[] = 'vaultpress';
2759
		} else {
2760
			$active = array_diff( $active, array( 'vaultpress' ) );
2761
		}
2762
2763
		// If protect is active on the main site of a multisite, it should be active on all sites.
2764
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2765
			$active[] = 'protect';
2766
		}
2767
2768
		/**
2769
		 * Allow filtering of the active modules.
2770
		 *
2771
		 * Gives theme and plugin developers the power to alter the modules that
2772
		 * are activated on the fly.
2773
		 *
2774
		 * @since 5.8.0
2775
		 *
2776
		 * @param array $active Array of active module slugs.
2777
		 */
2778
		$active = apply_filters( 'jetpack_active_modules', $active );
2779
2780
		return array_unique( $active );
2781
	}
2782
2783
	/**
2784
	 * Check whether or not a Jetpack module is active.
2785
	 *
2786
	 * @param string $module The slug of a Jetpack module.
2787
	 * @return bool
2788
	 *
2789
	 * @static
2790
	 */
2791
	public static function is_module_active( $module ) {
2792
		return in_array( $module, self::get_active_modules() );
2793
	}
2794
2795
	public static function is_module( $module ) {
2796
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2797
	}
2798
2799
	/**
2800
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2801
	 *
2802
	 * @param bool $catch True to start catching, False to stop.
2803
	 *
2804
	 * @static
2805
	 */
2806
	public static function catch_errors( $catch ) {
2807
		static $display_errors, $error_reporting;
2808
2809
		if ( $catch ) {
2810
			$display_errors  = @ini_set( 'display_errors', 1 );
2811
			$error_reporting = @error_reporting( E_ALL );
2812
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2813
		} else {
2814
			@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...
2815
			@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...
2816
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2817
		}
2818
	}
2819
2820
	/**
2821
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2822
	 */
2823
	public static function catch_errors_on_shutdown() {
2824
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2825
	}
2826
2827
	/**
2828
	 * Rewrite any string to make paths easier to read.
2829
	 *
2830
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2831
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2832
	 *
2833
	 * @param $string
2834
	 * @return mixed
2835
	 */
2836
	public static function alias_directories( $string ) {
2837
		// ABSPATH has a trailing slash.
2838
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2839
		// WP_CONTENT_DIR does not have a trailing slash.
2840
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2841
2842
		return $string;
2843
	}
2844
2845
	public static function activate_default_modules(
2846
		$min_version = false,
2847
		$max_version = false,
2848
		$other_modules = array(),
2849
		$redirect = null,
2850
		$send_state_messages = null
2851
	) {
2852
		$jetpack = self::init();
2853
2854
		if ( is_null( $redirect ) ) {
2855
			if (
2856
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2857
			||
2858
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2859
			||
2860
				( defined( 'WP_CLI' ) && WP_CLI )
2861
			||
2862
				( defined( 'DOING_CRON' ) && DOING_CRON )
2863
			||
2864
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2865
			) {
2866
				$redirect = false;
2867
			} elseif ( is_admin() ) {
2868
				$redirect = true;
2869
			} else {
2870
				$redirect = false;
2871
			}
2872
		}
2873
2874
		if ( is_null( $send_state_messages ) ) {
2875
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2876
		}
2877
2878
		$modules = self::get_default_modules( $min_version, $max_version );
2879
		$modules = array_merge( $other_modules, $modules );
2880
2881
		// Look for standalone plugins and disable if active.
2882
2883
		$to_deactivate = array();
2884
		foreach ( $modules as $module ) {
2885
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2886
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2887
			}
2888
		}
2889
2890
		$deactivated = array();
2891
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2892
			list( $probable_file, $probable_title ) = $deactivate_me;
2893
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2894
				$deactivated[] = $module;
2895
			}
2896
		}
2897
2898
		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...
2899
			if ( $send_state_messages ) {
2900
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2901
			}
2902
2903
			if ( $redirect ) {
2904
				$url = add_query_arg(
2905
					array(
2906
						'action'   => 'activate_default_modules',
2907
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2908
					),
2909
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2910
				);
2911
				wp_safe_redirect( $url );
2912
				exit;
2913
			}
2914
		}
2915
2916
		/**
2917
		 * Fires before default modules are activated.
2918
		 *
2919
		 * @since 1.9.0
2920
		 *
2921
		 * @param string $min_version Minimum version number required to use modules.
2922
		 * @param string $max_version Maximum version number required to use modules.
2923
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2924
		 */
2925
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2926
2927
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2928
		if ( $send_state_messages ) {
2929
			self::restate();
2930
			self::catch_errors( true );
2931
		}
2932
2933
		$active = self::get_active_modules();
2934
2935
		foreach ( $modules as $module ) {
2936
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2937
				$active[] = $module;
2938
				self::update_active_modules( $active );
2939
				continue;
2940
			}
2941
2942
			if ( $send_state_messages && in_array( $module, $active ) ) {
2943
				$module_info = self::get_module( $module );
2944 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2945
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2946
					if ( $active_state = self::state( $state ) ) {
2947
						$active_state = explode( ',', $active_state );
2948
					} else {
2949
						$active_state = array();
2950
					}
2951
					$active_state[] = $module;
2952
					self::state( $state, implode( ',', $active_state ) );
2953
				}
2954
				continue;
2955
			}
2956
2957
			$file = self::get_module_path( $module );
2958
			if ( ! file_exists( $file ) ) {
2959
				continue;
2960
			}
2961
2962
			// we'll override this later if the plugin can be included without fatal error
2963
			if ( $redirect ) {
2964
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2965
			}
2966
2967
			if ( $send_state_messages ) {
2968
				self::state( 'error', 'module_activation_failed' );
2969
				self::state( 'module', $module );
2970
			}
2971
2972
			ob_start();
2973
			require_once $file;
2974
2975
			$active[] = $module;
2976
2977 View Code Duplication
			if ( $send_state_messages ) {
2978
2979
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2980
				if ( $active_state = self::state( $state ) ) {
2981
					$active_state = explode( ',', $active_state );
2982
				} else {
2983
					$active_state = array();
2984
				}
2985
				$active_state[] = $module;
2986
				self::state( $state, implode( ',', $active_state ) );
2987
			}
2988
2989
			self::update_active_modules( $active );
2990
2991
			ob_end_clean();
2992
		}
2993
2994
		if ( $send_state_messages ) {
2995
			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...
2996
			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...
2997
		}
2998
2999
		self::catch_errors( false );
3000
		/**
3001
		 * Fires when default modules are activated.
3002
		 *
3003
		 * @since 1.9.0
3004
		 *
3005
		 * @param string $min_version Minimum version number required to use modules.
3006
		 * @param string $max_version Maximum version number required to use modules.
3007
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3008
		 */
3009
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3010
	}
3011
3012
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3013
		/**
3014
		 * Fires before a module is activated.
3015
		 *
3016
		 * @since 2.6.0
3017
		 *
3018
		 * @param string $module Module slug.
3019
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3020
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3021
		 */
3022
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3023
3024
		$jetpack = self::init();
3025
3026
		if ( ! strlen( $module ) ) {
3027
			return false;
3028
		}
3029
3030
		if ( ! self::is_module( $module ) ) {
3031
			return false;
3032
		}
3033
3034
		// If it's already active, then don't do it again
3035
		$active = self::get_active_modules();
3036
		foreach ( $active as $act ) {
3037
			if ( $act == $module ) {
3038
				return true;
3039
			}
3040
		}
3041
3042
		$module_data = self::get_module( $module );
3043
3044
		$is_offline_mode = ( new Status() )->is_offline_mode();
3045
		if ( ! self::is_active() ) {
3046
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
3047
				return false;
3048
			}
3049
3050
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
3051
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3052
				return false;
3053
			}
3054
		}
3055
3056
		// Check and see if the old plugin is active
3057
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3058
			// Deactivate the old plugin
3059
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3060
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3061
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3062
				self::state( 'deactivated_plugins', $module );
3063
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3064
				exit;
3065
			}
3066
		}
3067
3068
		// Protect won't work with mis-configured IPs
3069
		if ( 'protect' === $module ) {
3070
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3071
			if ( ! jetpack_protect_get_ip() ) {
3072
				self::state( 'message', 'protect_misconfigured_ip' );
3073
				return false;
3074
			}
3075
		}
3076
3077
		if ( ! Jetpack_Plan::supports( $module ) ) {
3078
			return false;
3079
		}
3080
3081
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3082
		self::state( 'module', $module );
3083
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3084
3085
		self::catch_errors( true );
3086
		ob_start();
3087
		require self::get_module_path( $module );
3088
		/** This action is documented in class.jetpack.php */
3089
		do_action( 'jetpack_activate_module', $module );
3090
		$active[] = $module;
3091
		self::update_active_modules( $active );
3092
3093
		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...
3094
		ob_end_clean();
3095
		self::catch_errors( false );
3096
3097
		if ( $redirect ) {
3098
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3099
		}
3100
		if ( $exit ) {
3101
			exit;
3102
		}
3103
		return true;
3104
	}
3105
3106
	function activate_module_actions( $module ) {
3107
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3108
	}
3109
3110
	public static function deactivate_module( $module ) {
3111
		/**
3112
		 * Fires when a module is deactivated.
3113
		 *
3114
		 * @since 1.9.0
3115
		 *
3116
		 * @param string $module Module slug.
3117
		 */
3118
		do_action( 'jetpack_pre_deactivate_module', $module );
3119
3120
		$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...
3121
3122
		$active = self::get_active_modules();
3123
		$new    = array_filter( array_diff( $active, (array) $module ) );
3124
3125
		return self::update_active_modules( $new );
3126
	}
3127
3128
	public static function enable_module_configurable( $module ) {
3129
		$module = self::get_module_slug( $module );
3130
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3131
	}
3132
3133
	/**
3134
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3135
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3136
	 *
3137
	 * @param string $module Module slug
3138
	 * @return string $url module configuration URL
3139
	 */
3140
	public static function module_configuration_url( $module ) {
3141
		$module      = self::get_module_slug( $module );
3142
		$default_url = self::admin_url() . "#/settings?term=$module";
3143
		/**
3144
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3145
		 *
3146
		 * @since 6.9.0
3147
		 *
3148
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3149
		 */
3150
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3151
3152
		return $url;
3153
	}
3154
3155
	/* Installation */
3156
	public static function bail_on_activation( $message, $deactivate = true ) {
3157
		?>
3158
<!doctype html>
3159
<html>
3160
<head>
3161
<meta charset="<?php bloginfo( 'charset' ); ?>">
3162
<style>
3163
* {
3164
	text-align: center;
3165
	margin: 0;
3166
	padding: 0;
3167
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3168
}
3169
p {
3170
	margin-top: 1em;
3171
	font-size: 18px;
3172
}
3173
</style>
3174
<body>
3175
<p><?php echo esc_html( $message ); ?></p>
3176
</body>
3177
</html>
3178
		<?php
3179
		if ( $deactivate ) {
3180
			$plugins = get_option( 'active_plugins' );
3181
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3182
			$update  = false;
3183
			foreach ( $plugins as $i => $plugin ) {
3184
				if ( $plugin === $jetpack ) {
3185
					$plugins[ $i ] = false;
3186
					$update        = true;
3187
				}
3188
			}
3189
3190
			if ( $update ) {
3191
				update_option( 'active_plugins', array_filter( $plugins ) );
3192
			}
3193
		}
3194
		exit;
3195
	}
3196
3197
	/**
3198
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3199
	 *
3200
	 * @static
3201
	 */
3202
	public static function plugin_activation( $network_wide ) {
3203
		Jetpack_Options::update_option( 'activated', 1 );
3204
3205
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3206
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3207
		}
3208
3209
		if ( $network_wide ) {
3210
			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...
3211
		}
3212
3213
		// For firing one-off events (notices) immediately after activation
3214
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3215
3216
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3217
3218
		Health::on_jetpack_activated();
3219
3220
		self::plugin_initialize();
3221
	}
3222
3223
	public static function get_activation_source( $referer_url ) {
3224
3225
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3226
			return array( 'wp-cli', null );
3227
		}
3228
3229
		$referer = wp_parse_url( $referer_url );
3230
3231
		$source_type  = 'unknown';
3232
		$source_query = null;
3233
3234
		if ( ! is_array( $referer ) ) {
3235
			return array( $source_type, $source_query );
3236
		}
3237
3238
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3239
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3240
3241
		if ( isset( $referer['query'] ) ) {
3242
			parse_str( $referer['query'], $query_parts );
3243
		} else {
3244
			$query_parts = array();
3245
		}
3246
3247
		if ( $plugins_path === $referer['path'] ) {
3248
			$source_type = 'list';
3249
		} elseif ( $plugins_install_path === $referer['path'] ) {
3250
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3251
			switch ( $tab ) {
3252
				case 'popular':
3253
					$source_type = 'popular';
3254
					break;
3255
				case 'recommended':
3256
					$source_type = 'recommended';
3257
					break;
3258
				case 'favorites':
3259
					$source_type = 'favorites';
3260
					break;
3261
				case 'search':
3262
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3263
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3264
					break;
3265
				default:
3266
					$source_type = 'featured';
3267
			}
3268
		}
3269
3270
		return array( $source_type, $source_query );
3271
	}
3272
3273
	/**
3274
	 * Runs before bumping version numbers up to a new version
3275
	 *
3276
	 * @param string $version    Version:timestamp.
3277
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3278
	 */
3279
	public static function do_version_bump( $version, $old_version ) {
3280
		if ( $old_version ) { // For existing Jetpack installations.
3281
3282
			// If a front end page is visited after the update, the 'wp' action will fire.
3283
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3284
3285
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3286
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3287
		}
3288
	}
3289
3290
	/**
3291
	 * Sets the display_update_modal state.
3292
	 */
3293
	public static function set_update_modal_display() {
3294
		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...
3295
	}
3296
3297
	/**
3298
	 * Sets the internal version number and activation state.
3299
	 *
3300
	 * @static
3301
	 */
3302
	public static function plugin_initialize() {
3303
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3304
			Jetpack_Options::update_option( 'activated', 2 );
3305
		}
3306
3307 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3308
			$version = $old_version = JETPACK__VERSION . ':' . time();
3309
			/** This action is documented in class.jetpack.php */
3310
			do_action( 'updating_jetpack_version', $version, false );
3311
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3312
		}
3313
3314
		self::load_modules();
3315
3316
		Jetpack_Options::delete_option( 'do_activate' );
3317
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3318
	}
3319
3320
	/**
3321
	 * Removes all connection options
3322
	 *
3323
	 * @static
3324
	 */
3325
	public static function plugin_deactivation() {
3326
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3327
		$tracking = new Tracking();
3328
		$tracking->record_user_event( 'deactivate_plugin', array() );
3329
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3330
			Jetpack_Network::init()->deactivate();
3331
		} else {
3332
			self::disconnect( false );
3333
			// Jetpack_Heartbeat::init()->deactivate();
3334
		}
3335
	}
3336
3337
	/**
3338
	 * Disconnects from the Jetpack servers.
3339
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3340
	 *
3341
	 * @static
3342
	 */
3343
	public static function disconnect( $update_activated_state = true ) {
3344
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3345
3346
		$connection = self::connection();
3347
		$connection->clean_nonces( true );
3348
3349
		// If the site is in an IDC because sync is not allowed,
3350
		// let's make sure to not disconnect the production site.
3351
		if ( ! self::validate_sync_error_idc_option() ) {
3352
			$tracking = new Tracking();
3353
			$tracking->record_user_event( 'disconnect_site', array() );
3354
3355
			$connection->disconnect_site_wpcom( true );
3356
		}
3357
3358
		$connection->delete_all_connection_tokens( true );
3359
		Jetpack_IDC::clear_all_idc_options();
3360
3361
		if ( $update_activated_state ) {
3362
			Jetpack_Options::update_option( 'activated', 4 );
3363
		}
3364
3365
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3366
			// Check then record unique disconnection if site has never been disconnected previously
3367
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3368
				$jetpack_unique_connection['disconnected'] = 1;
3369
			} else {
3370
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3371
					// track unique disconnect
3372
					$jetpack = self::init();
3373
3374
					$jetpack->stat( 'connections', 'unique-disconnect' );
3375
					$jetpack->do_stats( 'server_side' );
3376
				}
3377
				// increment number of times disconnected
3378
				$jetpack_unique_connection['disconnected'] += 1;
3379
			}
3380
3381
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3382
		}
3383
3384
		// Delete all the sync related data. Since it could be taking up space.
3385
		Sender::get_instance()->uninstall();
3386
3387
	}
3388
3389
	/**
3390
	 * Disconnects the user
3391
	 *
3392
	 * @param int $user_id The user ID to disconnect.
3393
	 */
3394
	public function disconnect_user( $user_id ) {
3395
		$this->connection_manager->disconnect_user( $user_id );
3396
	}
3397
3398
	/**
3399
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3400
	 */
3401
	public static function try_registration() {
3402
		$terms_of_service = new Terms_Of_Service();
3403
		// The user has agreed to the TOS at some point by now.
3404
		$terms_of_service->agree();
3405
3406
		// Let's get some testing in beta versions and such.
3407
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3408
			// Before attempting to connect, let's make sure that the domains are viable.
3409
			$domains_to_check = array_unique(
3410
				array(
3411
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3412
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3413
				)
3414
			);
3415
			foreach ( $domains_to_check as $domain ) {
3416
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3415 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...
3417
				if ( is_wp_error( $result ) ) {
3418
					return $result;
3419
				}
3420
			}
3421
		}
3422
3423
		$result = self::register();
3424
3425
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3426
		if ( ! $result || is_wp_error( $result ) ) {
3427
			return $result;
3428
		} else {
3429
			return true;
3430
		}
3431
	}
3432
3433
	/**
3434
	 * Tracking an internal event log. Try not to put too much chaff in here.
3435
	 *
3436
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3437
	 */
3438
	public static function log( $code, $data = null ) {
3439
		// only grab the latest 200 entries
3440
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3441
3442
		// Append our event to the log
3443
		$log_entry = array(
3444
			'time'    => time(),
3445
			'user_id' => get_current_user_id(),
3446
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3447
			'code'    => $code,
3448
		);
3449
		// Don't bother storing it unless we've got some.
3450
		if ( ! is_null( $data ) ) {
3451
			$log_entry['data'] = $data;
3452
		}
3453
		$log[] = $log_entry;
3454
3455
		// Try add_option first, to make sure it's not autoloaded.
3456
		// @todo: Add an add_option method to Jetpack_Options
3457
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3458
			Jetpack_Options::update_option( 'log', $log );
3459
		}
3460
3461
		/**
3462
		 * Fires when Jetpack logs an internal event.
3463
		 *
3464
		 * @since 3.0.0
3465
		 *
3466
		 * @param array $log_entry {
3467
		 *  Array of details about the log entry.
3468
		 *
3469
		 *  @param string time Time of the event.
3470
		 *  @param int user_id ID of the user who trigerred the event.
3471
		 *  @param int blog_id Jetpack Blog ID.
3472
		 *  @param string code Unique name for the event.
3473
		 *  @param string data Data about the event.
3474
		 * }
3475
		 */
3476
		do_action( 'jetpack_log_entry', $log_entry );
3477
	}
3478
3479
	/**
3480
	 * Get the internal event log.
3481
	 *
3482
	 * @param $event (string) - only return the specific log events
3483
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3484
	 *
3485
	 * @return array of log events || WP_Error for invalid params
3486
	 */
3487
	public static function get_log( $event = false, $num = false ) {
3488
		if ( $event && ! is_string( $event ) ) {
3489
			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...
3490
		}
3491
3492
		if ( $num && ! is_numeric( $num ) ) {
3493
			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...
3494
		}
3495
3496
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3497
3498
		// If nothing set - act as it did before, otherwise let's start customizing the output
3499
		if ( ! $num && ! $event ) {
3500
			return $entire_log;
3501
		} else {
3502
			$entire_log = array_reverse( $entire_log );
3503
		}
3504
3505
		$custom_log_output = array();
3506
3507
		if ( $event ) {
3508
			foreach ( $entire_log as $log_event ) {
3509
				if ( $event == $log_event['code'] ) {
3510
					$custom_log_output[] = $log_event;
3511
				}
3512
			}
3513
		} else {
3514
			$custom_log_output = $entire_log;
3515
		}
3516
3517
		if ( $num ) {
3518
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3519
		}
3520
3521
		return $custom_log_output;
3522
	}
3523
3524
	/**
3525
	 * Log modification of important settings.
3526
	 */
3527
	public static function log_settings_change( $option, $old_value, $value ) {
3528
		switch ( $option ) {
3529
			case 'jetpack_sync_non_public_post_stati':
3530
				self::log( $option, $value );
3531
				break;
3532
		}
3533
	}
3534
3535
	/**
3536
	 * Return stat data for WPCOM sync
3537
	 */
3538
	public static function get_stat_data( $encode = true, $extended = true ) {
3539
		$data = Jetpack_Heartbeat::generate_stats_array();
3540
3541
		if ( $extended ) {
3542
			$additional_data = self::get_additional_stat_data();
3543
			$data            = array_merge( $data, $additional_data );
3544
		}
3545
3546
		if ( $encode ) {
3547
			return json_encode( $data );
3548
		}
3549
3550
		return $data;
3551
	}
3552
3553
	/**
3554
	 * Get additional stat data to sync to WPCOM
3555
	 */
3556
	public static function get_additional_stat_data( $prefix = '' ) {
3557
		$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...
3558
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3559
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3560
		$return[ "{$prefix}site-count" ]    = 0;
3561
3562
		if ( function_exists( 'get_blog_count' ) ) {
3563
			$return[ "{$prefix}site-count" ] = get_blog_count();
3564
		}
3565
		return $return;
3566
	}
3567
3568
	private static function get_site_user_count() {
3569
		global $wpdb;
3570
3571
		if ( function_exists( 'wp_is_large_network' ) ) {
3572
			if ( wp_is_large_network( 'users' ) ) {
3573
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3574
			}
3575
		}
3576
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3577
			// It wasn't there, so regenerate the data and save the transient
3578
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3579
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3580
		}
3581
		return $user_count;
3582
	}
3583
3584
	/* Admin Pages */
3585
3586
	function admin_init() {
3587
		// If the plugin is not connected, display a connect message.
3588
		if (
3589
			// the plugin was auto-activated and needs its candy
3590
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3591
		||
3592
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3593
			! Jetpack_Options::get_option( 'activated' )
3594
		) {
3595
			self::plugin_initialize();
3596
		}
3597
3598
		$is_offline_mode = ( new Status() )->is_offline_mode();
3599
		if ( ! self::is_active() && ! $is_offline_mode ) {
3600
			Jetpack_Connection_Banner::init();
3601
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3602
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3603
			// Upgrade: 1.1 -> 1.1.1
3604
			// Check and see if host can verify the Jetpack servers' SSL certificate
3605
			$args = array();
3606
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3607
		}
3608
3609
		Jetpack_Recommendations_Banner::init();
3610
		Jetpack_Wizard_Banner::init();
3611
3612
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3613
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3614
		}
3615
3616
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3617
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3618
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3619
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3620
3621
		if ( self::is_active() || $is_offline_mode ) {
3622
			// Artificially throw errors in certain specific cases during plugin activation.
3623
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3624
		}
3625
3626
		// Add custom column in wp-admin/users.php to show whether user is linked.
3627
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3628
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3629
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3630
	}
3631
3632
	function admin_body_class( $admin_body_class = '' ) {
3633
		$classes = explode( ' ', trim( $admin_body_class ) );
3634
3635
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3636
3637
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3638
		return " $admin_body_class ";
3639
	}
3640
3641
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3642
		return $admin_body_class . ' jetpack-pagestyles ';
3643
	}
3644
3645
	/**
3646
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3647
	 * This function artificially throws errors for such cases (per a specific list).
3648
	 *
3649
	 * @param string $plugin The activated plugin.
3650
	 */
3651
	function throw_error_on_activate_plugin( $plugin ) {
3652
		$active_modules = self::get_active_modules();
3653
3654
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3655
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3656
			$throw = false;
3657
3658
			// Try and make sure it really was the stats plugin
3659
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3660
				if ( 'stats.php' == basename( $plugin ) ) {
3661
					$throw = true;
3662
				}
3663
			} else {
3664
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3665
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3666
					$throw = true;
3667
				}
3668
			}
3669
3670
			if ( $throw ) {
3671
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3672
			}
3673
		}
3674
	}
3675
3676
	function intercept_plugin_error_scrape_init() {
3677
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3678
	}
3679
3680
	function intercept_plugin_error_scrape( $action, $result ) {
3681
		if ( ! $result ) {
3682
			return;
3683
		}
3684
3685
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3686
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3687
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3688
			}
3689
		}
3690
	}
3691
3692
	/**
3693
	 * Register the remote file upload request handlers, if needed.
3694
	 *
3695
	 * @access public
3696
	 */
3697
	public function add_remote_request_handlers() {
3698
		// Remote file uploads are allowed only via AJAX requests.
3699
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3700
			return;
3701
		}
3702
3703
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3704
		$remote_request_actions = array(
3705
			'jetpack_upload_file',
3706
			'jetpack_update_file',
3707
		);
3708
3709
		// phpcs:ignore WordPress.Security.NonceVerification
3710
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3711
			return;
3712
		}
3713
3714
		// Require Jetpack authentication for the remote file upload AJAX requests.
3715
		if ( ! $this->connection_manager ) {
3716
			$this->connection_manager = new Connection_Manager();
3717
		}
3718
3719
		$this->connection_manager->require_jetpack_authentication();
3720
3721
		// Register the remote file upload AJAX handlers.
3722
		foreach ( $remote_request_actions as $action ) {
3723
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3724
		}
3725
	}
3726
3727
	/**
3728
	 * Handler for Jetpack remote file uploads.
3729
	 *
3730
	 * @access public
3731
	 */
3732
	public function remote_request_handlers() {
3733
		$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...
3734
3735
		switch ( current_filter() ) {
3736
			case 'wp_ajax_nopriv_jetpack_upload_file':
3737
				$response = $this->upload_handler();
3738
				break;
3739
3740
			case 'wp_ajax_nopriv_jetpack_update_file':
3741
				$response = $this->upload_handler( true );
3742
				break;
3743
			default:
3744
				$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...
3745
				break;
3746
		}
3747
3748
		if ( ! $response ) {
3749
			$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...
3750
		}
3751
3752
		if ( is_wp_error( $response ) ) {
3753
			$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...
3754
			$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...
3755
			$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...
3756
3757
			if ( ! is_int( $status_code ) ) {
3758
				$status_code = 400;
3759
			}
3760
3761
			status_header( $status_code );
3762
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3763
		}
3764
3765
		status_header( 200 );
3766
		if ( true === $response ) {
3767
			exit;
3768
		}
3769
3770
		die( json_encode( (object) $response ) );
3771
	}
3772
3773
	/**
3774
	 * Uploads a file gotten from the global $_FILES.
3775
	 * If `$update_media_item` is true and `post_id` is defined
3776
	 * the attachment file of the media item (gotten through of the post_id)
3777
	 * will be updated instead of add a new one.
3778
	 *
3779
	 * @param  boolean $update_media_item - update media attachment
3780
	 * @return array - An array describing the uploadind files process
3781
	 */
3782
	function upload_handler( $update_media_item = false ) {
3783
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3784
			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...
3785
		}
3786
3787
		$user = wp_authenticate( '', '' );
3788
		if ( ! $user || is_wp_error( $user ) ) {
3789
			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...
3790
		}
3791
3792
		wp_set_current_user( $user->ID );
3793
3794
		if ( ! current_user_can( 'upload_files' ) ) {
3795
			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...
3796
		}
3797
3798
		if ( empty( $_FILES ) ) {
3799
			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...
3800
		}
3801
3802
		foreach ( array_keys( $_FILES ) as $files_key ) {
3803
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3804
				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...
3805
			}
3806
		}
3807
3808
		$media_keys = array_keys( $_FILES['media'] );
3809
3810
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3811
		if ( ! $token || is_wp_error( $token ) ) {
3812
			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...
3813
		}
3814
3815
		$uploaded_files = array();
3816
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3817
		unset( $GLOBALS['post'] );
3818
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3819
			$file = array();
3820
			foreach ( $media_keys as $media_key ) {
3821
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3822
			}
3823
3824
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3825
3826
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3827
			if ( $hmac_provided !== $hmac_file ) {
3828
				$uploaded_files[ $index ] = (object) array(
3829
					'error'             => 'invalid_hmac',
3830
					'error_description' => 'The corresponding HMAC for this file does not match',
3831
				);
3832
				continue;
3833
			}
3834
3835
			$_FILES['.jetpack.upload.'] = $file;
3836
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3837
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3838
				$post_id = 0;
3839
			}
3840
3841
			if ( $update_media_item ) {
3842
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3843
					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...
3844
				}
3845
3846
				$media_array = $_FILES['media'];
3847
3848
				$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...
3849
				$file_array['type']     = $media_array['type'][0];
3850
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3851
				$file_array['error']    = $media_array['error'][0];
3852
				$file_array['size']     = $media_array['size'][0];
3853
3854
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3855
3856
				if ( is_wp_error( $edited_media_item ) ) {
3857
					return $edited_media_item;
3858
				}
3859
3860
				$response = (object) array(
3861
					'id'   => (string) $post_id,
3862
					'file' => (string) $edited_media_item->post_title,
3863
					'url'  => (string) wp_get_attachment_url( $post_id ),
3864
					'type' => (string) $edited_media_item->post_mime_type,
3865
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3866
				);
3867
3868
				return (array) array( $response );
3869
			}
3870
3871
			$attachment_id = media_handle_upload(
3872
				'.jetpack.upload.',
3873
				$post_id,
3874
				array(),
3875
				array(
3876
					'action' => 'jetpack_upload_file',
3877
				)
3878
			);
3879
3880
			if ( ! $attachment_id ) {
3881
				$uploaded_files[ $index ] = (object) array(
3882
					'error'             => 'unknown',
3883
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3884
				);
3885
			} elseif ( is_wp_error( $attachment_id ) ) {
3886
				$uploaded_files[ $index ] = (object) array(
3887
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3888
					'error_description' => $attachment_id->get_error_message(),
3889
				);
3890
			} else {
3891
				$attachment               = get_post( $attachment_id );
3892
				$uploaded_files[ $index ] = (object) array(
3893
					'id'   => (string) $attachment_id,
3894
					'file' => $attachment->post_title,
3895
					'url'  => wp_get_attachment_url( $attachment_id ),
3896
					'type' => $attachment->post_mime_type,
3897
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3898
				);
3899
				// Zip files uploads are not supported unless they are done for installation purposed
3900
				// lets delete them in case something goes wrong in this whole process
3901
				if ( 'application/zip' === $attachment->post_mime_type ) {
3902
					// Schedule a cleanup for 2 hours from now in case of failed install.
3903
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3904
				}
3905
			}
3906
		}
3907
		if ( ! is_null( $global_post ) ) {
3908
			$GLOBALS['post'] = $global_post;
3909
		}
3910
3911
		return $uploaded_files;
3912
	}
3913
3914
	/**
3915
	 * Add help to the Jetpack page
3916
	 *
3917
	 * @since Jetpack (1.2.3)
3918
	 * @return false if not the Jetpack page
3919
	 */
3920
	function admin_help() {
3921
		$current_screen = get_current_screen();
3922
3923
		// Overview
3924
		$current_screen->add_help_tab(
3925
			array(
3926
				'id'      => 'home',
3927
				'title'   => __( 'Home', 'jetpack' ),
3928
				'content' =>
3929
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3930
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3931
					'<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>',
3932
			)
3933
		);
3934
3935
		// Screen Content
3936
		if ( current_user_can( 'manage_options' ) ) {
3937
			$current_screen->add_help_tab(
3938
				array(
3939
					'id'      => 'settings',
3940
					'title'   => __( 'Settings', 'jetpack' ),
3941
					'content' =>
3942
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3943
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3944
						'<ol>' .
3945
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3946
							'<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>' .
3947
						'</ol>' .
3948
						'<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>',
3949
				)
3950
			);
3951
		}
3952
3953
		// Help Sidebar
3954
		$support_url = Redirect::get_url( 'jetpack-support' );
3955
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3956
		$current_screen->set_help_sidebar(
3957
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3958
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3959
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3960
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3961
		);
3962
	}
3963
3964
	function admin_menu_css() {
3965
		wp_enqueue_style( 'jetpack-icons' );
3966
	}
3967
3968
	function admin_menu_order() {
3969
		return true;
3970
	}
3971
3972
	function jetpack_menu_order( $menu_order ) {
3973
		$jp_menu_order = array();
3974
3975
		foreach ( $menu_order as $index => $item ) {
3976
			if ( $item != 'jetpack' ) {
3977
				$jp_menu_order[] = $item;
3978
			}
3979
3980
			if ( $index == 0 ) {
3981
				$jp_menu_order[] = 'jetpack';
3982
			}
3983
		}
3984
3985
		return $jp_menu_order;
3986
	}
3987
3988
	function admin_banner_styles() {
3989
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3990
3991 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3992
			wp_register_style(
3993
				'jetpack-dops-style',
3994
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3995
				array(),
3996
				JETPACK__VERSION
3997
			);
3998
		}
3999
4000
		wp_enqueue_style(
4001
			'jetpack',
4002
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4003
			array( 'jetpack-dops-style' ),
4004
			JETPACK__VERSION . '-20121016'
4005
		);
4006
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4007
		wp_style_add_data( 'jetpack', 'suffix', $min );
4008
	}
4009
4010
	function plugin_action_links( $actions ) {
4011
4012
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4013
4014
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4015
			return array_merge(
4016
				$jetpack_home,
4017
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4018
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4019
				$actions
4020
			);
4021
		}
4022
4023
		return array_merge( $jetpack_home, $actions );
4024
	}
4025
4026
	/**
4027
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4028
	 *
4029
	 * @param string $hook The current admin page.
4030
	 *
4031
	 * @return void
4032
	 */
4033
	public function deactivate_dialog( $hook ) {
4034
		if (
4035
			'plugins.php' === $hook
4036
			&& self::is_active()
4037
		) {
4038
4039
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4040
4041
			if ( count( $active_plugins_using_connection ) > 1 ) {
4042
4043
				add_thickbox();
4044
4045
				wp_register_script(
4046
					'jp-tracks',
4047
					'//stats.wp.com/w.js',
4048
					array(),
4049
					gmdate( 'YW' ),
4050
					true
4051
				);
4052
4053
				wp_register_script(
4054
					'jp-tracks-functions',
4055
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4056
					array( 'jp-tracks' ),
4057
					JETPACK__VERSION,
4058
					false
4059
				);
4060
4061
				wp_enqueue_script(
4062
					'jetpack-deactivate-dialog-js',
4063
					Assets::get_file_url_for_environment(
4064
						'_inc/build/jetpack-deactivate-dialog.min.js',
4065
						'_inc/jetpack-deactivate-dialog.js'
4066
					),
4067
					array( 'jquery', 'jp-tracks-functions' ),
4068
					JETPACK__VERSION,
4069
					true
4070
				);
4071
4072
				wp_localize_script(
4073
					'jetpack-deactivate-dialog-js',
4074
					'deactivate_dialog',
4075
					array(
4076
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4077
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4078
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4079
					)
4080
				);
4081
4082
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4083
4084
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4085
			}
4086
		}
4087
	}
4088
4089
	/**
4090
	 * Outputs the content of the deactivation modal
4091
	 *
4092
	 * @return void
4093
	 */
4094
	public function deactivate_dialog_content() {
4095
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4096
		unset( $active_plugins_using_connection['jetpack'] );
4097
		$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 4095 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...
4098
	}
4099
4100
	/**
4101
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4102
	 *
4103
	 * @param string $login_url The wp-login URL.
4104
	 * @param string $redirect  URL to redirect users after logging in.
4105
	 * @since Jetpack 8.4
4106
	 * @return string
4107
	 */
4108
	public function login_url( $login_url, $redirect ) {
4109
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4110
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4111
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4112
		}
4113
		return $login_url;
4114
	}
4115
4116
	/**
4117
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4118
	 *
4119
	 * @since Jetpack 8.4
4120
	 */
4121
	public function login_init() {
4122
		// phpcs:ignore WordPress.Security.NonceVerification
4123
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4124
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4125
			wp_safe_redirect(
4126
				add_query_arg(
4127
					array(
4128
						'forceInstall' => 1,
4129
						'url'          => rawurlencode( get_site_url() ),
4130
					),
4131
					// @todo provide way to go to specific calypso env.
4132
					self::get_calypso_host() . 'jetpack/connect'
4133
				)
4134
			);
4135
			exit;
4136
		}
4137
	}
4138
4139
	/*
4140
	 * Registration flow:
4141
	 * 1 - ::admin_page_load() action=register
4142
	 * 2 - ::try_registration()
4143
	 * 3 - ::register()
4144
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4145
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4146
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4147
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4148
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4149
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4150
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4151
	 *       jetpack_id, jetpack_secret, jetpack_public
4152
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4153
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4154
	 * 5 - user logs in with WP.com account
4155
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4156
	 *		- Manager::authorize()
4157
	 *		- Manager::get_token()
4158
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4159
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4160
	 *			- which responds with access_token, token_type, scope
4161
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4162
	 *		- Jetpack::activate_default_modules()
4163
	 *     		- Deactivates deprecated plugins
4164
	 *     		- Activates all default modules
4165
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4166
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4167
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4168
	 *     Done!
4169
	 */
4170
4171
	/**
4172
	 * Handles the page load events for the Jetpack admin page
4173
	 */
4174
	function admin_page_load() {
4175
		$error = false;
4176
4177
		// Make sure we have the right body class to hook stylings for subpages off of.
4178
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4179
4180
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4181
			// Should only be used in intermediate redirects to preserve state across redirects
4182
			self::restate();
4183
		}
4184
4185
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4186
			// @todo: Add validation against a known allowed list.
4187
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4188
			// User clicked in the iframe to link their accounts
4189
			if ( ! self::connection()->is_user_connected() ) {
4190
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4191
4192
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4193
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4194
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4195
4196
				if ( isset( $_GET['notes_iframe'] ) ) {
4197
					$connect_url .= '&notes_iframe';
4198
				}
4199
				wp_redirect( $connect_url );
4200
				exit;
4201
			} else {
4202
				if ( ! isset( $_GET['calypso_env'] ) ) {
4203
					self::state( 'message', 'already_authorized' );
4204
					wp_safe_redirect( self::admin_url() );
4205
					exit;
4206
				} else {
4207
					$connect_url  = $this->build_connect_url( true, false, $from );
4208
					$connect_url .= '&already_authorized=true';
4209
					wp_redirect( $connect_url );
4210
					exit;
4211
				}
4212
			}
4213
		}
4214
4215
		if ( isset( $_GET['action'] ) ) {
4216
			switch ( $_GET['action'] ) {
4217
				case 'authorize_redirect':
4218
					self::log( 'authorize_redirect' );
4219
4220
					add_filter(
4221
						'allowed_redirect_hosts',
4222
						function ( $domains ) {
4223
							$domains[] = 'jetpack.com';
4224
							$domains[] = 'jetpack.wordpress.com';
4225
							$domains[] = 'wordpress.com';
4226
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4227
							return array_unique( $domains );
4228
						}
4229
					);
4230
4231
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4232
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4233
4234
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4235
						// The destination URL is missing or invalid, nothing to do here.
4236
						exit;
4237
					}
4238
4239
					if ( self::is_active() && self::is_user_connected() ) {
4240
						// The user is either already connected, or finished the connection process.
4241
						wp_safe_redirect( $dest_url );
4242
						exit;
4243
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4244
						// The user decided not to proceed with setting up the connection.
4245
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4246
						exit;
4247
					}
4248
4249
					$redirect_url = self::admin_url(
4250
						array(
4251
							'page'     => 'jetpack',
4252
							'action'   => 'authorize_redirect',
4253
							'dest_url' => rawurlencode( $dest_url ),
4254
							'done'     => '1',
4255
						)
4256
					);
4257
4258
					wp_safe_redirect( static::build_authorize_url( $redirect_url ) );
0 ignored issues
show
Documentation introduced by
$redirect_url 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...
4259
					exit;
4260
				case 'authorize':
4261
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4262
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4263
					exit;
4264
				case 'register':
4265
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4266
						$error = 'cheatin';
4267
						break;
4268
					}
4269
					check_admin_referer( 'jetpack-register' );
4270
					self::log( 'register' );
4271
					self::maybe_set_version_option();
4272
					$registered = self::try_registration();
4273
					if ( is_wp_error( $registered ) ) {
4274
						$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...
4275
						self::state( 'error', $error );
4276
						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...
4277
4278
						/**
4279
						 * Jetpack registration Error.
4280
						 *
4281
						 * @since 7.5.0
4282
						 *
4283
						 * @param string|int $error The error code.
4284
						 * @param \WP_Error $registered The error object.
4285
						 */
4286
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4287
						break;
4288
					}
4289
4290
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4291
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4292
4293
					/**
4294
					 * Jetpack registration Success.
4295
					 *
4296
					 * @since 7.5.0
4297
					 *
4298
					 * @param string $from 'from' GET parameter;
4299
					 */
4300
					do_action( 'jetpack_connection_register_success', $from );
4301
4302
					$url = $this->build_connect_url( true, $redirect, $from );
4303
4304
					if ( ! empty( $_GET['onboarding'] ) ) {
4305
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4306
					}
4307
4308
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4309
						$url = add_query_arg( 'auth_approved', 'true', $url );
4310
					}
4311
4312
					wp_redirect( $url );
4313
					exit;
4314
				case 'activate':
4315
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4316
						$error = 'cheatin';
4317
						break;
4318
					}
4319
4320
					$module = stripslashes( $_GET['module'] );
4321
					check_admin_referer( "jetpack_activate-$module" );
4322
					self::log( 'activate', $module );
4323
					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...
4324
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4325
					}
4326
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4327
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4328
					exit;
4329
				case 'activate_default_modules':
4330
					check_admin_referer( 'activate_default_modules' );
4331
					self::log( 'activate_default_modules' );
4332
					self::restate();
4333
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4334
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4335
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4336
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4337
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4338
					exit;
4339 View Code Duplication
				case 'disconnect':
4340
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4341
						$error = 'cheatin';
4342
						break;
4343
					}
4344
4345
					check_admin_referer( 'jetpack-disconnect' );
4346
					self::log( 'disconnect' );
4347
					self::disconnect();
4348
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4349
					exit;
4350 View Code Duplication
				case 'reconnect':
4351
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4352
						$error = 'cheatin';
4353
						break;
4354
					}
4355
4356
					check_admin_referer( 'jetpack-reconnect' );
4357
					self::log( 'reconnect' );
4358
					self::disconnect();
4359
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4360
					exit;
4361 View Code Duplication
				case 'deactivate':
4362
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4363
						$error = 'cheatin';
4364
						break;
4365
					}
4366
4367
					$modules = stripslashes( $_GET['module'] );
4368
					check_admin_referer( "jetpack_deactivate-$modules" );
4369
					foreach ( explode( ',', $modules ) as $module ) {
4370
						self::log( 'deactivate', $module );
4371
						self::deactivate_module( $module );
4372
						self::state( 'message', 'module_deactivated' );
4373
					}
4374
					self::state( 'module', $modules );
4375
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4376
					exit;
4377
				case 'unlink':
4378
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4379
					check_admin_referer( 'jetpack-unlink' );
4380
					self::log( 'unlink' );
4381
					$this->connection_manager->disconnect_user();
4382
					self::state( 'message', 'unlinked' );
4383
					if ( 'sub-unlink' == $redirect ) {
4384
						wp_safe_redirect( admin_url() );
4385
					} else {
4386
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4387
					}
4388
					exit;
4389
				case 'onboard':
4390
					if ( ! current_user_can( 'manage_options' ) ) {
4391
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4392
					} else {
4393
						self::create_onboarding_token();
4394
						$url = $this->build_connect_url( true );
4395
4396
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4397
							$url = add_query_arg( 'onboarding', $token, $url );
4398
						}
4399
4400
						$calypso_env = $this->get_calypso_env();
4401
						if ( ! empty( $calypso_env ) ) {
4402
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4403
						}
4404
4405
						wp_redirect( $url );
4406
						exit;
4407
					}
4408
					exit;
4409
				default:
4410
					/**
4411
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4412
					 *
4413
					 * @since 2.6.0
4414
					 *
4415
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4416
					 */
4417
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4418
			}
4419
		}
4420
4421
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4422
			self::activate_new_modules( true );
4423
		}
4424
4425
		$message_code = self::state( 'message' );
4426
		if ( self::state( 'optin-manage' ) ) {
4427
			$activated_manage = $message_code;
4428
			$message_code     = 'jetpack-manage';
4429
		}
4430
4431
		switch ( $message_code ) {
4432
			case 'jetpack-manage':
4433
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4434
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4435
				$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>';
4436
				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...
4437
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4438
				}
4439
				break;
4440
4441
		}
4442
4443
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4444
4445
		if ( ! empty( $deactivated_plugins ) ) {
4446
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4447
			$deactivated_titles  = array();
4448
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4449
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4450
					continue;
4451
				}
4452
4453
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4454
			}
4455
4456
			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...
4457
				if ( $this->message ) {
4458
					$this->message .= "<br /><br />\n";
4459
				}
4460
4461
				$this->message .= wp_sprintf(
4462
					_n(
4463
						'Jetpack contains the most recent version of the old %l plugin.',
4464
						'Jetpack contains the most recent versions of the old %l plugins.',
4465
						count( $deactivated_titles ),
4466
						'jetpack'
4467
					),
4468
					$deactivated_titles
4469
				);
4470
4471
				$this->message .= "<br />\n";
4472
4473
				$this->message .= _n(
4474
					'The old version has been deactivated and can be removed from your site.',
4475
					'The old versions have been deactivated and can be removed from your site.',
4476
					count( $deactivated_titles ),
4477
					'jetpack'
4478
				);
4479
			}
4480
		}
4481
4482
		$this->privacy_checks = self::state( 'privacy_checks' );
4483
4484
		if ( $this->message || $this->error || $this->privacy_checks ) {
4485
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4486
		}
4487
4488
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4489
	}
4490
4491
	function admin_notices() {
4492
4493
		if ( $this->error ) {
4494
			?>
4495
<div id="message" class="jetpack-message jetpack-err">
4496
	<div class="squeezer">
4497
		<h2>
4498
			<?php
4499
			echo wp_kses(
4500
				$this->error,
4501
				array(
4502
					'a'      => array( 'href' => array() ),
4503
					'small'  => true,
4504
					'code'   => true,
4505
					'strong' => true,
4506
					'br'     => true,
4507
					'b'      => true,
4508
				)
4509
			);
4510
			?>
4511
			</h2>
4512
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4513
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4514
<?php	endif; ?>
4515
	</div>
4516
</div>
4517
			<?php
4518
		}
4519
4520
		if ( $this->message ) {
4521
			?>
4522
<div id="message" class="jetpack-message">
4523
	<div class="squeezer">
4524
		<h2>
4525
			<?php
4526
			echo wp_kses(
4527
				$this->message,
4528
				array(
4529
					'strong' => array(),
4530
					'a'      => array( 'href' => true ),
4531
					'br'     => true,
4532
				)
4533
			);
4534
			?>
4535
			</h2>
4536
	</div>
4537
</div>
4538
			<?php
4539
		}
4540
4541
		if ( $this->privacy_checks ) :
4542
			$module_names = $module_slugs = array();
4543
4544
			$privacy_checks = explode( ',', $this->privacy_checks );
4545
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4546
			foreach ( $privacy_checks as $module_slug ) {
4547
				$module = self::get_module( $module_slug );
4548
				if ( ! $module ) {
4549
					continue;
4550
				}
4551
4552
				$module_slugs[] = $module_slug;
4553
				$module_names[] = "<strong>{$module['name']}</strong>";
4554
			}
4555
4556
			$module_slugs = join( ',', $module_slugs );
4557
			?>
4558
<div id="message" class="jetpack-message jetpack-err">
4559
	<div class="squeezer">
4560
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4561
		<p>
4562
			<?php
4563
			echo wp_kses(
4564
				wptexturize(
4565
					wp_sprintf(
4566
						_nx(
4567
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4568
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4569
							count( $privacy_checks ),
4570
							'%l = list of Jetpack module/feature names',
4571
							'jetpack'
4572
						),
4573
						$module_names
4574
					)
4575
				),
4576
				array( 'strong' => true )
4577
			);
4578
4579
			echo "\n<br />\n";
4580
4581
			echo wp_kses(
4582
				sprintf(
4583
					_nx(
4584
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4585
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4586
						count( $privacy_checks ),
4587
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4588
						'jetpack'
4589
					),
4590
					wp_nonce_url(
4591
						self::admin_url(
4592
							array(
4593
								'page'   => 'jetpack',
4594
								'action' => 'deactivate',
4595
								'module' => urlencode( $module_slugs ),
4596
							)
4597
						),
4598
						"jetpack_deactivate-$module_slugs"
4599
					),
4600
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4601
				),
4602
				array(
4603
					'a' => array(
4604
						'href'  => true,
4605
						'title' => true,
4606
					),
4607
				)
4608
			);
4609
			?>
4610
		</p>
4611
	</div>
4612
</div>
4613
			<?php
4614
endif;
4615
	}
4616
4617
	/**
4618
	 * We can't always respond to a signed XML-RPC request with a
4619
	 * helpful error message. In some circumstances, doing so could
4620
	 * leak information.
4621
	 *
4622
	 * Instead, track that the error occurred via a Jetpack_Option,
4623
	 * and send that data back in the heartbeat.
4624
	 * All this does is increment a number, but it's enough to find
4625
	 * trends.
4626
	 *
4627
	 * @param WP_Error $xmlrpc_error The error produced during
4628
	 *                               signature validation.
4629
	 */
4630
	function track_xmlrpc_error( $xmlrpc_error ) {
4631
		$code = is_wp_error( $xmlrpc_error )
4632
			? $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...
4633
			: 'should-not-happen';
4634
4635
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4636
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4637
			// No need to update the option if we already have
4638
			// this code stored.
4639
			return;
4640
		}
4641
		$xmlrpc_errors[ $code ] = true;
4642
4643
		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...
4644
	}
4645
4646
	/**
4647
	 * Initialize the jetpack stats instance only when needed
4648
	 *
4649
	 * @return void
4650
	 */
4651
	private function initialize_stats() {
4652
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4653
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4654
		}
4655
	}
4656
4657
	/**
4658
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4659
	 */
4660
	function stat( $group, $detail ) {
4661
		$this->initialize_stats();
4662
		$this->a8c_mc_stats_instance->add( $group, $detail );
4663
4664
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4665
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4666
	}
4667
4668
	/**
4669
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4670
	 */
4671
	function do_stats( $method = '' ) {
4672
		$this->initialize_stats();
4673
		if ( 'server_side' === $method ) {
4674
			$this->a8c_mc_stats_instance->do_server_side_stats();
4675
		} else {
4676
			$this->a8c_mc_stats_instance->do_stats();
4677
		}
4678
4679
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4680
		$this->stats = array();
4681
	}
4682
4683
	/**
4684
	 * Runs stats code for a one-off, server-side.
4685
	 *
4686
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4687
	 *
4688
	 * @return bool If it worked.
4689
	 */
4690
	static function do_server_side_stat( $args ) {
4691
		$url                   = self::build_stats_url( $args );
4692
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4693
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4694
	}
4695
4696
	/**
4697
	 * Builds the stats url.
4698
	 *
4699
	 * @param $args array|string The arguments to append to the URL.
4700
	 *
4701
	 * @return string The URL to be pinged.
4702
	 */
4703
	static function build_stats_url( $args ) {
4704
4705
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4706
		return $a8c_mc_stats_instance->build_stats_url( $args );
4707
4708
	}
4709
4710
	/**
4711
	 * Builds a URL to the Jetpack connection auth page
4712
	 *
4713
	 * @since 3.9.5
4714
	 *
4715
	 * @param bool        $raw If true, URL will not be escaped.
4716
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4717
	 *                              If string, will be a custom redirect.
4718
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4719
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4720
	 *
4721
	 * @return string Connect URL
4722
	 */
4723
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4724
		$site_id    = Jetpack_Options::get_option( 'id' );
4725
		$blog_token = ( new Tokens() )->get_access_token();
4726
4727
		if ( $register || ! $blog_token || ! $site_id ) {
4728
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4729
4730
			if ( ! empty( $redirect ) ) {
4731
				$url = add_query_arg(
4732
					'redirect',
4733
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4734
					$url
4735
				);
4736
			}
4737
4738
			if ( is_network_admin() ) {
4739
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4740
			}
4741
4742
			$calypso_env = self::get_calypso_env();
4743
4744
			if ( ! empty( $calypso_env ) ) {
4745
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4746
			}
4747
		} else {
4748
4749
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4750
			// because otherwise this logic can get us in to a loop.
4751
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4752
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4753
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4754
4755
				$response = Client::wpcom_json_api_request_as_blog(
4756
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4757
					'1.1'
4758
				);
4759
4760
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4761
4762
					// Generating a register URL instead to refresh the existing token
4763
					return $this->build_connect_url( $raw, $redirect, $from, true );
4764
				}
4765
			}
4766
4767
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4723 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...
4768
		}
4769
4770
		if ( $from ) {
4771
			$url = add_query_arg( 'from', $from, $url );
4772
		}
4773
4774
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4775
		/**
4776
		 * Filter the URL used when connecting a user to a WordPress.com account.
4777
		 *
4778
		 * @since 8.1.0
4779
		 *
4780
		 * @param string $url Connection URL.
4781
		 * @param bool   $raw If true, URL will not be escaped.
4782
		 */
4783
		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...
4784
	}
4785
4786
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4787
4788
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4789
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4790
4791
		if ( $iframe ) {
4792
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4793
		}
4794
4795
		$c8n = self::connection();
4796
		$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...
4797
4798
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4799
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4800
4801
		if ( $iframe ) {
4802
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4803
		}
4804
4805
		/**
4806
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4807
		 *
4808
		 * @since 8.9.0
4809
		 *
4810
		 * @param string $url Connection URL.
4811
		 */
4812
		return apply_filters( 'jetpack_build_authorize_url', $url );
4813
	}
4814
4815
	/**
4816
	 * Filters the connection URL parameter array.
4817
	 *
4818
	 * @param array $args default URL parameters used by the package.
4819
	 * @return array the modified URL arguments array.
4820
	 */
4821
	public static function filter_connect_request_body( $args ) {
4822
		if (
4823
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4824
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4825
		) {
4826
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4827
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4828
				? $gp_locale->slug
4829
				: '';
4830
		}
4831
4832
		$tracking        = new Tracking();
4833
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4834
4835
		$args = array_merge(
4836
			$args,
4837
			array(
4838
				'_ui' => $tracks_identity['_ui'],
4839
				'_ut' => $tracks_identity['_ut'],
4840
			)
4841
		);
4842
4843
		$calypso_env = self::get_calypso_env();
4844
4845
		if ( ! empty( $calypso_env ) ) {
4846
			$args['calypso_env'] = $calypso_env;
4847
		}
4848
4849
		return $args;
4850
	}
4851
4852
	/**
4853
	 * Filters the URL that will process the connection data. It can be different from the URL
4854
	 * that we send the user to after everything is done.
4855
	 *
4856
	 * @param String $processing_url the default redirect URL used by the package.
4857
	 * @return String the modified URL.
4858
	 *
4859
	 * @deprecated since Jetpack 9.5.0
4860
	 */
4861
	public static function filter_connect_processing_url( $processing_url ) {
4862
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4863
4864
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4865
		return $processing_url;
4866
	}
4867
4868
	/**
4869
	 * Filters the redirection URL that is used for connect requests. The redirect
4870
	 * URL should return the user back to the Jetpack console.
4871
	 *
4872
	 * @param String $redirect the default redirect URL used by the package.
4873
	 * @return String the modified URL.
4874
	 */
4875
	public static function filter_connect_redirect_url( $redirect ) {
4876
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4877
		$redirect           = $redirect
4878
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4879
			: $jetpack_admin_page;
4880
4881
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4882
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4883
		}
4884
4885
		return $redirect;
4886
	}
4887
4888
	/**
4889
	 * This action fires at the beginning of the Manager::authorize method.
4890
	 */
4891
	public static function authorize_starting() {
4892
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4893
		// Checking if site has been active/connected previously before recording unique connection.
4894
		if ( ! $jetpack_unique_connection ) {
4895
			// jetpack_unique_connection option has never been set.
4896
			$jetpack_unique_connection = array(
4897
				'connected'    => 0,
4898
				'disconnected' => 0,
4899
				'version'      => '3.6.1',
4900
			);
4901
4902
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4903
4904
			// Track unique connection.
4905
			$jetpack = self::init();
4906
4907
			$jetpack->stat( 'connections', 'unique-connection' );
4908
			$jetpack->do_stats( 'server_side' );
4909
		}
4910
4911
		// Increment number of times connected.
4912
		$jetpack_unique_connection['connected'] += 1;
4913
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4914
	}
4915
4916
	/**
4917
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4918
	 * linked.
4919
	 */
4920
	public static function authorize_ending_linked() {
4921
		// Don't activate anything since we are just connecting a user.
4922
		self::state( 'message', 'linked' );
4923
	}
4924
4925
	/**
4926
	 * This action fires at the end of the Manager::authorize method when the master user is
4927
	 * authorized.
4928
	 *
4929
	 * @param array $data The request data.
4930
	 */
4931
	public static function authorize_ending_authorized( $data ) {
4932
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4933
		self::invalidate_onboarding_token();
4934
4935
		// If redirect_uri is SSO, ensure SSO module is enabled.
4936
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4937
4938
		/** This filter is documented in class.jetpack-cli.php */
4939
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4940
4941
		$activate_sso = (
4942
			isset( $redirect_options['action'] ) &&
4943
			'jetpack-sso' === $redirect_options['action'] &&
4944
			$jetpack_start_enable_sso
4945
		);
4946
4947
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4948
4949
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4950
	}
4951
4952
	/**
4953
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4954
	 * reconnect process is completed.
4955
	 * Note that this currently only happens when we don't need the user to re-authorize
4956
	 * their WP.com account, eg in cases where we are restoring a connection with
4957
	 * unhealthy blog token.
4958
	 */
4959
	public static function reconnection_completed() {
4960
		self::state( 'message', 'reconnection_completed' );
4961
	}
4962
4963
	/**
4964
	 * Get our assumed site creation date.
4965
	 * Calculated based on the earlier date of either:
4966
	 * - Earliest admin user registration date.
4967
	 * - Earliest date of post of any post type.
4968
	 *
4969
	 * @since 7.2.0
4970
	 * @deprecated since 7.8.0
4971
	 *
4972
	 * @return string Assumed site creation date and time.
4973
	 */
4974
	public static function get_assumed_site_creation_date() {
4975
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4976
		return self::connection()->get_assumed_site_creation_date();
4977
	}
4978
4979 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4980
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4981
4982
		if ( $activation_source_name ) {
4983
			$args['_as'] = urlencode( $activation_source_name );
4984
		}
4985
4986
		if ( $activation_source_keyword ) {
4987
			$args['_ak'] = urlencode( $activation_source_keyword );
4988
		}
4989
	}
4990
4991
	function build_reconnect_url( $raw = false ) {
4992
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4993
		return $raw ? $url : esc_url( $url );
4994
	}
4995
4996
	public static function admin_url( $args = null ) {
4997
		$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...
4998
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4999
		return $url;
5000
	}
5001
5002
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5003
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5004
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5005
	}
5006
5007
	function dismiss_jetpack_notice() {
5008
5009
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5010
			return;
5011
		}
5012
5013
		switch ( $_GET['jetpack-notice'] ) {
5014
			case 'dismiss':
5015
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5016
5017
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5018
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5019
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5020
				}
5021
				break;
5022
		}
5023
	}
5024
5025
	public static function sort_modules( $a, $b ) {
5026
		if ( $a['sort'] == $b['sort'] ) {
5027
			return 0;
5028
		}
5029
5030
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5031
	}
5032
5033
	function ajax_recheck_ssl() {
5034
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5035
		$result = self::permit_ssl( true );
5036
		wp_send_json(
5037
			array(
5038
				'enabled' => $result,
5039
				'message' => get_transient( 'jetpack_https_test_message' ),
5040
			)
5041
		);
5042
	}
5043
5044
	/* Client API */
5045
5046
	/**
5047
	 * Returns the requested Jetpack API URL
5048
	 *
5049
	 * @deprecated since 7.7
5050
	 * @return string
5051
	 */
5052
	public static function api_url( $relative_url ) {
5053
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5054
		$connection = self::connection();
5055
		return $connection->api_url( $relative_url );
5056
	}
5057
5058
	/**
5059
	 * @deprecated 8.0
5060
	 *
5061
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5062
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5063
	 */
5064
	public static function fix_url_for_bad_hosts( $url ) {
5065
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5066
		return $url;
5067
	}
5068
5069
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5070
		// Default to a blog token.
5071
		$token_type = 'blog';
5072
5073
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5074
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5075
			if ( ! empty( $_GET['onboarding'] ) ) {
5076
				$jpo = $_GET;
5077
			} else {
5078
				$jpo = json_decode( $request_data, true );
5079
			}
5080
5081
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5082
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5083
5084
			if (
5085
				isset( $jpo_user )
5086
				&& isset( $jpo_token )
5087
				&& is_email( $jpo_user )
5088
				&& ctype_alnum( $jpo_token )
5089
				&& isset( $_GET['rest_route'] )
5090
				&& self::validate_onboarding_token_action(
5091
					$jpo_token,
5092
					$_GET['rest_route']
5093
				)
5094
			) {
5095
				$jp_user = get_user_by( 'email', $jpo_user );
5096
				if ( is_a( $jp_user, 'WP_User' ) ) {
5097
					wp_set_current_user( $jp_user->ID );
5098
					$user_can = is_multisite()
5099
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5100
						: current_user_can( 'manage_options' );
5101
					if ( $user_can ) {
5102
						$token_type              = 'user';
5103
						$token->external_user_id = $jp_user->ID;
5104
					}
5105
				}
5106
			}
5107
5108
			$token_data['type']    = $token_type;
5109
			$token_data['user_id'] = $token->external_user_id;
5110
		}
5111
5112
		return $token_data;
5113
	}
5114
5115
	/**
5116
	 * Create a random secret for validating onboarding payload
5117
	 *
5118
	 * @return string Secret token
5119
	 */
5120
	public static function create_onboarding_token() {
5121
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5122
			$token = wp_generate_password( 32, false );
5123
			Jetpack_Options::update_option( 'onboarding', $token );
5124
		}
5125
5126
		return $token;
5127
	}
5128
5129
	/**
5130
	 * Remove the onboarding token
5131
	 *
5132
	 * @return bool True on success, false on failure
5133
	 */
5134
	public static function invalidate_onboarding_token() {
5135
		return Jetpack_Options::delete_option( 'onboarding' );
5136
	}
5137
5138
	/**
5139
	 * Validate an onboarding token for a specific action
5140
	 *
5141
	 * @return boolean True if token/action pair is accepted, false if not
5142
	 */
5143
	public static function validate_onboarding_token_action( $token, $action ) {
5144
		// Compare tokens, bail if tokens do not match
5145
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5146
			return false;
5147
		}
5148
5149
		// List of valid actions we can take
5150
		$valid_actions = array(
5151
			'/jetpack/v4/settings',
5152
		);
5153
5154
		// Only allow valid actions.
5155
		if ( ! in_array( $action, $valid_actions ) ) {
5156
			return false;
5157
		}
5158
5159
		return true;
5160
	}
5161
5162
	/**
5163
	 * Checks to see if the URL is using SSL to connect with Jetpack
5164
	 *
5165
	 * @since 2.3.3
5166
	 * @return boolean
5167
	 */
5168
	public static function permit_ssl( $force_recheck = false ) {
5169
		// Do some fancy tests to see if ssl is being supported
5170
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5171
			$message = '';
5172
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5173
				$ssl = 0;
5174
			} else {
5175
				$ssl = 1;
5176
5177
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5178
					$ssl     = 0;
5179
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5180
				} else {
5181
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5182
					if ( is_wp_error( $response ) ) {
5183
						$ssl     = 0;
5184
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5185
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5186
						$ssl     = 0;
5187
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5188
					}
5189
				}
5190
			}
5191
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5192
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5193
		}
5194
5195
		return (bool) $ssl;
5196
	}
5197
5198
	/*
5199
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5200
	 */
5201
	public function alert_auto_ssl_fail() {
5202
		if ( ! current_user_can( 'manage_options' ) ) {
5203
			return;
5204
		}
5205
5206
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5207
		?>
5208
5209
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5210
			<div class="jp-banner__content">
5211
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5212
				<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>
5213
				<p>
5214
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5215
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5216
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5217
				</p>
5218
				<p>
5219
					<?php
5220
					printf(
5221
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5222
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5223
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5224
					);
5225
					?>
5226
				</p>
5227
			</div>
5228
		</div>
5229
		<style>
5230
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5231
		</style>
5232
		<script type="text/javascript">
5233
			jQuery( document ).ready( function( $ ) {
5234
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5235
					var $this = $( this );
5236
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5237
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5238
					e.preventDefault();
5239
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5240
					$.post( ajaxurl, data )
5241
					  .done( function( response ) {
5242
						  if ( response.enabled ) {
5243
							  $( '#jetpack-ssl-warning' ).hide();
5244
						  } else {
5245
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5246
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5247
						  }
5248
					  }.bind( $this ) );
5249
				} );
5250
			} );
5251
		</script>
5252
5253
		<?php
5254
	}
5255
5256
	/**
5257
	 * Returns the Jetpack XML-RPC API
5258
	 *
5259
	 * @deprecated 8.0 Use Connection_Manager instead.
5260
	 * @return string
5261
	 */
5262
	public static function xmlrpc_api_url() {
5263
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5264
		return self::connection()->xmlrpc_api_url();
5265
	}
5266
5267
	/**
5268
	 * Returns the connection manager object.
5269
	 *
5270
	 * @return Automattic\Jetpack\Connection\Manager
5271
	 */
5272
	public static function connection() {
5273
		$jetpack = static::init();
5274
5275
		// If the connection manager hasn't been instantiated, do that now.
5276
		if ( ! $jetpack->connection_manager ) {
5277
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5278
		}
5279
5280
		return $jetpack->connection_manager;
5281
	}
5282
5283
	/**
5284
	 * Creates two secret tokens and the end of life timestamp for them.
5285
	 *
5286
	 * Note these tokens are unique per call, NOT static per site for connecting.
5287
	 *
5288
	 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5289
	 *
5290
	 * @since 2.6
5291
	 * @param String  $action  The action name.
5292
	 * @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...
5293
	 * @param Integer $exp     Expiration time in seconds.
5294
	 * @return array
5295
	 */
5296
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5297
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5298
		return ( new Secrets() )->generate( $action, $user_id, $exp );
5299
	}
5300
5301
	public static function get_secrets( $action, $user_id ) {
5302
		$secrets = ( new Secrets() )->get( $action, $user_id );
5303
5304
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5305
			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...
5306
		}
5307
5308
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5309
			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...
5310
		}
5311
5312
		return $secrets;
5313
	}
5314
5315
	/**
5316
	 * Builds the timeout limit for queries talking with the wpcom servers.
5317
	 *
5318
	 * Based on local php max_execution_time in php.ini
5319
	 *
5320
	 * @since 2.6
5321
	 * @return int
5322
	 * @deprecated
5323
	 **/
5324
	public function get_remote_query_timeout_limit() {
5325
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5326
		return self::get_max_execution_time();
5327
	}
5328
5329
	/**
5330
	 * Builds the timeout limit for queries talking with the wpcom servers.
5331
	 *
5332
	 * Based on local php max_execution_time in php.ini
5333
	 *
5334
	 * @since 5.4
5335
	 * @return int
5336
	 **/
5337
	public static function get_max_execution_time() {
5338
		$timeout = (int) ini_get( 'max_execution_time' );
5339
5340
		// Ensure exec time set in php.ini
5341
		if ( ! $timeout ) {
5342
			$timeout = 30;
5343
		}
5344
		return $timeout;
5345
	}
5346
5347
	/**
5348
	 * Sets a minimum request timeout, and returns the current timeout
5349
	 *
5350
	 * @since 5.4
5351
	 **/
5352 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5353
		$timeout = self::get_max_execution_time();
5354
		if ( $timeout < $min_timeout ) {
5355
			$timeout = $min_timeout;
5356
			set_time_limit( $timeout );
5357
		}
5358
		return $timeout;
5359
	}
5360
5361
	/**
5362
	 * Takes the response from the Jetpack register new site endpoint and
5363
	 * verifies it worked properly.
5364
	 *
5365
	 * @since 2.6
5366
	 * @deprecated since 7.7.0
5367
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5368
	 **/
5369
	public function validate_remote_register_response() {
5370
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5371
	}
5372
5373
	/**
5374
	 * @return bool|WP_Error
5375
	 */
5376
	public static function register() {
5377
		$tracking = new Tracking();
5378
		$tracking->record_user_event( 'jpc_register_begin' );
5379
5380
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5381
5382
		$connection   = self::connection();
5383
		$registration = $connection->register();
5384
5385
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5386
5387
		if ( ! $registration || is_wp_error( $registration ) ) {
5388
			return $registration;
5389
		}
5390
5391
		return true;
5392
	}
5393
5394
	/**
5395
	 * Filters the registration request body to include tracking properties.
5396
	 *
5397
	 * @param array $properties
5398
	 * @return array amended properties.
5399
	 */
5400 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5401
		$tracking        = new Tracking();
5402
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5403
5404
		return array_merge(
5405
			$properties,
5406
			array(
5407
				'_ui' => $tracks_identity['_ui'],
5408
				'_ut' => $tracks_identity['_ut'],
5409
			)
5410
		);
5411
	}
5412
5413
	/**
5414
	 * Filters the token request body to include tracking properties.
5415
	 *
5416
	 * @param array $properties
5417
	 * @return array amended properties.
5418
	 */
5419 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5420
		$tracking        = new Tracking();
5421
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5422
5423
		return array_merge(
5424
			$properties,
5425
			array(
5426
				'_ui' => $tracks_identity['_ui'],
5427
				'_ut' => $tracks_identity['_ut'],
5428
			)
5429
		);
5430
	}
5431
5432
	/**
5433
	 * If the db version is showing something other that what we've got now, bump it to current.
5434
	 *
5435
	 * @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...
5436
	 */
5437
	public static function maybe_set_version_option() {
5438
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5439
		if ( JETPACK__VERSION != $version ) {
5440
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5441
5442
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5443
				/** This action is documented in class.jetpack.php */
5444
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5445
			}
5446
5447
			return true;
5448
		}
5449
		return false;
5450
	}
5451
5452
	/* Client Server API */
5453
5454
	/**
5455
	 * Loads the Jetpack XML-RPC client.
5456
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5457
	 *
5458
	 * @deprecated since 7.7.0
5459
	 */
5460
	public static function load_xml_rpc_client() {
5461
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5462
	}
5463
5464
	/**
5465
	 * Resets the saved authentication state in between testing requests.
5466
	 *
5467
	 * @deprecated since 8.9.0
5468
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5469
	 */
5470
	public function reset_saved_auth_state() {
5471
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5472
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5473
	}
5474
5475
	/**
5476
	 * Verifies the signature of the current request.
5477
	 *
5478
	 * @deprecated since 7.7.0
5479
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5480
	 *
5481
	 * @return false|array
5482
	 */
5483
	public function verify_xml_rpc_signature() {
5484
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5485
		return self::connection()->verify_xml_rpc_signature();
5486
	}
5487
5488
	/**
5489
	 * Verifies the signature of the current request.
5490
	 *
5491
	 * This function has side effects and should not be used. Instead,
5492
	 * use the memoized version `->verify_xml_rpc_signature()`.
5493
	 *
5494
	 * @deprecated since 7.7.0
5495
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5496
	 * @internal
5497
	 */
5498
	private function internal_verify_xml_rpc_signature() {
5499
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5500
	}
5501
5502
	/**
5503
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5504
	 *
5505
	 * @deprecated since 7.7.0
5506
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5507
	 *
5508
	 * @param \WP_User|mixed $user     User object if authenticated.
5509
	 * @param string         $username Username.
5510
	 * @param string         $password Password string.
5511
	 * @return \WP_User|mixed Authenticated user or error.
5512
	 */
5513 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5514
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5515
5516
		if ( ! $this->connection_manager ) {
5517
			$this->connection_manager = new Connection_Manager();
5518
		}
5519
5520
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5521
	}
5522
5523
	/**
5524
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5525
	 * Uses the existing XMLRPC request signing implementation.
5526
	 *
5527
	 * @deprecated since 8.9.0
5528
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5529
	 */
5530
	function wp_rest_authenticate( $user ) {
5531
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5532
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5533
	}
5534
5535
	/**
5536
	 * Report authentication status to the WP REST API.
5537
	 *
5538
	 * @deprecated since 8.9.0
5539
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5540
	 *
5541
	 * @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...
5542
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5543
	 */
5544
	public function wp_rest_authentication_errors( $value ) {
5545
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5546
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5547
	}
5548
5549
	/**
5550
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5551
	 * Capture it here so we can verify the signature later.
5552
	 *
5553
	 * @deprecated since 7.7.0
5554
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5555
	 *
5556
	 * @param array $methods XMLRPC methods.
5557
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5558
	 */
5559 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5560
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5561
5562
		if ( ! $this->connection_manager ) {
5563
			$this->connection_manager = new Connection_Manager();
5564
		}
5565
5566
		return $this->connection_manager->xmlrpc_methods( $methods );
5567
	}
5568
5569
	/**
5570
	 * Register additional public XMLRPC methods.
5571
	 *
5572
	 * @deprecated since 7.7.0
5573
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5574
	 *
5575
	 * @param array $methods Public XMLRPC methods.
5576
	 * @return array Public XMLRPC methods, with the getOptions one.
5577
	 */
5578 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5579
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5580
5581
		if ( ! $this->connection_manager ) {
5582
			$this->connection_manager = new Connection_Manager();
5583
		}
5584
5585
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5586
	}
5587
5588
	/**
5589
	 * Handles a getOptions XMLRPC method call.
5590
	 *
5591
	 * @deprecated since 7.7.0
5592
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5593
	 *
5594
	 * @param array $args method call arguments.
5595
	 * @return array an amended XMLRPC server options array.
5596
	 */
5597 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5598
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5599
5600
		if ( ! $this->connection_manager ) {
5601
			$this->connection_manager = new Connection_Manager();
5602
		}
5603
5604
		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...
5605
	}
5606
5607
	/**
5608
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5609
	 *
5610
	 * @deprecated since 7.7.0
5611
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5612
	 *
5613
	 * @param array $options Standard Core options.
5614
	 * @return array Amended options.
5615
	 */
5616 View Code Duplication
	public function xmlrpc_options( $options ) {
5617
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5618
5619
		if ( ! $this->connection_manager ) {
5620
			$this->connection_manager = new Connection_Manager();
5621
		}
5622
5623
		return $this->connection_manager->xmlrpc_options( $options );
5624
	}
5625
5626
	/**
5627
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5628
	 * SET: state( $key, $value );
5629
	 * GET: $value = state( $key );
5630
	 *
5631
	 * @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...
5632
	 * @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...
5633
	 * @param bool   $restate private
5634
	 */
5635
	public static function state( $key = null, $value = null, $restate = false ) {
5636
		static $state = array();
5637
		static $path, $domain;
5638
		if ( ! isset( $path ) ) {
5639
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5640
			$admin_url = self::admin_url();
5641
			$bits      = wp_parse_url( $admin_url );
5642
5643
			if ( is_array( $bits ) ) {
5644
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5645
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5646
			} else {
5647
				$path = $domain = null;
5648
			}
5649
		}
5650
5651
		// Extract state from cookies and delete cookies
5652
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5653
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5654
			unset( $_COOKIE['jetpackState'] );
5655
			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...
5656
				if ( strlen( $v ) ) {
5657
					$state[ $k ] = $v;
5658
				}
5659
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5660
			}
5661
		}
5662
5663
		if ( $restate ) {
5664
			foreach ( $state as $k => $v ) {
5665
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5666
			}
5667
			return;
5668
		}
5669
5670
		// Get a state variable.
5671
		if ( isset( $key ) && ! isset( $value ) ) {
5672
			if ( array_key_exists( $key, $state ) ) {
5673
				return $state[ $key ];
5674
			}
5675
			return null;
5676
		}
5677
5678
		// Set a state variable.
5679
		if ( isset( $key ) && isset( $value ) ) {
5680
			if ( is_array( $value ) && isset( $value[0] ) ) {
5681
				$value = $value[0];
5682
			}
5683
			$state[ $key ] = $value;
5684
			if ( ! headers_sent() ) {
5685
				if ( self::should_set_cookie( $key ) ) {
5686
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5687
				}
5688
			}
5689
		}
5690
	}
5691
5692
	public static function restate() {
5693
		self::state( null, null, true );
5694
	}
5695
5696
	/**
5697
	 * Determines whether the jetpackState[$key] value should be added to the
5698
	 * cookie.
5699
	 *
5700
	 * @param string $key The state key.
5701
	 *
5702
	 * @return boolean Whether the value should be added to the cookie.
5703
	 */
5704
	public static function should_set_cookie( $key ) {
5705
		global $current_screen;
5706
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5707
5708
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5709
			return false;
5710
		}
5711
5712
		return true;
5713
	}
5714
5715
	public static function check_privacy( $file ) {
5716
		static $is_site_publicly_accessible = null;
5717
5718
		if ( is_null( $is_site_publicly_accessible ) ) {
5719
			$is_site_publicly_accessible = false;
5720
5721
			$rpc = new Jetpack_IXR_Client();
5722
5723
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5724
			if ( $success ) {
5725
				$response = $rpc->getResponse();
5726
				if ( $response ) {
5727
					$is_site_publicly_accessible = true;
5728
				}
5729
			}
5730
5731
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5732
		}
5733
5734
		if ( $is_site_publicly_accessible ) {
5735
			return;
5736
		}
5737
5738
		$module_slug = self::get_module_slug( $file );
5739
5740
		$privacy_checks = self::state( 'privacy_checks' );
5741
		if ( ! $privacy_checks ) {
5742
			$privacy_checks = $module_slug;
5743
		} else {
5744
			$privacy_checks .= ",$module_slug";
5745
		}
5746
5747
		self::state( 'privacy_checks', $privacy_checks );
5748
	}
5749
5750
	/**
5751
	 * Helper method for multicall XMLRPC.
5752
	 *
5753
	 * @deprecated since 8.9.0
5754
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5755
	 *
5756
	 * @param ...$args Args for the async_call.
5757
	 */
5758
	public static function xmlrpc_async_call( ...$args ) {
5759
5760
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5761
5762
		global $blog_id;
5763
		static $clients = array();
5764
5765
		$client_blog_id = is_multisite() ? $blog_id : 0;
5766
5767
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5768
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5769
			if ( function_exists( 'ignore_user_abort' ) ) {
5770
				ignore_user_abort( true );
5771
			}
5772
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5773
		}
5774
5775
		if ( ! empty( $args[0] ) ) {
5776
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5777
		} elseif ( is_multisite() ) {
5778
			foreach ( $clients as $client_blog_id => $client ) {
5779
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5780
					continue;
5781
				}
5782
5783
				$switch_success = switch_to_blog( $client_blog_id, true );
5784
				if ( ! $switch_success ) {
5785
					continue;
5786
				}
5787
5788
				flush();
5789
				$client->query();
5790
5791
				restore_current_blog();
5792
			}
5793
		} else {
5794
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5795
				flush();
5796
				$clients[0]->query();
5797
			}
5798
		}
5799
	}
5800
5801
	/**
5802
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5803
	 *
5804
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5805
	 *
5806
	 * @param string $url WordPress.com static resource URL.
5807
	 */
5808
	public static function staticize_subdomain( $url ) {
5809
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5810
		return Assets::staticize_subdomain( $url );
5811
	}
5812
5813
	/* JSON API Authorization */
5814
5815
	/**
5816
	 * Handles the login action for Authorizing the JSON API
5817
	 */
5818
	function login_form_json_api_authorization() {
5819
		$this->verify_json_api_authorization_request();
5820
5821
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5822
5823
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5824
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5825
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5826
	}
5827
5828
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5829
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5830
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5831
			return $url;
5832
		}
5833
5834
		$parsed_url = wp_parse_url( $url );
5835
		$url        = strtok( $url, '?' );
5836
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5837
		if ( ! empty( $parsed_url['query'] ) ) {
5838
			$url .= "&{$parsed_url['query']}";
5839
		}
5840
5841
		return $url;
5842
	}
5843
5844
	// Make sure the POSTed request is handled by the same action
5845
	function preserve_action_in_login_form_for_json_api_authorization() {
5846
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5847
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5848
	}
5849
5850
	// If someone logs in to approve API access, store the Access Code in usermeta
5851
	function store_json_api_authorization_token( $user_login, $user ) {
5852
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5853
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5854
		$token = wp_generate_password( 32, false );
5855
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5856
	}
5857
5858
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5859
	function allow_wpcom_public_api_domain( $domains ) {
5860
		$domains[] = 'public-api.wordpress.com';
5861
		return $domains;
5862
	}
5863
5864
	static function is_redirect_encoded( $redirect_url ) {
5865
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5866
	}
5867
5868
	// Add all wordpress.com environments to the safe redirect allowed list.
5869
	function allow_wpcom_environments( $domains ) {
5870
		$domains[] = 'wordpress.com';
5871
		$domains[] = 'wpcalypso.wordpress.com';
5872
		$domains[] = 'horizon.wordpress.com';
5873
		$domains[] = 'calypso.localhost';
5874
		return $domains;
5875
	}
5876
5877
	// Add the Access Code details to the public-api.wordpress.com redirect
5878
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5879
		return add_query_arg(
5880
			urlencode_deep(
5881
				array(
5882
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5883
					'jetpack-user-id' => (int) $user->ID,
5884
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5885
				)
5886
			),
5887
			$redirect_to
5888
		);
5889
	}
5890
5891
	/**
5892
	 * Verifies the request by checking the signature
5893
	 *
5894
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5895
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5896
	 *
5897
	 * @param null|array $environment
5898
	 */
5899
	function verify_json_api_authorization_request( $environment = null ) {
5900
		$environment = is_null( $environment )
5901
			? $_REQUEST
5902
			: $environment;
5903
5904
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
5905
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version 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 = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
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::connection()->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