Completed
Push — fix/social-previews-responsive... ( 411de4...5d9f76 )
by
unknown
130:08 queued 121:24
created

class.jetpack.php (83 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
8
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Partner;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Functions;
14
use Automattic\Jetpack\Sync\Health;
15
use Automattic\Jetpack\Sync\Sender;
16
use Automattic\Jetpack\Sync\Users;
17
use Automattic\Jetpack\Terms_Of_Service;
18
use Automattic\Jetpack\Tracking;
19
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
20
use Automattic\Jetpack\Redirect;
21
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
22
23
/*
24
Options:
25
jetpack_options (array)
26
	An array of options.
27
	@see Jetpack_Options::get_option_names()
28
29
jetpack_register (string)
30
	Temporary verification secrets.
31
32
jetpack_activated (int)
33
	1: the plugin was activated normally
34
	2: the plugin was activated on this site because of a network-wide activation
35
	3: the plugin was auto-installed
36
	4: the plugin was manually disconnected (but is still installed)
37
38
jetpack_active_modules (array)
39
	Array of active module slugs.
40
41
jetpack_do_activate (bool)
42
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
43
*/
44
45
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
46
47
class Jetpack {
48
	public $xmlrpc_server = null;
49
50
	private $rest_authentication_status = null;
51
52
	/**
53
	 * @var array The handles of styles that are concatenated into jetpack.css.
54
	 *
55
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
56
	 */
57
	public $concatenated_style_handles = array(
58
		'jetpack-carousel',
59
		'grunion.css',
60
		'the-neverending-homepage',
61
		'jetpack_likes',
62
		'jetpack_related-posts',
63
		'sharedaddy',
64
		'jetpack-slideshow',
65
		'presentations',
66
		'quiz',
67
		'jetpack-subscriptions',
68
		'jetpack-responsive-videos-style',
69
		'jetpack-social-menu',
70
		'tiled-gallery',
71
		'jetpack_display_posts_widget',
72
		'gravatar-profile-widget',
73
		'goodreads-widget',
74
		'jetpack_social_media_icons_widget',
75
		'jetpack-top-posts-widget',
76
		'jetpack_image_widget',
77
		'jetpack-my-community-widget',
78
		'jetpack-authors-widget',
79
		'wordads',
80
		'eu-cookie-law-style',
81
		'flickr-widget-style',
82
		'jetpack-search-widget',
83
		'jetpack-simple-payments-widget-style',
84
		'jetpack-widget-social-icons-styles',
85
		'wpcom_instagram_widget',
86
	);
87
88
	/**
89
	 * Contains all assets that have had their URL rewritten to minified versions.
90
	 *
91
	 * @var array
92
	 */
93
	static $min_assets = array();
94
95
	public $plugins_to_deactivate = array(
96
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
97
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
98
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
99
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
100
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
101
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
102
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
103
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
104
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
105
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
106
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
107
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
108
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
109
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
110
	);
111
112
	/**
113
	 * Map of roles we care about, and their corresponding minimum capabilities.
114
	 *
115
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
116
	 *
117
	 * @access public
118
	 * @static
119
	 *
120
	 * @var array
121
	 */
122
	public static $capability_translations = array(
123
		'administrator' => 'manage_options',
124
		'editor'        => 'edit_others_posts',
125
		'author'        => 'publish_posts',
126
		'contributor'   => 'edit_posts',
127
		'subscriber'    => 'read',
128
	);
129
130
	/**
131
	 * Map of modules that have conflicts with plugins and should not be auto-activated
132
	 * if the plugins are active.  Used by filter_default_modules
133
	 *
134
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
135
	 * change `module-slug` and add this to your plugin:
136
	 *
137
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
138
	 * function my_jetpack_get_default_modules( $modules ) {
139
	 *     return array_diff( $modules, array( 'module-slug' ) );
140
	 * }
141
	 *
142
	 * @var array
143
	 */
144
	private $conflicting_plugins = array(
145
		'comments'           => array(
146
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
147
			'Disqus'                         => 'disqus-comment-system/disqus.php',
148
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
149
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
150
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
151
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
152
		),
153
		'comment-likes'      => array(
154
			'Epoch' => 'epoch/plugincore.php',
155
		),
156
		'contact-form'       => array(
157
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
158
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
159
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
160
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
161
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
162
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
163
		),
164
		'latex'              => array(
165
			'LaTeX for WordPress'     => 'latex/latex.php',
166
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
167
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
168
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
169
			'Enable Latex'            => 'enable-latex/enable-latex.php',
170
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
171
		),
172
		'protect'            => array(
173
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
174
			'Captcha'                           => 'captcha/captcha.php',
175
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
176
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
177
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
178
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
179
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
180
			'Security-protection'               => 'security-protection/security-protection.php',
181
			'Login Security'                    => 'login-security/login-security.php',
182
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
183
			'Wordfence Security'                => 'wordfence/wordfence.php',
184
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
185
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
186
		),
187
		'random-redirect'    => array(
188
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
189
		),
190
		'related-posts'      => array(
191
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
192
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
193
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
194
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
195
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
196
			'outbrain'                    => 'outbrain/outbrain.php',
197
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
198
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
199
		),
200
		'sharedaddy'         => array(
201
			'AddThis'     => 'addthis/addthis_social_widget.php',
202
			'Add To Any'  => 'add-to-any/add-to-any.php',
203
			'ShareThis'   => 'share-this/sharethis.php',
204
			'Shareaholic' => 'shareaholic/shareaholic.php',
205
		),
206
		'seo-tools'          => array(
207
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
208
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
209
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211
			'The SEO Framework'              => 'autodescription/autodescription.php',
212
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
213
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
214
		),
215
		'verification-tools' => array(
216
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
217
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
218
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
219
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
220
			'The SEO Framework'              => 'autodescription/autodescription.php',
221
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
222
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
223
		),
224
		'widget-visibility'  => array(
225
			'Widget Logic'    => 'widget-logic/widget_logic.php',
226
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
227
		),
228
		'sitemaps'           => array(
229
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
230
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
231
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
232
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
233
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
234
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
235
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
236
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
237
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
238
			'The SEO Framework'                    => 'autodescription/autodescription.php',
239
			'Sitemap'                              => 'sitemap/sitemap.php',
240
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
241
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
242
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
243
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
244
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
245
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
246
		),
247
		'lazy-images'        => array(
248
			'Lazy Load'              => 'lazy-load/lazy-load.php',
249
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
250
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
251
		),
252
	);
253
254
	/**
255
	 * Plugins for which we turn off our Facebook OG Tags implementation.
256
	 *
257
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
258
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
259
	 *
260
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
261
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
262
	 */
263
	private $open_graph_conflicting_plugins = array(
264
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
265
		// 2 Click Social Media Buttons
266
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
267
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
268
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
269
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
270
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
271
		// Open Graph Meta Tags by Heateor
272
		'facebook/facebook.php',                                 // Facebook (official plugin)
273
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
274
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
275
		// Facebook Featured Image & OG Meta Tags
276
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
277
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
278
		// Facebook Open Graph Meta Tags for WordPress
279
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
280
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
281
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
282
		// Fedmich's Facebook Open Graph Meta
283
		'network-publisher/networkpub.php',                      // Network Publisher
284
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
285
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
286
		// NextScripts SNAP
287
		'og-tags/og-tags.php',                                   // OG Tags
288
		'opengraph/opengraph.php',                               // Open Graph
289
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
290
		// Open Graph Protocol Framework
291
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
292
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
293
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
294
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
295
		'sharepress/sharepress.php',                             // SharePress
296
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
297
		'social-discussions/social-discussions.php',             // Social Discussions
298
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
299
		'socialize/socialize.php',                               // Socialize
300
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
301
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
302
		// Tweet, Like, Google +1 and Share
303
		'wordbooker/wordbooker.php',                             // Wordbooker
304
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
305
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
306
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
307
		// WP Facebook Like Send & Open Graph Meta
308
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
309
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
310
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
311
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
312
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
313
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
314
		'slim-seo/slim-seo.php',                                 // Slim SEO
315
	);
316
317
	/**
318
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
319
	 */
320
	private $twitter_cards_conflicting_plugins = array(
321
		// 'twitter/twitter.php',                       // The official one handles this on its own.
322
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
323
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
324
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
325
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
326
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
327
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
328
		'twitter-cards/twitter-cards.php',           // Twitter Cards
329
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
330
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
331
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
332
		'seo-by-rank-math/rank-math.php',            // Rank Math.
333
		'slim-seo/slim-seo.php',                     // Slim SEO
334
	);
335
336
	/**
337
	 * Message to display in admin_notice
338
	 *
339
	 * @var string
340
	 */
341
	public $message = '';
342
343
	/**
344
	 * Error to display in admin_notice
345
	 *
346
	 * @var string
347
	 */
348
	public $error = '';
349
350
	/**
351
	 * Modules that need more privacy description.
352
	 *
353
	 * @var string
354
	 */
355
	public $privacy_checks = '';
356
357
	/**
358
	 * Stats to record once the page loads
359
	 *
360
	 * @var array
361
	 */
362
	public $stats = array();
363
364
	/**
365
	 * Jetpack_Sync object
366
	 */
367
	public $sync;
368
369
	/**
370
	 * Verified data for JSON authorization request
371
	 */
372
	public $json_api_authorization_request = array();
373
374
	/**
375
	 * @var Automattic\Jetpack\Connection\Manager
376
	 */
377
	protected $connection_manager;
378
379
	/**
380
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
381
	 */
382
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
383
384
	/**
385
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
386
	 *
387
	 * @var Automattic\Jetpack\A8c_Mc_Stats
388
	 */
389
	public $a8c_mc_stats_instance;
390
391
	/**
392
	 * Constant for login redirect key.
393
	 *
394
	 * @var string
395
	 * @since 8.4.0
396
	 */
397
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
398
399
	/**
400
	 * Holds the singleton instance of this class
401
	 *
402
	 * @since 2.3.3
403
	 * @var Jetpack
404
	 */
405
	static $instance = false;
406
407
	/**
408
	 * Singleton
409
	 *
410
	 * @static
411
	 */
412
	public static function init() {
413
		if ( ! self::$instance ) {
414
			self::$instance = new Jetpack();
415
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
416
		}
417
418
		return self::$instance;
419
	}
420
421
	/**
422
	 * Must never be called statically
423
	 */
424
	function plugin_upgrade() {
425
		if ( self::is_active() ) {
426
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
427
			if ( JETPACK__VERSION != $version ) {
428
				// Prevent multiple upgrades at once - only a single process should trigger
429
				// an upgrade to avoid stampedes
430
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
431
					return;
432
				}
433
434
				// Set a short lock to prevent multiple instances of the upgrade
435
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
436
437
				// check which active modules actually exist and remove others from active_modules list
438
				$unfiltered_modules = self::get_active_modules();
439
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
440
				if ( array_diff( $unfiltered_modules, $modules ) ) {
441
					self::update_active_modules( $modules );
442
				}
443
444
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
445
446
				// Upgrade to 4.3.0
447
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
448
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
449
				}
450
451
				// Make sure Markdown for posts gets turned back on
452
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
453
					update_option( 'wpcom_publish_posts_with_markdown', true );
454
				}
455
456
				/*
457
				 * Minileven deprecation. 8.3.0.
458
				 * Only delete options if not using
459
				 * the replacement standalone Minileven plugin.
460
				 */
461
				if (
462
					! self::is_plugin_active( 'minileven-master/minileven.php' )
463
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
464
				) {
465
					if ( get_option( 'wp_mobile_custom_css' ) ) {
466
						delete_option( 'wp_mobile_custom_css' );
467
					}
468
					if ( get_option( 'wp_mobile_excerpt' ) ) {
469
						delete_option( 'wp_mobile_excerpt' );
470
					}
471
					if ( get_option( 'wp_mobile_featured_images' ) ) {
472
						delete_option( 'wp_mobile_featured_images' );
473
					}
474
					if ( get_option( 'wp_mobile_app_promos' ) ) {
475
						delete_option( 'wp_mobile_app_promos' );
476
					}
477
				}
478
479
				// Upgrade to 8.4.0.
480
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
481
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
482
				}
483
484
				// Update to 8.8.x (WordPress 5.5 Compatibility).
485
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
486
					$updated = update_site_option(
487
						'auto_update_plugins',
488
						array_unique(
489
							array_merge(
490
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
491
								(array) get_site_option( 'auto_update_plugins', array() )
492
							)
493
						)
494
					);
495
496
					if ( $updated ) {
497
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
498
					} // Should we have some type of fallback if something fails here?
499
				}
500
501
				if ( did_action( 'wp_loaded' ) ) {
502
					self::upgrade_on_load();
503
				} else {
504
					add_action(
505
						'wp_loaded',
506
						array( __CLASS__, 'upgrade_on_load' )
507
					);
508
				}
509
			}
510
		}
511
	}
512
513
	/**
514
	 * Runs upgrade routines that need to have modules loaded.
515
	 */
516
	static function upgrade_on_load() {
517
518
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
519
		// This can happen in case Jetpack has been just upgraded and is
520
		// being initialized late during the page load. In this case we wait
521
		// until the next proper admin page load with Jetpack active.
522
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
523
			delete_transient( self::$plugin_upgrade_lock_key );
524
525
			return;
526
		}
527
528
		self::maybe_set_version_option();
529
530
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
531
			Jetpack_Widget_Conditions::migrate_post_type_rules();
532
		}
533
534
		if (
535
			class_exists( 'Jetpack_Sitemap_Manager' )
536
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
537
		) {
538
			do_action( 'jetpack_sitemaps_purge_data' );
539
		}
540
541
		// Delete old stats cache
542
		delete_option( 'jetpack_restapi_stats_cache' );
543
544
		delete_transient( self::$plugin_upgrade_lock_key );
545
	}
546
547
	/**
548
	 * Saves all the currently active modules to options.
549
	 * Also fires Action hooks for each newly activated and deactivated module.
550
	 *
551
	 * @param $modules Array Array of active modules to be saved in options.
552
	 *
553
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

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

Loading history...
554
	 */
555
	static function update_active_modules( $modules ) {
556
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
557
		$active_modules       = self::get_active_modules();
558
		$new_active_modules   = array_diff( $modules, $current_modules );
559
		$new_inactive_modules = array_diff( $active_modules, $modules );
560
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
561
		$reindexed_modules    = array_values( $new_current_modules );
562
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
563
564
		foreach ( $new_active_modules as $module ) {
565
			/**
566
			 * Fires when a specific module is activated.
567
			 *
568
			 * @since 1.9.0
569
			 *
570
			 * @param string $module Module slug.
571
			 * @param boolean $success whether the module was activated. @since 4.2
572
			 */
573
			do_action( 'jetpack_activate_module', $module, $success );
574
			/**
575
			 * Fires when a module is activated.
576
			 * The dynamic part of the filter, $module, is the module slug.
577
			 *
578
			 * @since 1.9.0
579
			 *
580
			 * @param string $module Module slug.
581
			 */
582
			do_action( "jetpack_activate_module_$module", $module );
583
		}
584
585
		foreach ( $new_inactive_modules as $module ) {
586
			/**
587
			 * Fired after a module has been deactivated.
588
			 *
589
			 * @since 4.2.0
590
			 *
591
			 * @param string $module Module slug.
592
			 * @param boolean $success whether the module was deactivated.
593
			 */
594
			do_action( 'jetpack_deactivate_module', $module, $success );
595
			/**
596
			 * Fires when a module is deactivated.
597
			 * The dynamic part of the filter, $module, is the module slug.
598
			 *
599
			 * @since 1.9.0
600
			 *
601
			 * @param string $module Module slug.
602
			 */
603
			do_action( "jetpack_deactivate_module_$module", $module );
604
		}
605
606
		return $success;
607
	}
608
609
	static function delete_active_modules() {
610
		self::update_active_modules( array() );
611
	}
612
613
	/**
614
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
615
	 * available.
616
	 */
617
	public function add_configure_hook() {
618
		global $wp_filter;
619
620
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
621
		if ( false !== $current_priority ) {
622
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
623
		}
624
625
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
626
		sort( $taken_priorities );
627
628
		$first_priority = array_shift( $taken_priorities );
629
630
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
631
			$new_priority = - PHP_INT_MAX;
632
		} else {
633
			$new_priority = $first_priority - 1;
634
		}
635
636
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
637
	}
638
639
	/**
640
	 * Constructor.  Initializes WordPress hooks
641
	 */
642
	private function __construct() {
643
		/*
644
		 * Check for and alert any deprecated hooks
645
		 */
646
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
647
648
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
649
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
650
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
651
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
652
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
653
654
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
655
656
		add_filter(
657
			'jetpack_signature_check_token',
658
			array( __CLASS__, 'verify_onboarding_token' ),
659
			10,
660
			3
661
		);
662
663
		/**
664
		 * Prepare Gutenberg Editor functionality
665
		 */
666
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
667
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
668
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
669
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
670
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
671
672
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
673
674
		// Unlink user before deleting the user from WP.com.
675
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
676
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
677
678
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
679
680
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
681
		add_action( 'login_init', array( $this, 'login_init' ) );
682
683
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
684
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
685
686
		add_action( 'admin_init', array( $this, 'admin_init' ) );
687
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
688
689
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
690
691
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
692
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
693
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
694
695
		// returns HTTPS support status
696
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
697
698
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
699
700
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
701
702
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
703
704
		/**
705
		 * These actions run checks to load additional files.
706
		 * They check for external files or plugins, so they need to run as late as possible.
707
		 */
708
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
709
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
710
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
711
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
712
713
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
714
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
715
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
716
717
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
718
719
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
720
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
721
722
		// A filter to control all just in time messages
723
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
724
725
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
726
727
		/*
728
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
729
		 * We should make sure to only do this for front end links.
730
		 */
731
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
732
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
733
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
734
735
			/*
736
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
737
			 * so they point moderation links on emails to Calypso.
738
			 */
739
			jetpack_require_lib( 'functions.wp-notify' );
740
		}
741
742
		add_action(
743
			'plugins_loaded',
744
			function() {
745
				if ( User_Agent_Info::is_mobile_app() ) {
746
					add_filter( 'get_edit_post_link', '__return_empty_string' );
747
				}
748
			}
749
		);
750
751
		// Update the site's Jetpack plan and products from API on heartbeats.
752
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
753
754
		/**
755
		 * This is the hack to concatenate all css files into one.
756
		 * For description and reasoning see the implode_frontend_css method.
757
		 *
758
		 * Super late priority so we catch all the registered styles.
759
		 */
760
		if ( ! is_admin() ) {
761
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
762
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
763
		}
764
765
		/**
766
		 * These are sync actions that we need to keep track of for jitms
767
		 */
768
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
769
770
		// Actually push the stats on shutdown.
771
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
772
			add_action( 'shutdown', array( $this, 'push_stats' ) );
773
		}
774
775
		// Actions for Manager::authorize().
776
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
777
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
778
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
779
780
		// Filters for the Manager::get_token() urls and request body.
781
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
782
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
783
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
784
	}
785
786
	/**
787
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
788
	 * Config object.
789
	 */
790
	public function configure() {
791
		$config = new Config();
792
793
		foreach (
794
			array(
795
				'sync',
796
				'tracking',
797
				'tos',
798
			)
799
			as $feature
800
		) {
801
			$config->ensure( $feature );
802
		}
803
804
		$config->ensure(
805
			'connection',
806
			array(
807
				'slug' => 'jetpack',
808
				'name' => 'Jetpack',
809
			)
810
		);
811
812
		if ( is_admin() ) {
813
			$config->ensure( 'jitm' );
814
		}
815
816
		if ( ! $this->connection_manager ) {
817
			$this->connection_manager = new Connection_Manager( 'jetpack' );
818
		}
819
820
		/*
821
		 * Load things that should only be in Network Admin.
822
		 *
823
		 * For now blow away everything else until a more full
824
		 * understanding of what is needed at the network level is
825
		 * available
826
		 */
827
		if ( is_multisite() ) {
828
			$network = Jetpack_Network::init();
829
			$network->set_connection( $this->connection_manager );
830
		}
831
832
		if ( $this->connection_manager->is_active() ) {
833
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
834
835
			Jetpack_Heartbeat::init();
836
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
837
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
838
				Jetpack_Search_Performance_Logger::init();
839
			}
840
		}
841
842
		// Initialize remote file upload request handlers.
843
		$this->add_remote_request_handlers();
844
845
		/*
846
		 * Enable enhanced handling of previewing sites in Calypso
847
		 */
848
		if ( self::is_active() ) {
849
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
850
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
851
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
852
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
853
		}
854
	}
855
856
	/**
857
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
858
	 * initialization code.
859
	 *
860
	 * @action plugins_loaded
861
	 */
862
	public function late_initialization() {
863
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
864
865
		Partner::init();
866
867
		/**
868
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
869
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
870
		 *
871
		 * @since 8.1.0
872
		 *
873
		 * @param Jetpack $jetpack the main plugin class object.
874
		 */
875
		do_action( 'jetpack_loaded', $this );
876
877
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
878
	}
879
880
	/**
881
	 * Sets up the XMLRPC request handlers.
882
	 *
883
	 * @deprecated since 7.7.0
884
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
885
	 *
886
	 * @param array                 $request_params Incoming request parameters.
887
	 * @param Boolean               $is_active      Whether the connection is currently active.
888
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
889
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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

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

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

Loading history...
890
	 */
891 View Code Duplication
	public function setup_xmlrpc_handlers(
892
		$request_params,
893
		$is_active,
894
		$is_signed,
895
		Jetpack_XMLRPC_Server $xmlrpc_server = null
896
	) {
897
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
898
899
		if ( ! $this->connection_manager ) {
900
			$this->connection_manager = new Connection_Manager();
901
		}
902
903
		return $this->connection_manager->setup_xmlrpc_handlers(
904
			$request_params,
905
			$is_active,
906
			$is_signed,
907
			$xmlrpc_server
908
		);
909
	}
910
911
	/**
912
	 * Initialize REST API registration connector.
913
	 *
914
	 * @deprecated since 7.7.0
915
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
916
	 */
917 View Code Duplication
	public function initialize_rest_api_registration_connector() {
918
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
919
920
		if ( ! $this->connection_manager ) {
921
			$this->connection_manager = new Connection_Manager();
922
		}
923
924
		$this->connection_manager->initialize_rest_api_registration_connector();
925
	}
926
927
	/**
928
	 * This is ported over from the manage module, which has been deprecated and baked in here.
929
	 *
930
	 * @param $domains
931
	 */
932
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
933
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
934
	}
935
936
	/**
937
	 * Return $domains, with 'wordpress.com' appended.
938
	 * This is ported over from the manage module, which has been deprecated and baked in here.
939
	 *
940
	 * @param $domains
941
	 * @return array
942
	 */
943
	function allow_wpcom_domain( $domains ) {
944
		if ( empty( $domains ) ) {
945
			$domains = array();
946
		}
947
		$domains[] = 'wordpress.com';
948
		return array_unique( $domains );
949
	}
950
951
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
952
		$post = get_post( $post_id );
953
954
		if ( empty( $post ) ) {
955
			return $default_url;
956
		}
957
958
		$post_type = $post->post_type;
959
960
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
961
		// https://en.support.wordpress.com/custom-post-types/
962
		$allowed_post_types = array(
963
			'post',
964
			'page',
965
			'jetpack-portfolio',
966
			'jetpack-testimonial',
967
		);
968
969
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
970
			return $default_url;
971
		}
972
973
		return Redirect::get_url(
974
			'calypso-edit-' . $post_type,
975
			array(
976
				'path' => $post_id,
977
			)
978
		);
979
	}
980
981
	function point_edit_comment_links_to_calypso( $url ) {
982
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
983
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
The variable $query_args does not exist. Did you forget to declare it?

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

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

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2313
2314
		if ( $redirect ) {
2315
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2316
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2317
				$page = $_GET['page'];
2318
			}
2319
2320
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2321
			exit;
2322
		}
2323
	}
2324
2325
	/**
2326
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2327
	 * Make sure to tuck away module "library" files in a sub-directory.
2328
	 */
2329
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2330
		static $modules = null;
2331
2332
		if ( ! isset( $modules ) ) {
2333
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2334
			// Use the cache if we're on the front-end and it's available...
2335
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2336
				$modules = $available_modules_option[ JETPACK__VERSION ];
2337
			} else {
2338
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2339
2340
				$modules = array();
2341
2342
				foreach ( $files as $file ) {
2343
					if ( ! $headers = self::get_module( $file ) ) {
2344
						continue;
2345
					}
2346
2347
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2348
				}
2349
2350
				Jetpack_Options::update_option(
2351
					'available_modules',
2352
					array(
2353
						JETPACK__VERSION => $modules,
2354
					)
2355
				);
2356
			}
2357
		}
2358
2359
		/**
2360
		 * Filters the array of modules available to be activated.
2361
		 *
2362
		 * @since 2.4.0
2363
		 *
2364
		 * @param array $modules Array of available modules.
2365
		 * @param string $min_version Minimum version number required to use modules.
2366
		 * @param string $max_version Maximum version number required to use modules.
2367
		 */
2368
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
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...
2369
2370
		if ( ! $min_version && ! $max_version ) {
2371
			return array_keys( $mods );
2372
		}
2373
2374
		$r = array();
2375
		foreach ( $mods as $slug => $introduced ) {
2376
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2377
				continue;
2378
			}
2379
2380
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2381
				continue;
2382
			}
2383
2384
			$r[] = $slug;
2385
		}
2386
2387
		return $r;
2388
	}
2389
2390
	/**
2391
	 * Default modules loaded on activation.
2392
	 */
2393
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2394
		$return = array();
2395
2396
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2397
			$module_data = self::get_module( $module );
2398
2399
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2400
				case 'yes':
2401
					$return[] = $module;
2402
					break;
2403
				case 'public':
2404
					if ( Jetpack_Options::get_option( 'public' ) ) {
2405
						$return[] = $module;
2406
					}
2407
					break;
2408
				case 'no':
2409
				default:
2410
					break;
2411
			}
2412
		}
2413
		/**
2414
		 * Filters the array of default modules.
2415
		 *
2416
		 * @since 2.5.0
2417
		 *
2418
		 * @param array $return Array of default modules.
2419
		 * @param string $min_version Minimum version number required to use modules.
2420
		 * @param string $max_version Maximum version number required to use modules.
2421
		 */
2422
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
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...
2423
	}
2424
2425
	/**
2426
	 * Checks activated modules during auto-activation to determine
2427
	 * if any of those modules are being deprecated.  If so, close
2428
	 * them out, and add any replacement modules.
2429
	 *
2430
	 * Runs at priority 99 by default.
2431
	 *
2432
	 * This is run late, so that it can still activate a module if
2433
	 * the new module is a replacement for another that the user
2434
	 * currently has active, even if something at the normal priority
2435
	 * would kibosh everything.
2436
	 *
2437
	 * @since 2.6
2438
	 * @uses jetpack_get_default_modules filter
2439
	 * @param array $modules
2440
	 * @return array
2441
	 */
2442
	function handle_deprecated_modules( $modules ) {
2443
		$deprecated_modules = array(
2444
			'debug'            => null,  // Closed out and moved to the debugger library.
2445
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2446
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2447
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2448
		);
2449
2450
		// Don't activate SSO if they never completed activating WPCC.
2451
		if ( self::is_module_active( 'wpcc' ) ) {
2452
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2453
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2454
				$deprecated_modules['wpcc'] = null;
2455
			}
2456
		}
2457
2458
		foreach ( $deprecated_modules as $module => $replacement ) {
2459
			if ( self::is_module_active( $module ) ) {
2460
				self::deactivate_module( $module );
2461
				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...
2462
					$modules[] = $replacement;
2463
				}
2464
			}
2465
		}
2466
2467
		return array_unique( $modules );
2468
	}
2469
2470
	/**
2471
	 * Checks activated plugins during auto-activation to determine
2472
	 * if any of those plugins are in the list with a corresponding module
2473
	 * that is not compatible with the plugin. The module will not be allowed
2474
	 * to auto-activate.
2475
	 *
2476
	 * @since 2.6
2477
	 * @uses jetpack_get_default_modules filter
2478
	 * @param array $modules
2479
	 * @return array
2480
	 */
2481
	function filter_default_modules( $modules ) {
2482
2483
		$active_plugins = self::get_active_plugins();
2484
2485
		if ( ! empty( $active_plugins ) ) {
2486
2487
			// For each module we'd like to auto-activate...
2488
			foreach ( $modules as $key => $module ) {
2489
				// If there are potential conflicts for it...
2490
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2491
					// For each potential conflict...
2492
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2493
						// If that conflicting plugin is active...
2494
						if ( in_array( $plugin, $active_plugins ) ) {
2495
							// Remove that item from being auto-activated.
2496
							unset( $modules[ $key ] );
2497
						}
2498
					}
2499
				}
2500
			}
2501
		}
2502
2503
		return $modules;
2504
	}
2505
2506
	/**
2507
	 * Extract a module's slug from its full path.
2508
	 */
2509
	public static function get_module_slug( $file ) {
2510
		return str_replace( '.php', '', basename( $file ) );
2511
	}
2512
2513
	/**
2514
	 * Generate a module's path from its slug.
2515
	 */
2516
	public static function get_module_path( $slug ) {
2517
		/**
2518
		 * Filters the path of a modules.
2519
		 *
2520
		 * @since 7.4.0
2521
		 *
2522
		 * @param array $return The absolute path to a module's root php file
2523
		 * @param string $slug The module slug
2524
		 */
2525
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
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...
2526
	}
2527
2528
	/**
2529
	 * Load module data from module file. Headers differ from WordPress
2530
	 * plugin headers to avoid them being identified as standalone
2531
	 * plugins on the WordPress plugins page.
2532
	 */
2533
	public static function get_module( $module ) {
2534
		$headers = array(
2535
			'name'                      => 'Module Name',
2536
			'description'               => 'Module Description',
2537
			'sort'                      => 'Sort Order',
2538
			'recommendation_order'      => 'Recommendation Order',
2539
			'introduced'                => 'First Introduced',
2540
			'changed'                   => 'Major Changes In',
2541
			'deactivate'                => 'Deactivate',
2542
			'free'                      => 'Free',
2543
			'requires_connection'       => 'Requires Connection',
2544
			'auto_activate'             => 'Auto Activate',
2545
			'module_tags'               => 'Module Tags',
2546
			'feature'                   => 'Feature',
2547
			'additional_search_queries' => 'Additional Search Queries',
2548
			'plan_classes'              => 'Plans',
2549
		);
2550
2551
		$file = self::get_module_path( self::get_module_slug( $module ) );
2552
2553
		$mod = self::get_file_data( $file, $headers );
2554
		if ( empty( $mod['name'] ) ) {
2555
			return false;
2556
		}
2557
2558
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2559
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2560
		$mod['deactivate']           = empty( $mod['deactivate'] );
2561
		$mod['free']                 = empty( $mod['free'] );
2562
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2563
2564
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2565
			$mod['auto_activate'] = 'No';
2566
		} else {
2567
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2568
		}
2569
2570
		if ( $mod['module_tags'] ) {
2571
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2572
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2573
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2574
		} else {
2575
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2576
		}
2577
2578 View Code Duplication
		if ( $mod['plan_classes'] ) {
2579
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2580
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2581
		} else {
2582
			$mod['plan_classes'] = array( 'free' );
2583
		}
2584
2585 View Code Duplication
		if ( $mod['feature'] ) {
2586
			$mod['feature'] = explode( ',', $mod['feature'] );
2587
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2588
		} else {
2589
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2590
		}
2591
2592
		/**
2593
		 * Filters the feature array on a module.
2594
		 *
2595
		 * This filter allows you to control where each module is filtered: Recommended,
2596
		 * and the default "Other" listing.
2597
		 *
2598
		 * @since 3.5.0
2599
		 *
2600
		 * @param array   $mod['feature'] The areas to feature this module:
2601
		 *     'Recommended' shows on the main Jetpack admin screen.
2602
		 *     'Other' should be the default if no other value is in the array.
2603
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2604
		 * @param array   $mod All the currently assembled module data.
2605
		 */
2606
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
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...
2607
2608
		/**
2609
		 * Filter the returned data about a module.
2610
		 *
2611
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2612
		 * so please be careful.
2613
		 *
2614
		 * @since 3.6.0
2615
		 *
2616
		 * @param array   $mod    The details of the requested module.
2617
		 * @param string  $module The slug of the module, e.g. sharedaddy
2618
		 * @param string  $file   The path to the module source file.
2619
		 */
2620
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
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...
2621
	}
2622
2623
	/**
2624
	 * Like core's get_file_data implementation, but caches the result.
2625
	 */
2626
	public static function get_file_data( $file, $headers ) {
2627
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2628
		$file_name = basename( $file );
2629
2630
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2631
2632
		$file_data_option = get_transient( $cache_key );
2633
2634
		if ( ! is_array( $file_data_option ) ) {
2635
			delete_transient( $cache_key );
2636
			$file_data_option = false;
2637
		}
2638
2639
		if ( false === $file_data_option ) {
2640
			$file_data_option = array();
2641
		}
2642
2643
		$key           = md5( $file_name . serialize( $headers ) );
2644
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2645
2646
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2647
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2648
			return $file_data_option[ $key ];
2649
		}
2650
2651
		$data = get_file_data( $file, $headers );
2652
2653
		$file_data_option[ $key ] = $data;
2654
2655
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2656
2657
		return $data;
2658
	}
2659
2660
2661
	/**
2662
	 * Return translated module tag.
2663
	 *
2664
	 * @param string $tag Tag as it appears in each module heading.
2665
	 *
2666
	 * @return mixed
2667
	 */
2668
	public static function translate_module_tag( $tag ) {
2669
		return jetpack_get_module_i18n_tag( $tag );
2670
	}
2671
2672
	/**
2673
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2674
	 *
2675
	 * @since 3.9.2
2676
	 *
2677
	 * @param array $modules
2678
	 *
2679
	 * @return string|void
2680
	 */
2681
	public static function get_translated_modules( $modules ) {
2682
		foreach ( $modules as $index => $module ) {
2683
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2684
			if ( isset( $module['name'] ) ) {
2685
				$modules[ $index ]['name'] = $i18n_module['name'];
2686
			}
2687
			if ( isset( $module['description'] ) ) {
2688
				$modules[ $index ]['description']       = $i18n_module['description'];
2689
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2690
			}
2691
		}
2692
		return $modules;
2693
	}
2694
2695
	/**
2696
	 * Get a list of activated modules as an array of module slugs.
2697
	 */
2698
	public static function get_active_modules() {
2699
		$active = Jetpack_Options::get_option( 'active_modules' );
2700
2701
		if ( ! is_array( $active ) ) {
2702
			$active = array();
2703
		}
2704
2705
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2706
			$active[] = 'vaultpress';
2707
		} else {
2708
			$active = array_diff( $active, array( 'vaultpress' ) );
2709
		}
2710
2711
		// If protect is active on the main site of a multisite, it should be active on all sites.
2712
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2713
			$active[] = 'protect';
2714
		}
2715
2716
		/**
2717
		 * Allow filtering of the active modules.
2718
		 *
2719
		 * Gives theme and plugin developers the power to alter the modules that
2720
		 * are activated on the fly.
2721
		 *
2722
		 * @since 5.8.0
2723
		 *
2724
		 * @param array $active Array of active module slugs.
2725
		 */
2726
		$active = apply_filters( 'jetpack_active_modules', $active );
2727
2728
		return array_unique( $active );
2729
	}
2730
2731
	/**
2732
	 * Check whether or not a Jetpack module is active.
2733
	 *
2734
	 * @param string $module The slug of a Jetpack module.
2735
	 * @return bool
2736
	 *
2737
	 * @static
2738
	 */
2739
	public static function is_module_active( $module ) {
2740
		return in_array( $module, self::get_active_modules() );
2741
	}
2742
2743
	public static function is_module( $module ) {
2744
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2745
	}
2746
2747
	/**
2748
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2749
	 *
2750
	 * @param bool $catch True to start catching, False to stop.
2751
	 *
2752
	 * @static
2753
	 */
2754
	public static function catch_errors( $catch ) {
2755
		static $display_errors, $error_reporting;
2756
2757
		if ( $catch ) {
2758
			$display_errors  = @ini_set( 'display_errors', 1 );
2759
			$error_reporting = @error_reporting( E_ALL );
2760
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2761
		} else {
2762
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2763
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2764
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2765
		}
2766
	}
2767
2768
	/**
2769
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2770
	 */
2771
	public static function catch_errors_on_shutdown() {
2772
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2773
	}
2774
2775
	/**
2776
	 * Rewrite any string to make paths easier to read.
2777
	 *
2778
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2779
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2780
	 *
2781
	 * @param $string
2782
	 * @return mixed
2783
	 */
2784
	public static function alias_directories( $string ) {
2785
		// ABSPATH has a trailing slash.
2786
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2787
		// WP_CONTENT_DIR does not have a trailing slash.
2788
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2789
2790
		return $string;
2791
	}
2792
2793
	public static function activate_default_modules(
2794
		$min_version = false,
2795
		$max_version = false,
2796
		$other_modules = array(),
2797
		$redirect = null,
2798
		$send_state_messages = null
2799
	) {
2800
		$jetpack = self::init();
2801
2802
		if ( is_null( $redirect ) ) {
2803
			if (
2804
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2805
			||
2806
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2807
			||
2808
				( defined( 'WP_CLI' ) && WP_CLI )
2809
			||
2810
				( defined( 'DOING_CRON' ) && DOING_CRON )
2811
			||
2812
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2813
			) {
2814
				$redirect = false;
2815
			} elseif ( is_admin() ) {
2816
				$redirect = true;
2817
			} else {
2818
				$redirect = false;
2819
			}
2820
		}
2821
2822
		if ( is_null( $send_state_messages ) ) {
2823
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2824
		}
2825
2826
		$modules = self::get_default_modules( $min_version, $max_version );
2827
		$modules = array_merge( $other_modules, $modules );
2828
2829
		// Look for standalone plugins and disable if active.
2830
2831
		$to_deactivate = array();
2832
		foreach ( $modules as $module ) {
2833
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2834
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2835
			}
2836
		}
2837
2838
		$deactivated = array();
2839
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2840
			list( $probable_file, $probable_title ) = $deactivate_me;
2841
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2842
				$deactivated[] = $module;
2843
			}
2844
		}
2845
2846
		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...
2847
			if ( $send_state_messages ) {
2848
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2849
			}
2850
2851
			if ( $redirect ) {
2852
				$url = add_query_arg(
2853
					array(
2854
						'action'   => 'activate_default_modules',
2855
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2856
					),
2857
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2858
				);
2859
				wp_safe_redirect( $url );
2860
				exit;
2861
			}
2862
		}
2863
2864
		/**
2865
		 * Fires before default modules are activated.
2866
		 *
2867
		 * @since 1.9.0
2868
		 *
2869
		 * @param string $min_version Minimum version number required to use modules.
2870
		 * @param string $max_version Maximum version number required to use modules.
2871
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2872
		 */
2873
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2874
2875
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2876
		if ( $send_state_messages ) {
2877
			self::restate();
2878
			self::catch_errors( true );
2879
		}
2880
2881
		$active = self::get_active_modules();
2882
2883
		foreach ( $modules as $module ) {
2884
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2885
				$active[] = $module;
2886
				self::update_active_modules( $active );
2887
				continue;
2888
			}
2889
2890
			if ( $send_state_messages && in_array( $module, $active ) ) {
2891
				$module_info = self::get_module( $module );
2892 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2893
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2894
					if ( $active_state = self::state( $state ) ) {
2895
						$active_state = explode( ',', $active_state );
2896
					} else {
2897
						$active_state = array();
2898
					}
2899
					$active_state[] = $module;
2900
					self::state( $state, implode( ',', $active_state ) );
2901
				}
2902
				continue;
2903
			}
2904
2905
			$file = self::get_module_path( $module );
2906
			if ( ! file_exists( $file ) ) {
2907
				continue;
2908
			}
2909
2910
			// we'll override this later if the plugin can be included without fatal error
2911
			if ( $redirect ) {
2912
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2913
			}
2914
2915
			if ( $send_state_messages ) {
2916
				self::state( 'error', 'module_activation_failed' );
2917
				self::state( 'module', $module );
2918
			}
2919
2920
			ob_start();
2921
			require_once $file;
2922
2923
			$active[] = $module;
2924
2925 View Code Duplication
			if ( $send_state_messages ) {
2926
2927
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2928
				if ( $active_state = self::state( $state ) ) {
2929
					$active_state = explode( ',', $active_state );
2930
				} else {
2931
					$active_state = array();
2932
				}
2933
				$active_state[] = $module;
2934
				self::state( $state, implode( ',', $active_state ) );
2935
			}
2936
2937
			self::update_active_modules( $active );
2938
2939
			ob_end_clean();
2940
		}
2941
2942
		if ( $send_state_messages ) {
2943
			self::state( 'error', false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2945
		}
2946
2947
		self::catch_errors( false );
2948
		/**
2949
		 * Fires when default modules are activated.
2950
		 *
2951
		 * @since 1.9.0
2952
		 *
2953
		 * @param string $min_version Minimum version number required to use modules.
2954
		 * @param string $max_version Maximum version number required to use modules.
2955
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2956
		 */
2957
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2958
	}
2959
2960
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2961
		/**
2962
		 * Fires before a module is activated.
2963
		 *
2964
		 * @since 2.6.0
2965
		 *
2966
		 * @param string $module Module slug.
2967
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2968
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2969
		 */
2970
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2971
2972
		$jetpack = self::init();
2973
2974
		if ( ! strlen( $module ) ) {
2975
			return false;
2976
		}
2977
2978
		if ( ! self::is_module( $module ) ) {
2979
			return false;
2980
		}
2981
2982
		// If it's already active, then don't do it again
2983
		$active = self::get_active_modules();
2984
		foreach ( $active as $act ) {
2985
			if ( $act == $module ) {
2986
				return true;
2987
			}
2988
		}
2989
2990
		$module_data = self::get_module( $module );
2991
2992
		$is_offline_mode = ( new Status() )->is_offline_mode();
2993
		if ( ! self::is_active() ) {
2994
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
2995
				return false;
2996
			}
2997
2998
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
2999
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
3000
				return false;
3001
			}
3002
		}
3003
3004
		// Check and see if the old plugin is active
3005
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3006
			// Deactivate the old plugin
3007
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3008
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3009
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3010
				self::state( 'deactivated_plugins', $module );
3011
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3012
				exit;
3013
			}
3014
		}
3015
3016
		// Protect won't work with mis-configured IPs
3017
		if ( 'protect' === $module ) {
3018
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3019
			if ( ! jetpack_protect_get_ip() ) {
3020
				self::state( 'message', 'protect_misconfigured_ip' );
3021
				return false;
3022
			}
3023
		}
3024
3025
		if ( ! Jetpack_Plan::supports( $module ) ) {
3026
			return false;
3027
		}
3028
3029
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3030
		self::state( 'module', $module );
3031
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3032
3033
		self::catch_errors( true );
3034
		ob_start();
3035
		require self::get_module_path( $module );
3036
		/** This action is documented in class.jetpack.php */
3037
		do_action( 'jetpack_activate_module', $module );
3038
		$active[] = $module;
3039
		self::update_active_modules( $active );
3040
3041
		self::state( 'error', false ); // the override
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3042
		ob_end_clean();
3043
		self::catch_errors( false );
3044
3045
		if ( $redirect ) {
3046
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3047
		}
3048
		if ( $exit ) {
3049
			exit;
3050
		}
3051
		return true;
3052
	}
3053
3054
	function activate_module_actions( $module ) {
3055
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3056
	}
3057
3058
	public static function deactivate_module( $module ) {
3059
		/**
3060
		 * Fires when a module is deactivated.
3061
		 *
3062
		 * @since 1.9.0
3063
		 *
3064
		 * @param string $module Module slug.
3065
		 */
3066
		do_action( 'jetpack_pre_deactivate_module', $module );
3067
3068
		$jetpack = self::init();
0 ignored issues
show
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3069
3070
		$active = self::get_active_modules();
3071
		$new    = array_filter( array_diff( $active, (array) $module ) );
3072
3073
		return self::update_active_modules( $new );
3074
	}
3075
3076
	public static function enable_module_configurable( $module ) {
3077
		$module = self::get_module_slug( $module );
3078
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3079
	}
3080
3081
	/**
3082
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3083
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3084
	 *
3085
	 * @param string $module Module slug
3086
	 * @return string $url module configuration URL
3087
	 */
3088
	public static function module_configuration_url( $module ) {
3089
		$module      = self::get_module_slug( $module );
3090
		$default_url = self::admin_url() . "#/settings?term=$module";
3091
		/**
3092
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3093
		 *
3094
		 * @since 6.9.0
3095
		 *
3096
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3097
		 */
3098
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3099
3100
		return $url;
3101
	}
3102
3103
	/* Installation */
3104
	public static function bail_on_activation( $message, $deactivate = true ) {
3105
		?>
3106
<!doctype html>
3107
<html>
3108
<head>
3109
<meta charset="<?php bloginfo( 'charset' ); ?>">
3110
<style>
3111
* {
3112
	text-align: center;
3113
	margin: 0;
3114
	padding: 0;
3115
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3116
}
3117
p {
3118
	margin-top: 1em;
3119
	font-size: 18px;
3120
}
3121
</style>
3122
<body>
3123
<p><?php echo esc_html( $message ); ?></p>
3124
</body>
3125
</html>
3126
		<?php
3127
		if ( $deactivate ) {
3128
			$plugins = get_option( 'active_plugins' );
3129
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3130
			$update  = false;
3131
			foreach ( $plugins as $i => $plugin ) {
3132
				if ( $plugin === $jetpack ) {
3133
					$plugins[ $i ] = false;
3134
					$update        = true;
3135
				}
3136
			}
3137
3138
			if ( $update ) {
3139
				update_option( 'active_plugins', array_filter( $plugins ) );
3140
			}
3141
		}
3142
		exit;
3143
	}
3144
3145
	/**
3146
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3147
	 *
3148
	 * @static
3149
	 */
3150
	public static function plugin_activation( $network_wide ) {
3151
		Jetpack_Options::update_option( 'activated', 1 );
3152
3153
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3154
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3155
		}
3156
3157
		if ( $network_wide ) {
3158
			self::state( 'network_nag', true );
0 ignored issues
show
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3159
		}
3160
3161
		// For firing one-off events (notices) immediately after activation
3162
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3163
3164
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3165
3166
		Health::on_jetpack_activated();
3167
3168
		self::plugin_initialize();
3169
	}
3170
3171
	public static function get_activation_source( $referer_url ) {
3172
3173
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3174
			return array( 'wp-cli', null );
3175
		}
3176
3177
		$referer = wp_parse_url( $referer_url );
3178
3179
		$source_type  = 'unknown';
3180
		$source_query = null;
3181
3182
		if ( ! is_array( $referer ) ) {
3183
			return array( $source_type, $source_query );
3184
		}
3185
3186
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3187
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3188
3189
		if ( isset( $referer['query'] ) ) {
3190
			parse_str( $referer['query'], $query_parts );
3191
		} else {
3192
			$query_parts = array();
3193
		}
3194
3195
		if ( $plugins_path === $referer['path'] ) {
3196
			$source_type = 'list';
3197
		} elseif ( $plugins_install_path === $referer['path'] ) {
3198
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3199
			switch ( $tab ) {
3200
				case 'popular':
3201
					$source_type = 'popular';
3202
					break;
3203
				case 'recommended':
3204
					$source_type = 'recommended';
3205
					break;
3206
				case 'favorites':
3207
					$source_type = 'favorites';
3208
					break;
3209
				case 'search':
3210
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3211
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3212
					break;
3213
				default:
3214
					$source_type = 'featured';
3215
			}
3216
		}
3217
3218
		return array( $source_type, $source_query );
3219
	}
3220
3221
	/**
3222
	 * Runs before bumping version numbers up to a new version
3223
	 *
3224
	 * @param string $version    Version:timestamp.
3225
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3226
	 */
3227
	public static function do_version_bump( $version, $old_version ) {
3228
		if ( $old_version ) { // For existing Jetpack installations.
3229
3230
			// If a front end page is visited after the update, the 'wp' action will fire.
3231
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3232
3233
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3234
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3235
		}
3236
	}
3237
3238
	/**
3239
	 * Sets the display_update_modal state.
3240
	 */
3241
	public static function set_update_modal_display() {
3242
		self::state( 'display_update_modal', true );
0 ignored issues
show
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3243
	}
3244
3245
	/**
3246
	 * Sets the internal version number and activation state.
3247
	 *
3248
	 * @static
3249
	 */
3250
	public static function plugin_initialize() {
3251
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3252
			Jetpack_Options::update_option( 'activated', 2 );
3253
		}
3254
3255 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3256
			$version = $old_version = JETPACK__VERSION . ':' . time();
3257
			/** This action is documented in class.jetpack.php */
3258
			do_action( 'updating_jetpack_version', $version, false );
3259
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3260
		}
3261
3262
		self::load_modules();
3263
3264
		Jetpack_Options::delete_option( 'do_activate' );
3265
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3266
	}
3267
3268
	/**
3269
	 * Removes all connection options
3270
	 *
3271
	 * @static
3272
	 */
3273
	public static function plugin_deactivation() {
3274
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3275
		$tracking = new Tracking();
3276
		$tracking->record_user_event( 'deactivate_plugin', array() );
3277
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3278
			Jetpack_Network::init()->deactivate();
3279
		} else {
3280
			self::disconnect( false );
3281
			// Jetpack_Heartbeat::init()->deactivate();
3282
		}
3283
	}
3284
3285
	/**
3286
	 * Disconnects from the Jetpack servers.
3287
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3288
	 *
3289
	 * @static
3290
	 */
3291
	public static function disconnect( $update_activated_state = true ) {
3292
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3293
		$connection = self::connection();
3294
		$connection->clean_nonces( true );
3295
3296
		// If the site is in an IDC because sync is not allowed,
3297
		// let's make sure to not disconnect the production site.
3298
		if ( ! self::validate_sync_error_idc_option() ) {
3299
			$tracking = new Tracking();
3300
			$tracking->record_user_event( 'disconnect_site', array() );
3301
3302
			$connection->disconnect_site_wpcom( true );
3303
		}
3304
3305
		$connection->delete_all_connection_tokens( true );
3306
		Jetpack_IDC::clear_all_idc_options();
3307
3308
		if ( $update_activated_state ) {
3309
			Jetpack_Options::update_option( 'activated', 4 );
3310
		}
3311
3312
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3313
			// Check then record unique disconnection if site has never been disconnected previously
3314
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3315
				$jetpack_unique_connection['disconnected'] = 1;
3316
			} else {
3317
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3318
					// track unique disconnect
3319
					$jetpack = self::init();
3320
3321
					$jetpack->stat( 'connections', 'unique-disconnect' );
3322
					$jetpack->do_stats( 'server_side' );
3323
				}
3324
				// increment number of times disconnected
3325
				$jetpack_unique_connection['disconnected'] += 1;
3326
			}
3327
3328
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3329
		}
3330
3331
		// Delete all the sync related data. Since it could be taking up space.
3332
		Sender::get_instance()->uninstall();
3333
3334
	}
3335
3336
	/**
3337
	 * Unlinks the current user from the linked WordPress.com user.
3338
	 *
3339
	 * @deprecated since 7.7
3340
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3341
	 *
3342
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
3343
	 * @return Boolean Whether the disconnection of the user was successful.
3344
	 */
3345
	public static function unlink_user( $user_id = null ) {
3346
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3347
		return Connection_Manager::disconnect_user( $user_id );
3348
	}
3349
3350
	/**
3351
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3352
	 */
3353
	public static function try_registration() {
3354
		$terms_of_service = new Terms_Of_Service();
3355
		// The user has agreed to the TOS at some point by now.
3356
		$terms_of_service->agree();
3357
3358
		// Let's get some testing in beta versions and such.
3359
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3360
			// Before attempting to connect, let's make sure that the domains are viable.
3361
			$domains_to_check = array_unique(
3362
				array(
3363
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3364
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3365
				)
3366
			);
3367
			foreach ( $domains_to_check as $domain ) {
3368
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
$domain is of type array<string,string>|false, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3369
				if ( is_wp_error( $result ) ) {
3370
					return $result;
3371
				}
3372
			}
3373
		}
3374
3375
		$result = self::register();
3376
3377
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3378
		if ( ! $result || is_wp_error( $result ) ) {
3379
			return $result;
3380
		} else {
3381
			return true;
3382
		}
3383
	}
3384
3385
	/**
3386
	 * Tracking an internal event log. Try not to put too much chaff in here.
3387
	 *
3388
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3389
	 */
3390
	public static function log( $code, $data = null ) {
3391
		// only grab the latest 200 entries
3392
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3393
3394
		// Append our event to the log
3395
		$log_entry = array(
3396
			'time'    => time(),
3397
			'user_id' => get_current_user_id(),
3398
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3399
			'code'    => $code,
3400
		);
3401
		// Don't bother storing it unless we've got some.
3402
		if ( ! is_null( $data ) ) {
3403
			$log_entry['data'] = $data;
3404
		}
3405
		$log[] = $log_entry;
3406
3407
		// Try add_option first, to make sure it's not autoloaded.
3408
		// @todo: Add an add_option method to Jetpack_Options
3409
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3410
			Jetpack_Options::update_option( 'log', $log );
3411
		}
3412
3413
		/**
3414
		 * Fires when Jetpack logs an internal event.
3415
		 *
3416
		 * @since 3.0.0
3417
		 *
3418
		 * @param array $log_entry {
3419
		 *  Array of details about the log entry.
3420
		 *
3421
		 *  @param string time Time of the event.
3422
		 *  @param int user_id ID of the user who trigerred the event.
3423
		 *  @param int blog_id Jetpack Blog ID.
3424
		 *  @param string code Unique name for the event.
3425
		 *  @param string data Data about the event.
3426
		 * }
3427
		 */
3428
		do_action( 'jetpack_log_entry', $log_entry );
3429
	}
3430
3431
	/**
3432
	 * Get the internal event log.
3433
	 *
3434
	 * @param $event (string) - only return the specific log events
3435
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3436
	 *
3437
	 * @return array of log events || WP_Error for invalid params
3438
	 */
3439
	public static function get_log( $event = false, $num = false ) {
3440
		if ( $event && ! is_string( $event ) ) {
3441
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3442
		}
3443
3444
		if ( $num && ! is_numeric( $num ) ) {
3445
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3446
		}
3447
3448
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3449
3450
		// If nothing set - act as it did before, otherwise let's start customizing the output
3451
		if ( ! $num && ! $event ) {
3452
			return $entire_log;
3453
		} else {
3454
			$entire_log = array_reverse( $entire_log );
3455
		}
3456
3457
		$custom_log_output = array();
3458
3459
		if ( $event ) {
3460
			foreach ( $entire_log as $log_event ) {
3461
				if ( $event == $log_event['code'] ) {
3462
					$custom_log_output[] = $log_event;
3463
				}
3464
			}
3465
		} else {
3466
			$custom_log_output = $entire_log;
3467
		}
3468
3469
		if ( $num ) {
3470
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3471
		}
3472
3473
		return $custom_log_output;
3474
	}
3475
3476
	/**
3477
	 * Log modification of important settings.
3478
	 */
3479
	public static function log_settings_change( $option, $old_value, $value ) {
3480
		switch ( $option ) {
3481
			case 'jetpack_sync_non_public_post_stati':
3482
				self::log( $option, $value );
3483
				break;
3484
		}
3485
	}
3486
3487
	/**
3488
	 * Return stat data for WPCOM sync
3489
	 */
3490
	public static function get_stat_data( $encode = true, $extended = true ) {
3491
		$data = Jetpack_Heartbeat::generate_stats_array();
3492
3493
		if ( $extended ) {
3494
			$additional_data = self::get_additional_stat_data();
3495
			$data            = array_merge( $data, $additional_data );
3496
		}
3497
3498
		if ( $encode ) {
3499
			return json_encode( $data );
3500
		}
3501
3502
		return $data;
3503
	}
3504
3505
	/**
3506
	 * Get additional stat data to sync to WPCOM
3507
	 */
3508
	public static function get_additional_stat_data( $prefix = '' ) {
3509
		$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...
3510
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3511
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3512
		$return[ "{$prefix}site-count" ]    = 0;
3513
3514
		if ( function_exists( 'get_blog_count' ) ) {
3515
			$return[ "{$prefix}site-count" ] = get_blog_count();
3516
		}
3517
		return $return;
3518
	}
3519
3520
	private static function get_site_user_count() {
3521
		global $wpdb;
3522
3523
		if ( function_exists( 'wp_is_large_network' ) ) {
3524
			if ( wp_is_large_network( 'users' ) ) {
3525
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3526
			}
3527
		}
3528
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3529
			// It wasn't there, so regenerate the data and save the transient
3530
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3531
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3532
		}
3533
		return $user_count;
3534
	}
3535
3536
	/* Admin Pages */
3537
3538
	function admin_init() {
3539
		// If the plugin is not connected, display a connect message.
3540
		if (
3541
			// the plugin was auto-activated and needs its candy
3542
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3543
		||
3544
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3545
			! Jetpack_Options::get_option( 'activated' )
3546
		) {
3547
			self::plugin_initialize();
3548
		}
3549
3550
		$is_offline_mode = ( new Status() )->is_offline_mode();
3551
		if ( ! self::is_active() && ! $is_offline_mode ) {
3552
			Jetpack_Connection_Banner::init();
3553
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3554
			// Upgrade: 1.1 -> 1.1.1
3555
			// Check and see if host can verify the Jetpack servers' SSL certificate
3556
			$args       = array();
3557
			$connection = self::connection();
3558
			Client::_wp_remote_request(
3559
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3560
				$args,
3561
				true
3562
			);
3563
		}
3564
3565
		Jetpack_Wizard_Banner::init();
3566
3567
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3568
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3569
		}
3570
3571
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3572
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3573
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3574
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3575
3576
		if ( self::is_active() || $is_offline_mode ) {
3577
			// Artificially throw errors in certain specific cases during plugin activation.
3578
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3579
		}
3580
3581
		// Add custom column in wp-admin/users.php to show whether user is linked.
3582
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3583
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3584
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3585
	}
3586
3587
	function admin_body_class( $admin_body_class = '' ) {
3588
		$classes = explode( ' ', trim( $admin_body_class ) );
3589
3590
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3591
3592
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3593
		return " $admin_body_class ";
3594
	}
3595
3596
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3597
		return $admin_body_class . ' jetpack-pagestyles ';
3598
	}
3599
3600
	/**
3601
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3602
	 * This function artificially throws errors for such cases (per a specific list).
3603
	 *
3604
	 * @param string $plugin The activated plugin.
3605
	 */
3606
	function throw_error_on_activate_plugin( $plugin ) {
3607
		$active_modules = self::get_active_modules();
3608
3609
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3610
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3611
			$throw = false;
3612
3613
			// Try and make sure it really was the stats plugin
3614
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3615
				if ( 'stats.php' == basename( $plugin ) ) {
3616
					$throw = true;
3617
				}
3618
			} else {
3619
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3620
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3621
					$throw = true;
3622
				}
3623
			}
3624
3625
			if ( $throw ) {
3626
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3627
			}
3628
		}
3629
	}
3630
3631
	function intercept_plugin_error_scrape_init() {
3632
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3633
	}
3634
3635
	function intercept_plugin_error_scrape( $action, $result ) {
3636
		if ( ! $result ) {
3637
			return;
3638
		}
3639
3640
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3641
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3642
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3643
			}
3644
		}
3645
	}
3646
3647
	/**
3648
	 * Register the remote file upload request handlers, if needed.
3649
	 *
3650
	 * @access public
3651
	 */
3652
	public function add_remote_request_handlers() {
3653
		// Remote file uploads are allowed only via AJAX requests.
3654
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3655
			return;
3656
		}
3657
3658
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3659
		$remote_request_actions = array(
3660
			'jetpack_upload_file',
3661
			'jetpack_update_file',
3662
		);
3663
3664
		// phpcs:ignore WordPress.Security.NonceVerification
3665
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3666
			return;
3667
		}
3668
3669
		// Require Jetpack authentication for the remote file upload AJAX requests.
3670
		if ( ! $this->connection_manager ) {
3671
			$this->connection_manager = new Connection_Manager();
3672
		}
3673
3674
		$this->connection_manager->require_jetpack_authentication();
3675
3676
		// Register the remote file upload AJAX handlers.
3677
		foreach ( $remote_request_actions as $action ) {
3678
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3679
		}
3680
	}
3681
3682
	/**
3683
	 * Handler for Jetpack remote file uploads.
3684
	 *
3685
	 * @access public
3686
	 */
3687
	public function remote_request_handlers() {
3688
		$action = current_filter();
0 ignored issues
show
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3689
3690
		switch ( current_filter() ) {
3691
			case 'wp_ajax_nopriv_jetpack_upload_file':
3692
				$response = $this->upload_handler();
3693
				break;
3694
3695
			case 'wp_ajax_nopriv_jetpack_update_file':
3696
				$response = $this->upload_handler( true );
3697
				break;
3698
			default:
3699
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
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...
3700
				break;
3701
		}
3702
3703
		if ( ! $response ) {
3704
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
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...
3705
		}
3706
3707
		if ( is_wp_error( $response ) ) {
3708
			$status_code       = $response->get_error_data();
0 ignored issues
show
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...
3709
			$error             = $response->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3710
			$error_description = $response->get_error_message();
0 ignored issues
show
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3711
3712
			if ( ! is_int( $status_code ) ) {
3713
				$status_code = 400;
3714
			}
3715
3716
			status_header( $status_code );
3717
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3718
		}
3719
3720
		status_header( 200 );
3721
		if ( true === $response ) {
3722
			exit;
3723
		}
3724
3725
		die( json_encode( (object) $response ) );
3726
	}
3727
3728
	/**
3729
	 * Uploads a file gotten from the global $_FILES.
3730
	 * If `$update_media_item` is true and `post_id` is defined
3731
	 * the attachment file of the media item (gotten through of the post_id)
3732
	 * will be updated instead of add a new one.
3733
	 *
3734
	 * @param  boolean $update_media_item - update media attachment
3735
	 * @return array - An array describing the uploadind files process
3736
	 */
3737
	function upload_handler( $update_media_item = false ) {
3738
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3739
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
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...
3740
		}
3741
3742
		$user = wp_authenticate( '', '' );
3743
		if ( ! $user || is_wp_error( $user ) ) {
3744
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
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...
3745
		}
3746
3747
		wp_set_current_user( $user->ID );
3748
3749
		if ( ! current_user_can( 'upload_files' ) ) {
3750
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
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...
3751
		}
3752
3753
		if ( empty( $_FILES ) ) {
3754
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
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...
3755
		}
3756
3757
		foreach ( array_keys( $_FILES ) as $files_key ) {
3758
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3759
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
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...
3760
			}
3761
		}
3762
3763
		$media_keys = array_keys( $_FILES['media'] );
3764
3765
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

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

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4065
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4066
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4067
		}
4068
		return $login_url;
4069
	}
4070
4071
	/**
4072
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4073
	 *
4074
	 * @since Jetpack 8.4
4075
	 */
4076
	public function login_init() {
4077
		// phpcs:ignore WordPress.Security.NonceVerification
4078
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4079
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4080
			wp_safe_redirect(
4081
				add_query_arg(
4082
					array(
4083
						'forceInstall' => 1,
4084
						'url'          => rawurlencode( get_site_url() ),
4085
					),
4086
					// @todo provide way to go to specific calypso env.
4087
					self::get_calypso_host() . 'jetpack/connect'
4088
				)
4089
			);
4090
			exit;
4091
		}
4092
	}
4093
4094
	/*
4095
	 * Registration flow:
4096
	 * 1 - ::admin_page_load() action=register
4097
	 * 2 - ::try_registration()
4098
	 * 3 - ::register()
4099
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4100
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4101
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4102
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4103
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4104
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4105
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4106
	 *       jetpack_id, jetpack_secret, jetpack_public
4107
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4108
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4109
	 * 5 - user logs in with WP.com account
4110
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4111
	 *		- Manager::authorize()
4112
	 *		- Manager::get_token()
4113
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4114
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4115
	 *			- which responds with access_token, token_type, scope
4116
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4117
	 *		- Jetpack::activate_default_modules()
4118
	 *     		- Deactivates deprecated plugins
4119
	 *     		- Activates all default modules
4120
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4121
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4122
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4123
	 *     Done!
4124
	 */
4125
4126
	/**
4127
	 * Handles the page load events for the Jetpack admin page
4128
	 */
4129
	function admin_page_load() {
4130
		$error = false;
4131
4132
		// Make sure we have the right body class to hook stylings for subpages off of.
4133
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4134
4135
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4136
			// Should only be used in intermediate redirects to preserve state across redirects
4137
			self::restate();
4138
		}
4139
4140
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4141
			// @todo: Add validation against a known allowed list.
4142
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4143
			// User clicked in the iframe to link their accounts
4144
			if ( ! self::is_user_connected() ) {
4145
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4146
4147
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4148
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4149
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4150
4151
				if ( isset( $_GET['notes_iframe'] ) ) {
4152
					$connect_url .= '&notes_iframe';
4153
				}
4154
				wp_redirect( $connect_url );
4155
				exit;
4156
			} else {
4157
				if ( ! isset( $_GET['calypso_env'] ) ) {
4158
					self::state( 'message', 'already_authorized' );
4159
					wp_safe_redirect( self::admin_url() );
4160
					exit;
4161
				} else {
4162
					$connect_url  = $this->build_connect_url( true, false, $from );
4163
					$connect_url .= '&already_authorized=true';
4164
					wp_redirect( $connect_url );
4165
					exit;
4166
				}
4167
			}
4168
		}
4169
4170
		if ( isset( $_GET['action'] ) ) {
4171
			switch ( $_GET['action'] ) {
4172
				case 'authorize':
4173
					if ( self::is_active() && self::is_user_connected() ) {
4174
						self::state( 'message', 'already_authorized' );
4175
						wp_safe_redirect( self::admin_url() );
4176
						exit;
4177
					}
4178
					self::log( 'authorize' );
4179
					$client_server = new Jetpack_Client_Server();
4180
					$client_server->client_authorize();
4181
					exit;
4182
				case 'register':
4183
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4184
						$error = 'cheatin';
4185
						break;
4186
					}
4187
					check_admin_referer( 'jetpack-register' );
4188
					self::log( 'register' );
4189
					self::maybe_set_version_option();
4190
					$registered = self::try_registration();
4191 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4192
						$error = $registered->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4193
						self::state( 'error', $error );
4194
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4195
4196
						/**
4197
						 * Jetpack registration Error.
4198
						 *
4199
						 * @since 7.5.0
4200
						 *
4201
						 * @param string|int $error The error code.
4202
						 * @param \WP_Error $registered The error object.
4203
						 */
4204
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4205
						break;
4206
					}
4207
4208
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4209
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4210
4211
					/**
4212
					 * Jetpack registration Success.
4213
					 *
4214
					 * @since 7.5.0
4215
					 *
4216
					 * @param string $from 'from' GET parameter;
4217
					 */
4218
					do_action( 'jetpack_connection_register_success', $from );
4219
4220
					$url = $this->build_connect_url( true, $redirect, $from );
4221
4222
					if ( ! empty( $_GET['onboarding'] ) ) {
4223
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4224
					}
4225
4226
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4227
						$url = add_query_arg( 'auth_approved', 'true', $url );
4228
					}
4229
4230
					wp_redirect( $url );
4231
					exit;
4232
				case 'activate':
4233
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4234
						$error = 'cheatin';
4235
						break;
4236
					}
4237
4238
					$module = stripslashes( $_GET['module'] );
4239
					check_admin_referer( "jetpack_activate-$module" );
4240
					self::log( 'activate', $module );
4241
					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...
4242
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4243
					}
4244
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4245
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4246
					exit;
4247
				case 'activate_default_modules':
4248
					check_admin_referer( 'activate_default_modules' );
4249
					self::log( 'activate_default_modules' );
4250
					self::restate();
4251
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4252
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4253
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4254
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4255
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4256
					exit;
4257
				case 'disconnect':
4258
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4259
						$error = 'cheatin';
4260
						break;
4261
					}
4262
4263
					check_admin_referer( 'jetpack-disconnect' );
4264
					self::log( 'disconnect' );
4265
					self::disconnect();
4266
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4267
					exit;
4268
				case 'reconnect':
4269
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4270
						$error = 'cheatin';
4271
						break;
4272
					}
4273
4274
					check_admin_referer( 'jetpack-reconnect' );
4275
					self::log( 'reconnect' );
4276
					$this->disconnect();
4277
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4278
					exit;
4279 View Code Duplication
				case 'deactivate':
4280
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4281
						$error = 'cheatin';
4282
						break;
4283
					}
4284
4285
					$modules = stripslashes( $_GET['module'] );
4286
					check_admin_referer( "jetpack_deactivate-$modules" );
4287
					foreach ( explode( ',', $modules ) as $module ) {
4288
						self::log( 'deactivate', $module );
4289
						self::deactivate_module( $module );
4290
						self::state( 'message', 'module_deactivated' );
4291
					}
4292
					self::state( 'module', $modules );
4293
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4294
					exit;
4295
				case 'unlink':
4296
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4297
					check_admin_referer( 'jetpack-unlink' );
4298
					self::log( 'unlink' );
4299
					Connection_Manager::disconnect_user();
4300
					self::state( 'message', 'unlinked' );
4301
					if ( 'sub-unlink' == $redirect ) {
4302
						wp_safe_redirect( admin_url() );
4303
					} else {
4304
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4305
					}
4306
					exit;
4307
				case 'onboard':
4308
					if ( ! current_user_can( 'manage_options' ) ) {
4309
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4310
					} else {
4311
						self::create_onboarding_token();
4312
						$url = $this->build_connect_url( true );
4313
4314
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4315
							$url = add_query_arg( 'onboarding', $token, $url );
4316
						}
4317
4318
						$calypso_env = $this->get_calypso_env();
4319
						if ( ! empty( $calypso_env ) ) {
4320
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4321
						}
4322
4323
						wp_redirect( $url );
4324
						exit;
4325
					}
4326
					exit;
4327
				default:
4328
					/**
4329
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4330
					 *
4331
					 * @since 2.6.0
4332
					 *
4333
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4334
					 */
4335
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4336
			}
4337
		}
4338
4339
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4340
			self::activate_new_modules( true );
4341
		}
4342
4343
		$message_code = self::state( 'message' );
4344
		if ( self::state( 'optin-manage' ) ) {
4345
			$activated_manage = $message_code;
4346
			$message_code     = 'jetpack-manage';
4347
		}
4348
4349
		switch ( $message_code ) {
4350
			case 'jetpack-manage':
4351
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4352
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4353
				$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>';
4354
				if ( $activated_manage ) {
0 ignored issues
show
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4355
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4356
				}
4357
				break;
4358
4359
		}
4360
4361
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4362
4363
		if ( ! empty( $deactivated_plugins ) ) {
4364
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4365
			$deactivated_titles  = array();
4366
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4367
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4368
					continue;
4369
				}
4370
4371
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4372
			}
4373
4374
			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...
4375
				if ( $this->message ) {
4376
					$this->message .= "<br /><br />\n";
4377
				}
4378
4379
				$this->message .= wp_sprintf(
4380
					_n(
4381
						'Jetpack contains the most recent version of the old %l plugin.',
4382
						'Jetpack contains the most recent versions of the old %l plugins.',
4383
						count( $deactivated_titles ),
4384
						'jetpack'
4385
					),
4386
					$deactivated_titles
4387
				);
4388
4389
				$this->message .= "<br />\n";
4390
4391
				$this->message .= _n(
4392
					'The old version has been deactivated and can be removed from your site.',
4393
					'The old versions have been deactivated and can be removed from your site.',
4394
					count( $deactivated_titles ),
4395
					'jetpack'
4396
				);
4397
			}
4398
		}
4399
4400
		$this->privacy_checks = self::state( 'privacy_checks' );
4401
4402
		if ( $this->message || $this->error || $this->privacy_checks ) {
4403
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4404
		}
4405
4406
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4407
	}
4408
4409
	function admin_notices() {
4410
4411
		if ( $this->error ) {
4412
			?>
4413
<div id="message" class="jetpack-message jetpack-err">
4414
	<div class="squeezer">
4415
		<h2>
4416
			<?php
4417
			echo wp_kses(
4418
				$this->error,
4419
				array(
4420
					'a'      => array( 'href' => array() ),
4421
					'small'  => true,
4422
					'code'   => true,
4423
					'strong' => true,
4424
					'br'     => true,
4425
					'b'      => true,
4426
				)
4427
			);
4428
			?>
4429
			</h2>
4430
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4431
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4432
<?php	endif; ?>
4433
	</div>
4434
</div>
4435
			<?php
4436
		}
4437
4438
		if ( $this->message ) {
4439
			?>
4440
<div id="message" class="jetpack-message">
4441
	<div class="squeezer">
4442
		<h2>
4443
			<?php
4444
			echo wp_kses(
4445
				$this->message,
4446
				array(
4447
					'strong' => array(),
4448
					'a'      => array( 'href' => true ),
4449
					'br'     => true,
4450
				)
4451
			);
4452
			?>
4453
			</h2>
4454
	</div>
4455
</div>
4456
			<?php
4457
		}
4458
4459
		if ( $this->privacy_checks ) :
4460
			$module_names = $module_slugs = array();
4461
4462
			$privacy_checks = explode( ',', $this->privacy_checks );
4463
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4464
			foreach ( $privacy_checks as $module_slug ) {
4465
				$module = self::get_module( $module_slug );
4466
				if ( ! $module ) {
4467
					continue;
4468
				}
4469
4470
				$module_slugs[] = $module_slug;
4471
				$module_names[] = "<strong>{$module['name']}</strong>";
4472
			}
4473
4474
			$module_slugs = join( ',', $module_slugs );
4475
			?>
4476
<div id="message" class="jetpack-message jetpack-err">
4477
	<div class="squeezer">
4478
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4479
		<p>
4480
			<?php
4481
			echo wp_kses(
4482
				wptexturize(
4483
					wp_sprintf(
4484
						_nx(
4485
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4486
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4487
							count( $privacy_checks ),
4488
							'%l = list of Jetpack module/feature names',
4489
							'jetpack'
4490
						),
4491
						$module_names
4492
					)
4493
				),
4494
				array( 'strong' => true )
4495
			);
4496
4497
			echo "\n<br />\n";
4498
4499
			echo wp_kses(
4500
				sprintf(
4501
					_nx(
4502
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4503
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4504
						count( $privacy_checks ),
4505
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4506
						'jetpack'
4507
					),
4508
					wp_nonce_url(
4509
						self::admin_url(
4510
							array(
4511
								'page'   => 'jetpack',
4512
								'action' => 'deactivate',
4513
								'module' => urlencode( $module_slugs ),
4514
							)
4515
						),
4516
						"jetpack_deactivate-$module_slugs"
4517
					),
4518
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4519
				),
4520
				array(
4521
					'a' => array(
4522
						'href'  => true,
4523
						'title' => true,
4524
					),
4525
				)
4526
			);
4527
			?>
4528
		</p>
4529
	</div>
4530
</div>
4531
			<?php
4532
endif;
4533
	}
4534
4535
	/**
4536
	 * We can't always respond to a signed XML-RPC request with a
4537
	 * helpful error message. In some circumstances, doing so could
4538
	 * leak information.
4539
	 *
4540
	 * Instead, track that the error occurred via a Jetpack_Option,
4541
	 * and send that data back in the heartbeat.
4542
	 * All this does is increment a number, but it's enough to find
4543
	 * trends.
4544
	 *
4545
	 * @param WP_Error $xmlrpc_error The error produced during
4546
	 *                               signature validation.
4547
	 */
4548
	function track_xmlrpc_error( $xmlrpc_error ) {
4549
		$code = is_wp_error( $xmlrpc_error )
4550
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4551
			: 'should-not-happen';
4552
4553
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4554
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4555
			// No need to update the option if we already have
4556
			// this code stored.
4557
			return;
4558
		}
4559
		$xmlrpc_errors[ $code ] = true;
4560
4561
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4562
	}
4563
4564
	/**
4565
	 * Initialize the jetpack stats instance only when needed
4566
	 *
4567
	 * @return void
4568
	 */
4569
	private function initialize_stats() {
4570
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4571
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4572
		}
4573
	}
4574
4575
	/**
4576
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4577
	 */
4578
	function stat( $group, $detail ) {
4579
		$this->initialize_stats();
4580
		$this->a8c_mc_stats_instance->add( $group, $detail );
4581
4582
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4583
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4584
	}
4585
4586
	/**
4587
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4588
	 */
4589
	function do_stats( $method = '' ) {
4590
		$this->initialize_stats();
4591
		if ( 'server_side' === $method ) {
4592
			$this->a8c_mc_stats_instance->do_server_side_stats();
4593
		} else {
4594
			$this->a8c_mc_stats_instance->do_stats();
4595
		}
4596
4597
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4598
		$this->stats = array();
4599
	}
4600
4601
	/**
4602
	 * Runs stats code for a one-off, server-side.
4603
	 *
4604
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4605
	 *
4606
	 * @return bool If it worked.
4607
	 */
4608
	static function do_server_side_stat( $args ) {
4609
		$url                   = self::build_stats_url( $args );
4610
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4611
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4612
	}
4613
4614
	/**
4615
	 * Builds the stats url.
4616
	 *
4617
	 * @param $args array|string The arguments to append to the URL.
4618
	 *
4619
	 * @return string The URL to be pinged.
4620
	 */
4621
	static function build_stats_url( $args ) {
4622
4623
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4624
		return $a8c_mc_stats_instance->build_stats_url( $args );
4625
4626
	}
4627
4628
	/**
4629
	 * Get the role of the current user.
4630
	 *
4631
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4632
	 *
4633
	 * @access public
4634
	 * @static
4635
	 *
4636
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4637
	 */
4638
	public static function translate_current_user_to_role() {
4639
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4640
4641
		$roles = new Roles();
4642
		return $roles->translate_current_user_to_role();
4643
	}
4644
4645
	/**
4646
	 * Get the role of a particular user.
4647
	 *
4648
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4649
	 *
4650
	 * @access public
4651
	 * @static
4652
	 *
4653
	 * @param \WP_User $user User object.
4654
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4655
	 */
4656
	public static function translate_user_to_role( $user ) {
4657
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4658
4659
		$roles = new Roles();
4660
		return $roles->translate_user_to_role( $user );
4661
	}
4662
4663
	/**
4664
	 * Get the minimum capability for a role.
4665
	 *
4666
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4667
	 *
4668
	 * @access public
4669
	 * @static
4670
	 *
4671
	 * @param string $role Role name.
4672
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4673
	 */
4674
	public static function translate_role_to_cap( $role ) {
4675
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4676
4677
		$roles = new Roles();
4678
		return $roles->translate_role_to_cap( $role );
4679
	}
4680
4681
	/**
4682
	 * Sign a user role with the master access token.
4683
	 * If not specified, will default to the current user.
4684
	 *
4685
	 * @deprecated since 7.7
4686
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4687
	 *
4688
	 * @access public
4689
	 * @static
4690
	 *
4691
	 * @param string $role    User role.
4692
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
4693
	 * @return string Signed user role.
4694
	 */
4695
	public static function sign_role( $role, $user_id = null ) {
4696
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4697
		return self::connection()->sign_role( $role, $user_id );
4698
	}
4699
4700
	/**
4701
	 * Builds a URL to the Jetpack connection auth page
4702
	 *
4703
	 * @since 3.9.5
4704
	 *
4705
	 * @param bool        $raw If true, URL will not be escaped.
4706
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4707
	 *                              If string, will be a custom redirect.
4708
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4709
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4710
	 *
4711
	 * @return string Connect URL
4712
	 */
4713
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4714
		$site_id    = Jetpack_Options::get_option( 'id' );
4715
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4716
4717
		if ( $register || ! $blog_token || ! $site_id ) {
4718
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4719
4720
			if ( ! empty( $redirect ) ) {
4721
				$url = add_query_arg(
4722
					'redirect',
4723
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4724
					$url
4725
				);
4726
			}
4727
4728
			if ( is_network_admin() ) {
4729
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4730
			}
4731
4732
			$calypso_env = self::get_calypso_env();
4733
4734
			if ( ! empty( $calypso_env ) ) {
4735
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4736
			}
4737
		} else {
4738
4739
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4740
			// because otherwise this logic can get us in to a loop.
4741
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4742
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4743
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4744
4745
				$response = Client::wpcom_json_api_request_as_blog(
4746
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4747
					'1.1'
4748
				);
4749
4750
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4751
4752
					// Generating a register URL instead to refresh the existing token
4753
					return $this->build_connect_url( $raw, $redirect, $from, true );
4754
				}
4755
			}
4756
4757
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4713 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...
4758
		}
4759
4760
		if ( $from ) {
4761
			$url = add_query_arg( 'from', $from, $url );
4762
		}
4763
4764
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4765
		/**
4766
		 * Filter the URL used when connecting a user to a WordPress.com account.
4767
		 *
4768
		 * @since 8.1.0
4769
		 *
4770
		 * @param string $url Connection URL.
4771
		 * @param bool   $raw If true, URL will not be escaped.
4772
		 */
4773
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
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...
4774
	}
4775
4776
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4777
4778
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4779
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4780
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4781
4782
		if ( $iframe ) {
4783
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4784
		}
4785
4786
		$c8n = self::connection();
4787
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
$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...
4788
4789
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4790
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4791
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4792
4793
		if ( $iframe ) {
4794
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4795
		}
4796
4797
		return $url;
4798
	}
4799
4800
	/**
4801
	 * Filters the connection URL parameter array.
4802
	 *
4803
	 * @param array $args default URL parameters used by the package.
4804
	 * @return array the modified URL arguments array.
4805
	 */
4806
	public static function filter_connect_request_body( $args ) {
4807
		if (
4808
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4809
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4810
		) {
4811
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4812
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4813
				? $gp_locale->slug
4814
				: '';
4815
		}
4816
4817
		$tracking        = new Tracking();
4818
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4819
4820
		$args = array_merge(
4821
			$args,
4822
			array(
4823
				'_ui' => $tracks_identity['_ui'],
4824
				'_ut' => $tracks_identity['_ut'],
4825
			)
4826
		);
4827
4828
		$calypso_env = self::get_calypso_env();
4829
4830
		if ( ! empty( $calypso_env ) ) {
4831
			$args['calypso_env'] = $calypso_env;
4832
		}
4833
4834
		return $args;
4835
	}
4836
4837
	/**
4838
	 * Filters the URL that will process the connection data. It can be different from the URL
4839
	 * that we send the user to after everything is done.
4840
	 *
4841
	 * @param String $processing_url the default redirect URL used by the package.
4842
	 * @return String the modified URL.
4843
	 */
4844
	public static function filter_connect_processing_url( $processing_url ) {
4845
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4846
		return $processing_url;
4847
	}
4848
4849
	/**
4850
	 * Filters the redirection URL that is used for connect requests. The redirect
4851
	 * URL should return the user back to the Jetpack console.
4852
	 *
4853
	 * @param String $redirect the default redirect URL used by the package.
4854
	 * @return String the modified URL.
4855
	 */
4856
	public static function filter_connect_redirect_url( $redirect ) {
4857
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4858
		$redirect           = $redirect
4859
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4860
			: $jetpack_admin_page;
4861
4862
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4863
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4864
		}
4865
4866
		return $redirect;
4867
	}
4868
4869
	/**
4870
	 * This action fires at the beginning of the Manager::authorize method.
4871
	 */
4872
	public static function authorize_starting() {
4873
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4874
		// Checking if site has been active/connected previously before recording unique connection.
4875
		if ( ! $jetpack_unique_connection ) {
4876
			// jetpack_unique_connection option has never been set.
4877
			$jetpack_unique_connection = array(
4878
				'connected'    => 0,
4879
				'disconnected' => 0,
4880
				'version'      => '3.6.1',
4881
			);
4882
4883
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4884
4885
			// Track unique connection.
4886
			$jetpack = self::init();
4887
4888
			$jetpack->stat( 'connections', 'unique-connection' );
4889
			$jetpack->do_stats( 'server_side' );
4890
		}
4891
4892
		// Increment number of times connected.
4893
		$jetpack_unique_connection['connected'] += 1;
4894
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4895
	}
4896
4897
	/**
4898
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4899
	 * linked.
4900
	 */
4901
	public static function authorize_ending_linked() {
4902
		// Don't activate anything since we are just connecting a user.
4903
		self::state( 'message', 'linked' );
4904
	}
4905
4906
	/**
4907
	 * This action fires at the end of the Manager::authorize method when the master user is
4908
	 * authorized.
4909
	 *
4910
	 * @param array $data The request data.
4911
	 */
4912
	public static function authorize_ending_authorized( $data ) {
4913
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4914
		self::invalidate_onboarding_token();
4915
4916
		// If redirect_uri is SSO, ensure SSO module is enabled.
4917
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4918
4919
		/** This filter is documented in class.jetpack-cli.php */
4920
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4921
4922
		$activate_sso = (
4923
			isset( $redirect_options['action'] ) &&
4924
			'jetpack-sso' === $redirect_options['action'] &&
4925
			$jetpack_start_enable_sso
4926
		);
4927
4928
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4929
4930
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4931
	}
4932
4933
	/**
4934
	 * Get our assumed site creation date.
4935
	 * Calculated based on the earlier date of either:
4936
	 * - Earliest admin user registration date.
4937
	 * - Earliest date of post of any post type.
4938
	 *
4939
	 * @since 7.2.0
4940
	 * @deprecated since 7.8.0
4941
	 *
4942
	 * @return string Assumed site creation date and time.
4943
	 */
4944
	public static function get_assumed_site_creation_date() {
4945
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4946
		return self::connection()->get_assumed_site_creation_date();
4947
	}
4948
4949 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4950
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4951
4952
		if ( $activation_source_name ) {
4953
			$args['_as'] = urlencode( $activation_source_name );
4954
		}
4955
4956
		if ( $activation_source_keyword ) {
4957
			$args['_ak'] = urlencode( $activation_source_keyword );
4958
		}
4959
	}
4960
4961
	function build_reconnect_url( $raw = false ) {
4962
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4963
		return $raw ? $url : esc_url( $url );
4964
	}
4965
4966
	public static function admin_url( $args = null ) {
4967
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
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...
4968
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4969
		return $url;
4970
	}
4971
4972
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4973
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4974
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4975
	}
4976
4977
	function dismiss_jetpack_notice() {
4978
4979
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4980
			return;
4981
		}
4982
4983
		switch ( $_GET['jetpack-notice'] ) {
4984
			case 'dismiss':
4985
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4986
4987
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4988
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4989
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4990
				}
4991
				break;
4992
		}
4993
	}
4994
4995
	public static function sort_modules( $a, $b ) {
4996
		if ( $a['sort'] == $b['sort'] ) {
4997
			return 0;
4998
		}
4999
5000
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5001
	}
5002
5003
	function ajax_recheck_ssl() {
5004
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5005
		$result = self::permit_ssl( true );
5006
		wp_send_json(
5007
			array(
5008
				'enabled' => $result,
5009
				'message' => get_transient( 'jetpack_https_test_message' ),
5010
			)
5011
		);
5012
	}
5013
5014
	/* Client API */
5015
5016
	/**
5017
	 * Returns the requested Jetpack API URL
5018
	 *
5019
	 * @deprecated since 7.7
5020
	 * @return string
5021
	 */
5022
	public static function api_url( $relative_url ) {
5023
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5024
		$connection = self::connection();
5025
		return $connection->api_url( $relative_url );
5026
	}
5027
5028
	/**
5029
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5030
	 *
5031
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5032
	 */
5033
	public static function fix_url_for_bad_hosts( $url ) {
5034
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5035
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5036
	}
5037
5038
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5039
		// Default to a blog token.
5040
		$token_type = 'blog';
5041
5042
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5043
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5044
			if ( ! empty( $_GET['onboarding'] ) ) {
5045
				$jpo = $_GET;
5046
			} else {
5047
				$jpo = json_decode( $request_data, true );
5048
			}
5049
5050
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5051
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5052
5053
			if (
5054
				isset( $jpo_user )
5055
				&& isset( $jpo_token )
5056
				&& is_email( $jpo_user )
5057
				&& ctype_alnum( $jpo_token )
5058
				&& isset( $_GET['rest_route'] )
5059
				&& self::validate_onboarding_token_action(
5060
					$jpo_token,
5061
					$_GET['rest_route']
5062
				)
5063
			) {
5064
				$jp_user = get_user_by( 'email', $jpo_user );
5065
				if ( is_a( $jp_user, 'WP_User' ) ) {
5066
					wp_set_current_user( $jp_user->ID );
5067
					$user_can = is_multisite()
5068
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5069
						: current_user_can( 'manage_options' );
5070
					if ( $user_can ) {
5071
						$token_type              = 'user';
5072
						$token->external_user_id = $jp_user->ID;
5073
					}
5074
				}
5075
			}
5076
5077
			$token_data['type']    = $token_type;
5078
			$token_data['user_id'] = $token->external_user_id;
5079
		}
5080
5081
		return $token_data;
5082
	}
5083
5084
	/**
5085
	 * Create a random secret for validating onboarding payload
5086
	 *
5087
	 * @return string Secret token
5088
	 */
5089
	public static function create_onboarding_token() {
5090
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5091
			$token = wp_generate_password( 32, false );
5092
			Jetpack_Options::update_option( 'onboarding', $token );
5093
		}
5094
5095
		return $token;
5096
	}
5097
5098
	/**
5099
	 * Remove the onboarding token
5100
	 *
5101
	 * @return bool True on success, false on failure
5102
	 */
5103
	public static function invalidate_onboarding_token() {
5104
		return Jetpack_Options::delete_option( 'onboarding' );
5105
	}
5106
5107
	/**
5108
	 * Validate an onboarding token for a specific action
5109
	 *
5110
	 * @return boolean True if token/action pair is accepted, false if not
5111
	 */
5112
	public static function validate_onboarding_token_action( $token, $action ) {
5113
		// Compare tokens, bail if tokens do not match
5114
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5115
			return false;
5116
		}
5117
5118
		// List of valid actions we can take
5119
		$valid_actions = array(
5120
			'/jetpack/v4/settings',
5121
		);
5122
5123
		// Only allow valid actions.
5124
		if ( ! in_array( $action, $valid_actions ) ) {
5125
			return false;
5126
		}
5127
5128
		return true;
5129
	}
5130
5131
	/**
5132
	 * Checks to see if the URL is using SSL to connect with Jetpack
5133
	 *
5134
	 * @since 2.3.3
5135
	 * @return boolean
5136
	 */
5137
	public static function permit_ssl( $force_recheck = false ) {
5138
		// Do some fancy tests to see if ssl is being supported
5139
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5140
			$message = '';
5141
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5142
				$ssl = 0;
5143
			} else {
5144
				switch ( JETPACK_CLIENT__HTTPS ) {
5145
					case 'NEVER':
5146
						$ssl     = 0;
5147
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5148
						break;
5149
					case 'ALWAYS':
5150
					case 'AUTO':
5151
					default:
5152
						$ssl = 1;
5153
						break;
5154
				}
5155
5156
				// If it's not 'NEVER', test to see
5157
				if ( $ssl ) {
5158
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5159
						$ssl     = 0;
5160
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5161
					} else {
5162
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5163
						if ( is_wp_error( $response ) ) {
5164
							$ssl     = 0;
5165
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5166
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5167
							$ssl     = 0;
5168
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5169
						}
5170
					}
5171
				}
5172
			}
5173
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5174
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5175
		}
5176
5177
		return (bool) $ssl;
5178
	}
5179
5180
	/*
5181
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5182
	 */
5183
	public function alert_auto_ssl_fail() {
5184
		if ( ! current_user_can( 'manage_options' ) ) {
5185
			return;
5186
		}
5187
5188
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5189
		?>
5190
5191
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5192
			<div class="jp-banner__content">
5193
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5194
				<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>
5195
				<p>
5196
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5197
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5198
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5199
				</p>
5200
				<p>
5201
					<?php
5202
					printf(
5203
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5204
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5205
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5206
					);
5207
					?>
5208
				</p>
5209
			</div>
5210
		</div>
5211
		<style>
5212
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5213
		</style>
5214
		<script type="text/javascript">
5215
			jQuery( document ).ready( function( $ ) {
5216
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5217
					var $this = $( this );
5218
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5219
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5220
					e.preventDefault();
5221
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5222
					$.post( ajaxurl, data )
5223
					  .done( function( response ) {
5224
						  if ( response.enabled ) {
5225
							  $( '#jetpack-ssl-warning' ).hide();
5226
						  } else {
5227
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5228
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5229
						  }
5230
					  }.bind( $this ) );
5231
				} );
5232
			} );
5233
		</script>
5234
5235
		<?php
5236
	}
5237
5238
	/**
5239
	 * Returns the Jetpack XML-RPC API
5240
	 *
5241
	 * @deprecated 8.0 Use Connection_Manager instead.
5242
	 * @return string
5243
	 */
5244
	public static function xmlrpc_api_url() {
5245
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5246
		return self::connection()->xmlrpc_api_url();
5247
	}
5248
5249
	/**
5250
	 * Returns the connection manager object.
5251
	 *
5252
	 * @return Automattic\Jetpack\Connection\Manager
5253
	 */
5254
	public static function connection() {
5255
		$jetpack = static::init();
5256
5257
		// If the connection manager hasn't been instantiated, do that now.
5258
		if ( ! $jetpack->connection_manager ) {
5259
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5260
		}
5261
5262
		return $jetpack->connection_manager;
5263
	}
5264
5265
	/**
5266
	 * Creates two secret tokens and the end of life timestamp for them.
5267
	 *
5268
	 * Note these tokens are unique per call, NOT static per site for connecting.
5269
	 *
5270
	 * @since 2.6
5271
	 * @param String  $action  The action name.
5272
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
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...
5273
	 * @param Integer $exp     Expiration time in seconds.
5274
	 * @return array
5275
	 */
5276
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5277
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5278
	}
5279
5280
	public static function get_secrets( $action, $user_id ) {
5281
		$secrets = self::connection()->get_secrets( $action, $user_id );
5282
5283
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5284
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5285
		}
5286
5287
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5288
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5289
		}
5290
5291
		return $secrets;
5292
	}
5293
5294
	/**
5295
	 * @deprecated 7.5 Use Connection_Manager instead.
5296
	 *
5297
	 * @param $action
5298
	 * @param $user_id
5299
	 */
5300
	public static function delete_secrets( $action, $user_id ) {
5301
		return self::connection()->delete_secrets( $action, $user_id );
5302
	}
5303
5304
	/**
5305
	 * Builds the timeout limit for queries talking with the wpcom servers.
5306
	 *
5307
	 * Based on local php max_execution_time in php.ini
5308
	 *
5309
	 * @since 2.6
5310
	 * @return int
5311
	 * @deprecated
5312
	 **/
5313
	public function get_remote_query_timeout_limit() {
5314
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5315
		return self::get_max_execution_time();
5316
	}
5317
5318
	/**
5319
	 * Builds the timeout limit for queries talking with the wpcom servers.
5320
	 *
5321
	 * Based on local php max_execution_time in php.ini
5322
	 *
5323
	 * @since 5.4
5324
	 * @return int
5325
	 **/
5326
	public static function get_max_execution_time() {
5327
		$timeout = (int) ini_get( 'max_execution_time' );
5328
5329
		// Ensure exec time set in php.ini
5330
		if ( ! $timeout ) {
5331
			$timeout = 30;
5332
		}
5333
		return $timeout;
5334
	}
5335
5336
	/**
5337
	 * Sets a minimum request timeout, and returns the current timeout
5338
	 *
5339
	 * @since 5.4
5340
	 **/
5341 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5342
		$timeout = self::get_max_execution_time();
5343
		if ( $timeout < $min_timeout ) {
5344
			$timeout = $min_timeout;
5345
			set_time_limit( $timeout );
5346
		}
5347
		return $timeout;
5348
	}
5349
5350
	/**
5351
	 * Takes the response from the Jetpack register new site endpoint and
5352
	 * verifies it worked properly.
5353
	 *
5354
	 * @since 2.6
5355
	 * @deprecated since 7.7.0
5356
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5357
	 **/
5358
	public function validate_remote_register_response() {
5359
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5360
	}
5361
5362
	/**
5363
	 * @return bool|WP_Error
5364
	 */
5365
	public static function register() {
5366
		$tracking = new Tracking();
5367
		$tracking->record_user_event( 'jpc_register_begin' );
5368
5369
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5370
5371
		$connection   = self::connection();
5372
		$registration = $connection->register();
5373
5374
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5375
5376
		if ( ! $registration || is_wp_error( $registration ) ) {
5377
			return $registration;
5378
		}
5379
5380
		return true;
5381
	}
5382
5383
	/**
5384
	 * Filters the registration request body to include tracking properties.
5385
	 *
5386
	 * @param array $properties
5387
	 * @return array amended properties.
5388
	 */
5389 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5390
		$tracking        = new Tracking();
5391
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5392
5393
		return array_merge(
5394
			$properties,
5395
			array(
5396
				'_ui' => $tracks_identity['_ui'],
5397
				'_ut' => $tracks_identity['_ut'],
5398
			)
5399
		);
5400
	}
5401
5402
	/**
5403
	 * Filters the token request body to include tracking properties.
5404
	 *
5405
	 * @param array $properties
5406
	 * @return array amended properties.
5407
	 */
5408 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5409
		$tracking        = new Tracking();
5410
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5411
5412
		return array_merge(
5413
			$properties,
5414
			array(
5415
				'_ui' => $tracks_identity['_ui'],
5416
				'_ut' => $tracks_identity['_ut'],
5417
			)
5418
		);
5419
	}
5420
5421
	/**
5422
	 * If the db version is showing something other that what we've got now, bump it to current.
5423
	 *
5424
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5425
	 */
5426
	public static function maybe_set_version_option() {
5427
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5428
		if ( JETPACK__VERSION != $version ) {
5429
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5430
5431
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5432
				/** This action is documented in class.jetpack.php */
5433
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5434
			}
5435
5436
			return true;
5437
		}
5438
		return false;
5439
	}
5440
5441
	/* Client Server API */
5442
5443
	/**
5444
	 * Loads the Jetpack XML-RPC client.
5445
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5446
	 *
5447
	 * @deprecated since 7.7.0
5448
	 */
5449
	public static function load_xml_rpc_client() {
5450
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5451
	}
5452
5453
	/**
5454
	 * Resets the saved authentication state in between testing requests.
5455
	 */
5456
	public function reset_saved_auth_state() {
5457
		$this->rest_authentication_status = null;
5458
5459
		if ( ! $this->connection_manager ) {
5460
			$this->connection_manager = new Connection_Manager();
5461
		}
5462
5463
		$this->connection_manager->reset_saved_auth_state();
5464
	}
5465
5466
	/**
5467
	 * Verifies the signature of the current request.
5468
	 *
5469
	 * @deprecated since 7.7.0
5470
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5471
	 *
5472
	 * @return false|array
5473
	 */
5474
	public function verify_xml_rpc_signature() {
5475
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5476
		return self::connection()->verify_xml_rpc_signature();
5477
	}
5478
5479
	/**
5480
	 * Verifies the signature of the current request.
5481
	 *
5482
	 * This function has side effects and should not be used. Instead,
5483
	 * use the memoized version `->verify_xml_rpc_signature()`.
5484
	 *
5485
	 * @deprecated since 7.7.0
5486
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5487
	 * @internal
5488
	 */
5489
	private function internal_verify_xml_rpc_signature() {
5490
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5491
	}
5492
5493
	/**
5494
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5495
	 *
5496
	 * @deprecated since 7.7.0
5497
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5498
	 *
5499
	 * @param \WP_User|mixed $user     User object if authenticated.
5500
	 * @param string         $username Username.
5501
	 * @param string         $password Password string.
5502
	 * @return \WP_User|mixed Authenticated user or error.
5503
	 */
5504 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5505
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5506
5507
		if ( ! $this->connection_manager ) {
5508
			$this->connection_manager = new Connection_Manager();
5509
		}
5510
5511
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5512
	}
5513
5514
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5515
	// Uses the existing XMLRPC request signing implementation.
5516
	function wp_rest_authenticate( $user ) {
5517
		if ( ! empty( $user ) ) {
5518
			// Another authentication method is in effect.
5519
			return $user;
5520
		}
5521
5522
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5523
			// Nothing to do for this authentication method.
5524
			return null;
5525
		}
5526
5527
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5528
			// Nothing to do for this authentication method.
5529
			return null;
5530
		}
5531
5532
		// Only support specific request parameters that have been tested and
5533
		// are known to work with signature verification.  A different method
5534
		// can be passed to the WP REST API via the '?_method=' parameter if
5535
		// needed.
5536
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5537
			$this->rest_authentication_status = new WP_Error(
5538
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5539
				__( 'This request method is not supported.', 'jetpack' ),
5540
				array( 'status' => 400 )
5541
			);
5542
			return null;
5543
		}
5544
		if ( 'POST' !== $_SERVER['REQUEST_METHOD'] && ! empty( file_get_contents( 'php://input' ) ) ) {
5545
			$this->rest_authentication_status = new WP_Error(
5546
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5547
				__( 'This request method does not support body parameters.', 'jetpack' ),
5548
				array( 'status' => 400 )
5549
			);
5550
			return null;
5551
		}
5552
5553
		if ( ! $this->connection_manager ) {
5554
			$this->connection_manager = new Connection_Manager();
5555
		}
5556
5557
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5558
5559
		if (
5560
			$verified &&
5561
			isset( $verified['type'] ) &&
5562
			'user' === $verified['type'] &&
5563
			! empty( $verified['user_id'] )
5564
		) {
5565
			// Authentication successful.
5566
			$this->rest_authentication_status = true;
5567
			return $verified['user_id'];
5568
		}
5569
5570
		// Something else went wrong.  Probably a signature error.
5571
		$this->rest_authentication_status = new WP_Error(
5572
			'rest_invalid_signature',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5573
			__( 'The request is not signed correctly.', 'jetpack' ),
5574
			array( 'status' => 400 )
5575
		);
5576
		return null;
5577
	}
5578
5579
	/**
5580
	 * Report authentication status to the WP REST API.
5581
	 *
5582
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5583
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5584
	 */
5585
	public function wp_rest_authentication_errors( $value ) {
5586
		if ( $value !== null ) {
5587
			return $value;
5588
		}
5589
		return $this->rest_authentication_status;
5590
	}
5591
5592
	/**
5593
	 * Add our nonce to this request.
5594
	 *
5595
	 * @deprecated since 7.7.0
5596
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5597
	 *
5598
	 * @param int    $timestamp Timestamp of the request.
5599
	 * @param string $nonce     Nonce string.
5600
	 */
5601 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5602
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5603
5604
		if ( ! $this->connection_manager ) {
5605
			$this->connection_manager = new Connection_Manager();
5606
		}
5607
5608
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5609
	}
5610
5611
	/**
5612
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5613
	 * Capture it here so we can verify the signature later.
5614
	 *
5615
	 * @deprecated since 7.7.0
5616
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5617
	 *
5618
	 * @param array $methods XMLRPC methods.
5619
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5620
	 */
5621 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5622
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5623
5624
		if ( ! $this->connection_manager ) {
5625
			$this->connection_manager = new Connection_Manager();
5626
		}
5627
5628
		return $this->connection_manager->xmlrpc_methods( $methods );
5629
	}
5630
5631
	/**
5632
	 * Register additional public XMLRPC methods.
5633
	 *
5634
	 * @deprecated since 7.7.0
5635
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5636
	 *
5637
	 * @param array $methods Public XMLRPC methods.
5638
	 * @return array Public XMLRPC methods, with the getOptions one.
5639
	 */
5640 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5641
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5642
5643
		if ( ! $this->connection_manager ) {
5644
			$this->connection_manager = new Connection_Manager();
5645
		}
5646
5647
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5648
	}
5649
5650
	/**
5651
	 * Handles a getOptions XMLRPC method call.
5652
	 *
5653
	 * @deprecated since 7.7.0
5654
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5655
	 *
5656
	 * @param array $args method call arguments.
5657
	 * @return array an amended XMLRPC server options array.
5658
	 */
5659 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5660
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5661
5662
		if ( ! $this->connection_manager ) {
5663
			$this->connection_manager = new Connection_Manager();
5664
		}
5665
5666
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
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...
5667
	}
5668
5669
	/**
5670
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5671
	 *
5672
	 * @deprecated since 7.7.0
5673
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5674
	 *
5675
	 * @param array $options Standard Core options.
5676
	 * @return array Amended options.
5677
	 */
5678 View Code Duplication
	public function xmlrpc_options( $options ) {
5679
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5680
5681
		if ( ! $this->connection_manager ) {
5682
			$this->connection_manager = new Connection_Manager();
5683
		}
5684
5685
		return $this->connection_manager->xmlrpc_options( $options );
5686
	}
5687
5688
	/**
5689
	 * Cleans nonces that were saved when calling ::add_nonce.
5690
	 *
5691
	 * @deprecated since 7.7.0
5692
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5693
	 *
5694
	 * @param bool $all whether to clean even non-expired nonces.
5695
	 */
5696
	public static function clean_nonces( $all = false ) {
5697
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5698
		return self::connection()->clean_nonces( $all );
5699
	}
5700
5701
	/**
5702
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5703
	 * SET: state( $key, $value );
5704
	 * GET: $value = state( $key );
5705
	 *
5706
	 * @param string $key
0 ignored issues
show
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

Loading history...
5708
	 * @param bool   $restate private
5709
	 */
5710
	public static function state( $key = null, $value = null, $restate = false ) {
5711
		static $state = array();
5712
		static $path, $domain;
5713
		if ( ! isset( $path ) ) {
5714
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5715
			$admin_url = self::admin_url();
5716
			$bits      = wp_parse_url( $admin_url );
5717
5718
			if ( is_array( $bits ) ) {
5719
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5720
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5721
			} else {
5722
				$path = $domain = null;
5723
			}
5724
		}
5725
5726
		// Extract state from cookies and delete cookies
5727
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5728
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5729
			unset( $_COOKIE['jetpackState'] );
5730
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
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...
5731
				if ( strlen( $v ) ) {
5732
					$state[ $k ] = $v;
5733
				}
5734
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5735
			}
5736
		}
5737
5738
		if ( $restate ) {
5739
			foreach ( $state as $k => $v ) {
5740
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5741
			}
5742
			return;
5743
		}
5744
5745
		// Get a state variable.
5746
		if ( isset( $key ) && ! isset( $value ) ) {
5747
			if ( array_key_exists( $key, $state ) ) {
5748
				return $state[ $key ];
5749
			}
5750
			return null;
5751
		}
5752
5753
		// Set a state variable.
5754
		if ( isset( $key ) && isset( $value ) ) {
5755
			if ( is_array( $value ) && isset( $value[0] ) ) {
5756
				$value = $value[0];
5757
			}
5758
			$state[ $key ] = $value;
5759
			if ( ! headers_sent() ) {
5760
				if ( self::should_set_cookie( $key ) ) {
5761
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5762
				}
5763
			}
5764
		}
5765
	}
5766
5767
	public static function restate() {
5768
		self::state( null, null, true );
5769
	}
5770
5771
	/**
5772
	 * Determines whether the jetpackState[$key] value should be added to the
5773
	 * cookie.
5774
	 *
5775
	 * @param string $key The state key.
5776
	 *
5777
	 * @return boolean Whether the value should be added to the cookie.
5778
	 */
5779
	public static function should_set_cookie( $key ) {
5780
		global $current_screen;
5781
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5782
5783
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5784
			return false;
5785
		}
5786
5787
		return true;
5788
	}
5789
5790
	public static function check_privacy( $file ) {
5791
		static $is_site_publicly_accessible = null;
5792
5793
		if ( is_null( $is_site_publicly_accessible ) ) {
5794
			$is_site_publicly_accessible = false;
5795
5796
			$rpc = new Jetpack_IXR_Client();
5797
5798
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5799
			if ( $success ) {
5800
				$response = $rpc->getResponse();
5801
				if ( $response ) {
5802
					$is_site_publicly_accessible = true;
5803
				}
5804
			}
5805
5806
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5807
		}
5808
5809
		if ( $is_site_publicly_accessible ) {
5810
			return;
5811
		}
5812
5813
		$module_slug = self::get_module_slug( $file );
5814
5815
		$privacy_checks = self::state( 'privacy_checks' );
5816
		if ( ! $privacy_checks ) {
5817
			$privacy_checks = $module_slug;
5818
		} else {
5819
			$privacy_checks .= ",$module_slug";
5820
		}
5821
5822
		self::state( 'privacy_checks', $privacy_checks );
5823
	}
5824
5825
	/**
5826
	 * Helper method for multicall XMLRPC.
5827
	 *
5828
	 * @param ...$args Args for the async_call.
5829
	 */
5830
	public static function xmlrpc_async_call( ...$args ) {
5831
		global $blog_id;
5832
		static $clients = array();
5833
5834
		$client_blog_id = is_multisite() ? $blog_id : 0;
5835
5836
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5837
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5838
			if ( function_exists( 'ignore_user_abort' ) ) {
5839
				ignore_user_abort( true );
5840
			}
5841
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5842
		}
5843
5844
		if ( ! empty( $args[0] ) ) {
5845
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5846
		} elseif ( is_multisite() ) {
5847
			foreach ( $clients as $client_blog_id => $client ) {
5848
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5849
					continue;
5850
				}
5851
5852
				$switch_success = switch_to_blog( $client_blog_id, true );
5853
				if ( ! $switch_success ) {
5854
					continue;
5855
				}
5856
5857
				flush();
5858
				$client->query();
5859
5860
				restore_current_blog();
5861
			}
5862
		} else {
5863
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5864
				flush();
5865
				$clients[0]->query();
5866
			}
5867
		}
5868
	}
5869
5870
	public static function staticize_subdomain( $url ) {
5871
5872
		// Extract hostname from URL
5873
		$host = wp_parse_url( $url, PHP_URL_HOST );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5874
5875
		// Explode hostname on '.'
5876
		$exploded_host = explode( '.', $host );
5877
5878
		// Retrieve the name and TLD
5879
		if ( count( $exploded_host ) > 1 ) {
5880
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5881
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5882
			// Rebuild domain excluding subdomains
5883
			$domain = $name . '.' . $tld;
5884
		} else {
5885
			$domain = $host;
5886
		}
5887
		// Array of Automattic domains.
5888
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5889
5890
		// Return $url if not an Automattic domain.
5891
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5892
			return $url;
5893
		}
5894
5895
		if ( is_ssl() ) {
5896
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5897
		}
5898
5899
		srand( crc32( basename( $url ) ) );
5900
		$static_counter = rand( 0, 2 );
5901
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5902
5903
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5904
	}
5905
5906
	/* JSON API Authorization */
5907
5908
	/**
5909
	 * Handles the login action for Authorizing the JSON API
5910
	 */
5911
	function login_form_json_api_authorization() {
5912
		$this->verify_json_api_authorization_request();
5913
5914
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5915
5916
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5917
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5918
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5919
	}
5920
5921
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5922
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5923
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5924
			return $url;
5925
		}
5926
5927
		$parsed_url = wp_parse_url( $url );
5928
		$url        = strtok( $url, '?' );
5929
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5930
		if ( ! empty( $parsed_url['query'] ) ) {
5931
			$url .= "&{$parsed_url['query']}";
5932
		}
5933
5934
		return $url;
5935
	}
5936
5937
	// Make sure the POSTed request is handled by the same action
5938
	function preserve_action_in_login_form_for_json_api_authorization() {
5939
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5940
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5941
	}
5942
5943
	// If someone logs in to approve API access, store the Access Code in usermeta
5944
	function store_json_api_authorization_token( $user_login, $user ) {
5945
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5946
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5947
		$token = wp_generate_password( 32, false );
5948
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5949
	}
5950
5951
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5952
	function allow_wpcom_public_api_domain( $domains ) {
5953
		$domains[] = 'public-api.wordpress.com';
5954
		return $domains;
5955
	}
5956
5957
	static function is_redirect_encoded( $redirect_url ) {
5958
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5959
	}
5960
5961
	// Add all wordpress.com environments to the safe redirect allowed list.
5962
	function allow_wpcom_environments( $domains ) {
5963
		$domains[] = 'wordpress.com';
5964
		$domains[] = 'wpcalypso.wordpress.com';
5965
		$domains[] = 'horizon.wordpress.com';
5966
		$domains[] = 'calypso.localhost';
5967
		return $domains;
5968
	}
5969
5970
	// Add the Access Code details to the public-api.wordpress.com redirect
5971
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5972
		return add_query_arg(
5973
			urlencode_deep(
5974
				array(
5975
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5976
					'jetpack-user-id' => (int) $user->ID,
5977
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5978
				)
5979
			),
5980
			$redirect_to
5981
		);
5982
	}
5983
5984
5985
	/**
5986
	 * Verifies the request by checking the signature
5987
	 *
5988
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5989
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5990
	 *
5991
	 * @param null|array $environment
5992
	 */
5993
	function verify_json_api_authorization_request( $environment = null ) {
5994
		$environment = is_null( $environment )
5995
			? $_REQUEST
5996
			: $environment;
5997
5998
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5999
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
6000
		if ( ! $token || empty( $token->secret ) ) {
6001
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6002
		}
6003
6004
		$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' );
6005
6006
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6007
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6008
			/**
6009
			 * Jetpack authorisation request Error.
6010
			 *
6011
			 * @since 7.5.0
6012
			 */
6013
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6014
			$die_error = sprintf(
6015
				/* translators: %s is a URL */
6016
				__( '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' ),
6017
				Redirect::get_url( 'jetpack-support-double-encoding' )
6018
			);
6019
		}
6020
6021
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6022
6023
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6024
			$signature = $jetpack_signature->sign_request(
6025
				$environment['token'],
6026
				$environment['timestamp'],
6027
				$environment['nonce'],
6028
				'',
6029
				'GET',
6030
				$environment['jetpack_json_api_original_query'],
6031
				null,
6032
				true
6033
			);
6034
		} else {
6035
			$signature = $jetpack_signature->sign_current_request(
6036
				array(
6037
					'body'   => null,
6038
					'method' => 'GET',
6039
				)
6040
			);
6041
		}
6042
6043
		if ( ! $signature ) {
6044
			wp_die( $die_error );
6045
		} elseif ( is_wp_error( $signature ) ) {
6046
			wp_die( $die_error );
6047
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6048
			if ( is_ssl() ) {
6049
				// 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
6050
				$signature = $jetpack_signature->sign_current_request(
6051
					array(
6052
						'scheme' => 'http',
6053
						'body'   => null,
6054
						'method' => 'GET',
6055
					)
6056
				);
6057
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6058
					wp_die( $die_error );
6059
				}
6060
			} else {
6061
				wp_die( $die_error );
6062
			}
6063
		}
6064
6065
		$timestamp = (int) $environment['timestamp'];
6066
		$nonce     = stripslashes( (string) $environment['nonce'] );
6067
6068
		if ( ! $this->connection_manager ) {
6069
			$this->connection_manager = new Connection_Manager();
6070
		}
6071
6072
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6073
			// De-nonce the nonce, at least for 5 minutes.
6074
			// 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)
6075
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6076
			if ( $old_nonce_time < time() - 300 ) {
6077
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6078
			}
6079
		}
6080
6081
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6082
		$data_filters = array(
6083
			'state'        => 'opaque',
6084
			'client_id'    => 'int',
6085
			'client_title' => 'string',
6086
			'client_image' => 'url',
6087
		);
6088
6089
		foreach ( $data_filters as $key => $sanitation ) {
6090
			if ( ! isset( $data->$key ) ) {
6091
				wp_die( $die_error );
6092
			}
6093
6094
			switch ( $sanitation ) {
6095
				case 'int':
6096
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6097
					break;
6098
				case 'opaque':
6099
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6100
					break;
6101
				case 'string':
6102
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6103
					break;
6104
				case 'url':
6105
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6106
					break;
6107
			}
6108
		}
6109
6110
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6111
			wp_die( $die_error );
6112
		}
6113
	}
6114
6115
	function login_message_json_api_authorization( $message ) {
6116
		return '<p class="message">' . sprintf(
6117
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6118
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6119
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6120
	}
6121
6122
	/**
6123
	 * Get $content_width, but with a <s>twist</s> filter.
6124
	 */
6125
	public static function get_content_width() {
6126
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6127
			? $GLOBALS['content_width']
6128
			: false;
6129
		/**
6130
		 * Filter the Content Width value.
6131
		 *
6132
		 * @since 2.2.3
6133
		 *
6134
		 * @param string $content_width Content Width value.
6135
		 */
6136
		return apply_filters( 'jetpack_content_width', $content_width );
6137
	}
6138
6139
	/**
6140
	 * Pings the WordPress.com Mirror Site for the specified options.
6141
	 *
6142
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6143
	 *
6144
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6145
	 */
6146
	public function get_cloud_site_options( $option_names ) {
6147
		$option_names = array_filter( (array) $option_names, 'is_string' );
6148
6149
		$xml = new Jetpack_IXR_Client();
6150
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6151
		if ( $xml->isError() ) {
6152
			return array(
6153
				'error_code' => $xml->getErrorCode(),
6154
				'error_msg'  => $xml->getErrorMessage(),
6155
			);
6156
		}
6157
		$cloud_site_options = $xml->getResponse();
6158
6159
		return $cloud_site_options;
6160
	}
6161
6162
	/**
6163
	 * Checks if the site is currently in an identity crisis.
6164
	 *
6165
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6166
	 */
6167
	public static function check_identity_crisis() {
6168
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6169
			return false;
6170
		}
6171
6172
		return Jetpack_Options::get_option( 'sync_error_idc' );
6173
	}
6174
6175
	/**
6176
	 * Checks whether the home and siteurl specifically are allowed.
6177
	 * Written so that we don't have re-check $key and $value params every time
6178
	 * we want to check if this site is allowed, for example in footer.php
6179
	 *
6180
	 * @since  3.8.0
6181
	 * @return bool True = already allowed False = not on the allowed list.
6182
	 */
6183
	public static function is_staging_site() {
6184
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6185
		return ( new Status() )->is_staging_site();
6186
	}
6187
6188
	/**
6189
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6190
	 *
6191
	 * @since 4.4.0
6192
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6193
	 *
6194
	 * @return bool
6195
	 */
6196
	public static function validate_sync_error_idc_option() {
6197
		$is_valid = false;
6198
6199
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6200
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6201
		if ( $sync_error && self::sync_idc_optin() ) {
6202
			$local_options = self::get_sync_error_idc_option();
6203
			// Ensure all values are set.
6204
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6205
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6206
					$is_valid = true;
6207
				}
6208
			}
6209
		}
6210
6211
		/**
6212
		 * Filters whether the sync_error_idc option is valid.
6213
		 *
6214
		 * @since 4.4.0
6215
		 *
6216
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6217
		 */
6218
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6219
6220
		if ( ! $is_valid && $sync_error ) {
6221
			// Since the option exists, and did not validate, delete it
6222
			Jetpack_Options::delete_option( 'sync_error_idc' );
6223
		}
6224
6225
		return $is_valid;
6226
	}
6227
6228
	/**
6229
	 * Normalizes a url by doing three things:
6230
	 *  - Strips protocol
6231
	 *  - Strips www
6232
	 *  - Adds a trailing slash
6233
	 *
6234
	 * @since 4.4.0
6235
	 * @param string $url
6236
	 * @return WP_Error|string
6237
	 */
6238
	public static function normalize_url_protocol_agnostic( $url ) {
6239
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6240 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6241
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
6242
		}
6243
6244
		// Strip www and protocols
6245
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6246
		return $url;
6247
	}
6248
6249
	/**
6250
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6251
	 *
6252
	 * @since 4.4.0
6253
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6254
	 *
6255
	 * @param array $response
6256
	 * @return array Array of the local urls, wpcom urls, and error code
6257
	 */
6258
	public static function get_sync_error_idc_option( $response = array() ) {
6259
		// Since the local options will hit the database directly, store the values
6260
		// in a transient to allow for autoloading and caching on subsequent views.
6261
		$local_options = get_transient( 'jetpack_idc_local' );
6262
		if ( false === $local_options ) {
6263
			$local_options = array(
6264
				'home'    => Functions::home_url(),
6265
				'siteurl' => Functions::site_url(),
6266
			);
6267
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6268
		}
6269
6270
		$options = array_merge( $local_options, $response );
6271
6272
		$returned_values = array();
6273
		foreach ( $options as $key => $option ) {
6274
			if ( 'error_code' === $key ) {
6275
				$returned_values[ $key ] = $option;
6276
				continue;
6277
			}
6278
6279
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6280
				continue;
6281
			}
6282
6283
			$returned_values[ $key ] = $normalized_url;
6284
		}
6285
6286
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6287
6288
		return $returned_values;
6289
	}
6290
6291
	/**
6292
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6293
	 * If set to true, the site will be put into staging mode.
6294
	 *
6295
	 * @since 4.3.2
6296
	 * @return bool
6297
	 */
6298
	public static function sync_idc_optin() {
6299
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6300
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6301
		} else {
6302
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6303
		}
6304
6305
		/**
6306
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6307
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6308
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6309
		 *
6310
		 * @since 4.3.2
6311
		 *
6312
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6313
		 */
6314
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6315
	}
6316
6317
	/**
6318
	 * Maybe Use a .min.css stylesheet, maybe not.
6319
	 *
6320
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6321
	 */
6322
	public static function maybe_min_asset( $url, $path, $plugin ) {
6323
		// Short out on things trying to find actual paths.
6324
		if ( ! $path || empty( $plugin ) ) {
6325
			return $url;
6326
		}
6327
6328
		$path = ltrim( $path, '/' );
6329
6330
		// Strip out the abspath.
6331
		$base = dirname( plugin_basename( $plugin ) );
6332
6333
		// Short out on non-Jetpack assets.
6334
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6335
			return $url;
6336
		}
6337
6338
		// File name parsing.
6339
		$file              = "{$base}/{$path}";
6340
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6341
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6342
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6343
		$extension         = array_shift( $file_name_parts_r );
6344
6345
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6346
			// Already pointing at the minified version.
6347
			if ( 'min' === $file_name_parts_r[0] ) {
6348
				return $url;
6349
			}
6350
6351
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6352
			if ( file_exists( $min_full_path ) ) {
6353
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6354
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6355
				if ( 'css' === $extension ) {
6356
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6357
					self::$min_assets[ $key ] = $path;
6358
				}
6359
			}
6360
		}
6361
6362
		return $url;
6363
	}
6364
6365
	/**
6366
	 * If the asset is minified, let's flag .min as the suffix.
6367
	 *
6368
	 * Attached to `style_loader_src` filter.
6369
	 *
6370
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
6915
	 * @return mixed
6916
	 */
6917
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6918
		if ( ! is_array( $sorted ) ) {
6919
			return $sorted;
6920
		}
6921
6922
		foreach ( $sorted as $box_context => $ids ) {
6923
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6924
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6925
				continue;
6926
			}
6927
6928
			$ids_array = explode( ',', $ids );
6929
			$key       = array_search( 'dashboard_stats', $ids_array );
6930
6931
			if ( false !== $key ) {
6932
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6933
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6934
				$sorted[ $box_context ] = implode( ',', $ids_array );
6935
				// We've found it, stop searching, and just return.
6936
				break;
6937
			}
6938
		}
6939
6940
		return $sorted;
6941
	}
6942
6943
	public static function dashboard_widget() {
6944
		/**
6945
		 * Fires when the dashboard is loaded.
6946
		 *
6947
		 * @since 3.4.0
6948
		 */
6949
		do_action( 'jetpack_dashboard_widget' );
6950
	}
6951
6952
	public static function dashboard_widget_footer() {
6953
		?>
6954
		<footer>
6955
6956
		<div class="protect">
6957
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6958
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6959
				<p class="blocked-count">
6960
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6961
				</p>
6962
				<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>
6963
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
6964
				<a href="
6965
				<?php
6966
				echo esc_url(
6967
					wp_nonce_url(
6968
						self::admin_url(
6969
							array(
6970
								'action' => 'activate',
6971
								'module' => 'protect',
6972
							)
6973
						),
6974
						'jetpack_activate-protect'
6975
					)
6976
				);
6977
				?>
6978
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6979
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6980
				</a>
6981
			<?php else : ?>
6982
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6983
			<?php endif; ?>
6984
		</div>
6985
6986
		<div class="akismet">
6987
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6988
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6989
				<p class="blocked-count">
6990
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6991
				</p>
6992
				<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>
6993
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6994
				<a href="
6995
				<?php
6996
				echo esc_url(
6997
					wp_nonce_url(
6998
						add_query_arg(
6999
							array(
7000
								'action' => 'activate',
7001
								'plugin' => 'akismet/akismet.php',
7002
							),
7003
							admin_url( 'plugins.php' )
7004
						),
7005
						'activate-plugin_akismet/akismet.php'
7006
					)
7007
				);
7008
				?>
7009
							" class="button button-jetpack">
7010
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7011
				</a>
7012
			<?php else : ?>
7013
				<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>
7014
			<?php endif; ?>
7015
		</div>
7016
7017
		</footer>
7018
		<?php
7019
	}
7020
7021
	/*
7022
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7023
	 */
7024
	function jetpack_icon_user_connected( $columns ) {
7025
		$columns['user_jetpack'] = '';
7026
		return $columns;
7027
	}
7028
7029
	/*
7030
	 * Show Jetpack icon if the user is linked.
7031
	 */
7032
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7033
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7034
			$jetpack_logo = new Jetpack_Logo();
7035
			$emblem_html  = sprintf(
7036
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7037
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7038
				$jetpack_logo->get_jp_emblem()
7039
			);
7040
			return $emblem_html;
7041
		}
7042
7043
		return $val;
7044
	}
7045
7046
	/*
7047
	 * Style the Jetpack user column
7048
	 */
7049
	function jetpack_user_col_style() {
7050
		global $current_screen;
7051
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7052
			?>
7053
			<style>
7054
				.fixed .column-user_jetpack {
7055
					width: 21px;
7056
				}
7057
				.jp-emblem-user-admin svg {
7058
					width: 20px;
7059
					height: 20px;
7060
				}
7061
				.jp-emblem-user-admin path {
7062
					fill: #00BE28;
7063
				}
7064
			</style>
7065
			<?php
7066
		}
7067
	}
7068
7069
	/**
7070
	 * Checks if Akismet is active and working.
7071
	 *
7072
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7073
	 * that implied usage of methods present since more recent version.
7074
	 * See https://github.com/Automattic/jetpack/pull/9585
7075
	 *
7076
	 * @since  5.1.0
7077
	 *
7078
	 * @return bool True = Akismet available. False = Aksimet not available.
7079
	 */
7080
	public static function is_akismet_active() {
7081
		static $status = null;
7082
7083
		if ( ! is_null( $status ) ) {
7084
			return $status;
7085
		}
7086
7087
		// Check if a modern version of Akismet is active.
7088
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7089
			$status = false;
7090
			return $status;
7091
		}
7092
7093
		// Make sure there is a key known to Akismet at all before verifying key.
7094
		$akismet_key = Akismet::get_api_key();
7095
		if ( ! $akismet_key ) {
7096
			$status = false;
7097
			return $status;
7098
		}
7099
7100
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7101
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7102
7103
		// 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.
7104
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7105
		// We cache the result of the Akismet key verification for ten minutes.
7106
		if ( ! $akismet_key_state || $recheck ) {
7107
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7108
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7109
		}
7110
7111
		$status = 'valid' === $akismet_key_state;
7112
7113
		return $status;
7114
	}
7115
7116
	/**
7117
	 * @deprecated
7118
	 *
7119
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7120
	 */
7121
	public static function is_function_in_backtrace() {
7122
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7123
	}
7124
7125
	/**
7126
	 * Given a minified path, and a non-minified path, will return
7127
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7128
	 *
7129
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7130
	 * root Jetpack directory.
7131
	 *
7132
	 * @since 5.6.0
7133
	 *
7134
	 * @param string $min_path
7135
	 * @param string $non_min_path
7136
	 * @return string The URL to the file
7137
	 */
7138
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7139
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7140
	}
7141
7142
	/**
7143
	 * Checks for whether Jetpack Backup is enabled.
7144
	 * Will return true if the state of Backup is anything except "unavailable".
7145
	 *
7146
	 * @return bool|int|mixed
7147
	 */
7148
	public static function is_rewind_enabled() {
7149
		if ( ! self::is_active() ) {
7150
			return false;
7151
		}
7152
7153
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7154
		if ( false === $rewind_enabled ) {
7155
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7156
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7157
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7158
				&& ! empty( $rewind_data['state'] )
7159
				&& 'active' === $rewind_data['state'] )
7160
				? 1
7161
				: 0;
7162
7163
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7164
		}
7165
		return $rewind_enabled;
7166
	}
7167
7168
	/**
7169
	 * Return Calypso environment value; used for developing Jetpack and pairing
7170
	 * it with different Calypso enrionments, such as localhost.
7171
	 *
7172
	 * @since 7.4.0
7173
	 *
7174
	 * @return string Calypso environment
7175
	 */
7176
	public static function get_calypso_env() {
7177
		if ( isset( $_GET['calypso_env'] ) ) {
7178
			return sanitize_key( $_GET['calypso_env'] );
7179
		}
7180
7181
		if ( getenv( 'CALYPSO_ENV' ) ) {
7182
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7183
		}
7184
7185
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7186
			return sanitize_key( CALYPSO_ENV );
7187
		}
7188
7189
		return '';
7190
	}
7191
7192
	/**
7193
	 * Returns the hostname with protocol for Calypso.
7194
	 * Used for developing Jetpack with Calypso.
7195
	 *
7196
	 * @since 8.4.0
7197
	 *
7198
	 * @return string Calypso host.
7199
	 */
7200
	public static function get_calypso_host() {
7201
		$calypso_env = self::get_calypso_env();
7202
		switch ( $calypso_env ) {
7203
			case 'development':
7204
				return 'http://calypso.localhost:3000/';
7205
			case 'wpcalypso':
7206
				return 'https://wpcalypso.wordpress.com/';
7207
			case 'horizon':
7208
				return 'https://horizon.wordpress.com/';
7209
			default:
7210
				return 'https://wordpress.com/';
7211
		}
7212
	}
7213
7214
	/**
7215
	 * Checks whether or not TOS has been agreed upon.
7216
	 * Will return true if a user has clicked to register, or is already connected.
7217
	 */
7218
	public static function jetpack_tos_agreed() {
7219
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7220
7221
		$terms_of_service = new Terms_Of_Service();
7222
		return $terms_of_service->has_agreed();
7223
7224
	}
7225
7226
	/**
7227
	 * Handles activating default modules as well general cleanup for the new connection.
7228
	 *
7229
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7230
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7231
	 * @param boolean $send_state_messages          Whether to send state messages.
7232
	 * @return void
7233
	 */
7234
	public static function handle_post_authorization_actions(
7235
		$activate_sso = false,
7236
		$redirect_on_activation_error = false,
7237
		$send_state_messages = true
7238
	) {
7239
		$other_modules = $activate_sso
7240
			? array( 'sso' )
7241
			: array();
7242
7243
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7244
			self::delete_active_modules();
7245
7246
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7247
		} else {
7248
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7249
		}
7250
7251
		// Since this is a fresh connection, be sure to clear out IDC options
7252
		Jetpack_IDC::clear_all_idc_options();
7253
7254
		if ( $send_state_messages ) {
7255
			self::state( 'message', 'authorized' );
7256
		}
7257
	}
7258
7259
	/**
7260
	 * Returns a boolean for whether backups UI should be displayed or not.
7261
	 *
7262
	 * @return bool Should backups UI be displayed?
7263
	 */
7264
	public static function show_backups_ui() {
7265
		/**
7266
		 * Whether UI for backups should be displayed.
7267
		 *
7268
		 * @since 6.5.0
7269
		 *
7270
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7271
		 */
7272
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7273
	}
7274
7275
	/*
7276
	 * Deprecated manage functions
7277
	 */
7278
	function prepare_manage_jetpack_notice() {
7279
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7280
	}
7281
	function manage_activate_screen() {
7282
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7283
	}
7284
	function admin_jetpack_manage_notice() {
7285
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7286
	}
7287
	function opt_out_jetpack_manage_url() {
7288
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7289
	}
7290
	function opt_in_jetpack_manage_url() {
7291
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7292
	}
7293
	function opt_in_jetpack_manage_notice() {
7294
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7295
	}
7296
	function can_display_jetpack_manage_notice() {
7297
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7298
	}
7299
7300
	/**
7301
	 * Clean leftoveruser meta.
7302
	 *
7303
	 * Delete Jetpack-related user meta when it is no longer needed.
7304
	 *
7305
	 * @since 7.3.0
7306
	 *
7307
	 * @param int $user_id User ID being updated.
7308
	 */
7309
	public static function user_meta_cleanup( $user_id ) {
7310
		$meta_keys = array(
7311
			// AtD removed from Jetpack 7.3
7312
			'AtD_options',
7313
			'AtD_check_when',
7314
			'AtD_guess_lang',
7315
			'AtD_ignored_phrases',
7316
		);
7317
7318
		foreach ( $meta_keys as $meta_key ) {
7319
			if ( get_user_meta( $user_id, $meta_key ) ) {
7320
				delete_user_meta( $user_id, $meta_key );
7321
			}
7322
		}
7323
	}
7324
7325
	/**
7326
	 * Checks if a Jetpack site is both active and not in offline mode.
7327
	 *
7328
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7329
	 *
7330
	 * @deprecated 8.8.0
7331
	 *
7332
	 * @return bool True if Jetpack is active and not in offline mode.
7333
	 */
7334
	public static function is_active_and_not_development_mode() {
7335
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7336
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7337
			return false;
7338
		}
7339
		return true;
7340
	}
7341
7342
	/**
7343
	 * Checks if a Jetpack site is both active and not in offline mode.
7344
	 *
7345
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7346
	 *
7347
	 * @since 8.8.0
7348
	 *
7349
	 * @return bool True if Jetpack is active and not in offline mode.
7350
	 */
7351
	public static function is_active_and_not_offline_mode() {
7352
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7353
			return false;
7354
		}
7355
		return true;
7356
	}
7357
7358
	/**
7359
	 * Returns the list of products that we have available for purchase.
7360
	 */
7361
	public static function get_products_for_purchase() {
7362
		$products = array();
7363
		if ( ! is_multisite() ) {
7364
			$products[] = array(
7365
				'key'               => 'backup',
7366
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7367
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7368
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7369
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7370
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7371
				'options'           => array(
7372
					array(
7373
						'type'        => 'daily',
7374
						'slug'        => 'jetpack-backup-daily',
7375
						'key'         => 'jetpack_backup_daily',
7376
						'name'        => __( 'Daily Backups', 'jetpack' ),
7377
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7378
					),
7379
					array(
7380
						'type'        => 'realtime',
7381
						'slug'        => 'jetpack-backup-realtime',
7382
						'key'         => 'jetpack_backup_realtime',
7383
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7384
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7385
					),
7386
				),
7387
				'default_option'    => 'realtime',
7388
				'show_promotion'    => true,
7389
				'discount_percent'  => 70,
7390
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7391
			);
7392
7393
			$products[] = array(
7394
				'key'               => 'scan',
7395
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7396
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7397
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7398
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7399
				'show_promotion'    => true,
7400
				'discount_percent'  => 30,
7401
				'options'           => array(
7402
					array(
7403
						'type'      => 'scan',
7404
						'slug'      => 'jetpack-scan',
7405
						'key'       => 'jetpack_scan',
7406
						'name'      => __( 'Daily Scan', 'jetpack' ),
7407
					),
7408
				),
7409
				'default_option'    => 'scan',
7410
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7411
			);
7412
		}
7413
7414
		$products[] = array(
7415
			'key'               => 'search',
7416
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7417
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7418
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7419
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7420
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7421
			'options'           => array(
7422
				array(
7423
					'type'      => 'search',
7424
					'slug'      => 'jetpack-search',
7425
					'key'       => 'jetpack_search',
7426
					'name'      => __( 'Search', 'jetpack' ),
7427
				),
7428
			),
7429
			'tears'             => array(),
7430
			'default_option'    => 'search',
7431
			'show_promotion'    => false,
7432
			'included_in_plans' => array( 'search-plan' ),
7433
		);
7434
7435
		$products[] = array(
7436
			'key'               => 'anti-spam',
7437
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7438
			'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' ),
7439
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7440
			'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' ),
7441
			'options'           => array(
7442
				array(
7443
					'type'      => 'anti-spam',
7444
					'slug'      => 'jetpack-anti-spam',
7445
					'key'       => 'jetpack_anti_spam',
7446
					'name'      => __( 'Anti-Spam', 'jetpack' ),
7447
				),
7448
			),
7449
			'default_option'    => 'anti-spam',
7450
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7451
		);
7452
7453
		return $products;
7454
	}
7455
}
7456