Completed
Push — fix/improve-search-product-lay... ( e4fb73...5c8387 )
by
unknown
146:14 queued 136:16
created

Jetpack::get_available_modules()   C

Complexity

Conditions 13
Paths 15

Size

Total Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 15
nop 2
dl 0
loc 60
rs 6.6166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
888
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
889
		} else {
890
			/**
891
			 * Initialize tracking right after the user agrees to the terms of service.
892
			 */
893
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
894
		}
895
	}
896
897
	/**
898
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
899
	 * initialization code.
900
	 *
901
	 * @action plugins_loaded
902
	 */
903
	public function late_initialization() {
904
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
905
906
		Partner::init();
907
908
		/**
909
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
910
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
911
		 *
912
		 * @since 8.1.0
913
		 *
914
		 * @param Jetpack $jetpack the main plugin class object.
915
		 */
916
		do_action( 'jetpack_loaded', $this );
917
918
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
919
	}
920
921
	/**
922
	 * Sets up the XMLRPC request handlers.
923
	 *
924
	 * @deprecated since 7.7.0
925
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
926
	 *
927
	 * @param array                 $request_params Incoming request parameters.
928
	 * @param Boolean               $is_active      Whether the connection is currently active.
929
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
930
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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

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

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

Loading history...
931
	 */
932 View Code Duplication
	public function setup_xmlrpc_handlers(
933
		$request_params,
934
		$is_active,
935
		$is_signed,
936
		Jetpack_XMLRPC_Server $xmlrpc_server = null
937
	) {
938
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
939
940
		if ( ! $this->connection_manager ) {
941
			$this->connection_manager = new Connection_Manager();
942
		}
943
944
		return $this->connection_manager->setup_xmlrpc_handlers(
945
			$request_params,
946
			$is_active,
947
			$is_signed,
948
			$xmlrpc_server
949
		);
950
	}
951
952
	/**
953
	 * Initialize REST API registration connector.
954
	 *
955
	 * @deprecated since 7.7.0
956
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
957
	 */
958 View Code Duplication
	public function initialize_rest_api_registration_connector() {
959
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
960
961
		if ( ! $this->connection_manager ) {
962
			$this->connection_manager = new Connection_Manager();
963
		}
964
965
		$this->connection_manager->initialize_rest_api_registration_connector();
966
	}
967
968
	/**
969
	 * This is ported over from the manage module, which has been deprecated and baked in here.
970
	 *
971
	 * @param $domains
972
	 */
973
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
974
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
975
	}
976
977
	/**
978
	 * Return $domains, with 'wordpress.com' appended.
979
	 * This is ported over from the manage module, which has been deprecated and baked in here.
980
	 *
981
	 * @param $domains
982
	 * @return array
983
	 */
984
	function allow_wpcom_domain( $domains ) {
985
		if ( empty( $domains ) ) {
986
			$domains = array();
987
		}
988
		$domains[] = 'wordpress.com';
989
		return array_unique( $domains );
990
	}
991
992
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
993
		$post = get_post( $post_id );
994
995
		if ( empty( $post ) ) {
996
			return $default_url;
997
		}
998
999
		$post_type = $post->post_type;
1000
1001
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1002
		// https://en.support.wordpress.com/custom-post-types/
1003
		$allowed_post_types = array(
1004
			'post',
1005
			'page',
1006
			'jetpack-portfolio',
1007
			'jetpack-testimonial',
1008
		);
1009
1010
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1011
			return $default_url;
1012
		}
1013
1014
		return Redirect::get_url(
1015
			'calypso-edit-' . $post_type,
1016
			array(
1017
				'path' => $post_id,
1018
			)
1019
		);
1020
	}
1021
1022
	function point_edit_comment_links_to_calypso( $url ) {
1023
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1024
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

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

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

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

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

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

Loading history...
1460
	 */
1461
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1462
		if ( 'administrator' == $role
1463
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1464
			|| is_null( $old_roles )
1465
		) {
1466
			delete_transient( 'jetpack_other_linked_admins' );
1467
		}
1468
	}
1469
1470
	/**
1471
	 * Checks to see if there are any other users available to become primary
1472
	 * Users must both:
1473
	 * - Be linked to wpcom
1474
	 * - Be an admin
1475
	 *
1476
	 * @return mixed False if no other users are linked, Int if there are.
1477
	 */
1478
	static function get_other_linked_admins() {
1479
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1480
1481
		if ( false === $other_linked_users ) {
1482
			$admins = get_users( array( 'role' => 'administrator' ) );
1483
			if ( count( $admins ) > 1 ) {
1484
				$available = array();
1485
				foreach ( $admins as $admin ) {
1486
					if ( self::connection()->is_user_connected( $admin->ID ) ) {
1487
						$available[] = $admin->ID;
1488
					}
1489
				}
1490
1491
				$count_connected_admins = count( $available );
1492
				if ( count( $available ) > 1 ) {
1493
					$other_linked_users = $count_connected_admins;
1494
				} else {
1495
					$other_linked_users = 0;
1496
				}
1497
			} else {
1498
				$other_linked_users = 0;
1499
			}
1500
1501
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1502
		}
1503
1504
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1505
	}
1506
1507
	/**
1508
	 * Return whether we are dealing with a multi network setup or not.
1509
	 * The reason we are type casting this is because we want to avoid the situation where
1510
	 * the result is false since when is_main_network_option return false it cases
1511
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1512
	 * database which could be set to anything as opposed to what this function returns.
1513
	 *
1514
	 * @param  bool $option
1515
	 *
1516
	 * @return boolean
1517
	 */
1518
	public function is_main_network_option( $option ) {
1519
		// return '1' or ''
1520
		return (string) (bool) self::is_multi_network();
1521
	}
1522
1523
	/**
1524
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1525
	 *
1526
	 * @param  string $option
1527
	 * @return boolean
1528
	 */
1529
	public function is_multisite( $option ) {
1530
		return (string) (bool) is_multisite();
1531
	}
1532
1533
	/**
1534
	 * Implemented since there is no core is multi network function
1535
	 * Right now there is no way to tell if we which network is the dominant network on the system
1536
	 *
1537
	 * @since  3.3
1538
	 * @return boolean
1539
	 */
1540 View Code Duplication
	public static function is_multi_network() {
1541
		global  $wpdb;
1542
1543
		// if we don't have a multi site setup no need to do any more
1544
		if ( ! is_multisite() ) {
1545
			return false;
1546
		}
1547
1548
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1549
		if ( $num_sites > 1 ) {
1550
			return true;
1551
		} else {
1552
			return false;
1553
		}
1554
	}
1555
1556
	/**
1557
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1558
	 *
1559
	 * @return null
1560
	 */
1561
	function update_jetpack_main_network_site_option() {
1562
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1563
	}
1564
	/**
1565
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1566
	 */
1567
	function update_jetpack_network_settings() {
1568
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1569
		// Only sync this info for the main network site.
1570
	}
1571
1572
	/**
1573
	 * Get back if the current site is single user site.
1574
	 *
1575
	 * @return bool
1576
	 */
1577 View Code Duplication
	public static function is_single_user_site() {
1578
		global $wpdb;
1579
1580
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1581
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1582
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1583
		}
1584
		return 1 === (int) $some_users;
1585
	}
1586
1587
	/**
1588
	 * Returns true if the site has file write access false otherwise.
1589
	 *
1590
	 * @return string ( '1' | '0' )
1591
	 **/
1592
	public static function file_system_write_access() {
1593
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1594
			require_once ABSPATH . 'wp-admin/includes/file.php';
1595
		}
1596
1597
		require_once ABSPATH . 'wp-admin/includes/template.php';
1598
1599
		$filesystem_method = get_filesystem_method();
1600
		if ( $filesystem_method === 'direct' ) {
1601
			return 1;
1602
		}
1603
1604
		ob_start();
1605
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1606
		ob_end_clean();
1607
		if ( $filesystem_credentials_are_stored ) {
1608
			return 1;
1609
		}
1610
		return 0;
1611
	}
1612
1613
	/**
1614
	 * Finds out if a site is using a version control system.
1615
	 *
1616
	 * @return string ( '1' | '0' )
1617
	 **/
1618
	public static function is_version_controlled() {
1619
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1620
		return (string) (int) Functions::is_version_controlled();
1621
	}
1622
1623
	/**
1624
	 * Determines whether the current theme supports featured images or not.
1625
	 *
1626
	 * @return string ( '1' | '0' )
1627
	 */
1628
	public static function featured_images_enabled() {
1629
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1630
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1631
	}
1632
1633
	/**
1634
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1635
	 *
1636
	 * @deprecated 4.7 use get_avatar_url instead.
1637
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1638
	 * @param int               $size Size of the avatar image
1639
	 * @param string            $default URL to a default image to use if no avatar is available
1640
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1641
	 *
1642
	 * @return array
1643
	 */
1644
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1645
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1646
		return get_avatar_url(
1647
			$id_or_email,
1648
			array(
1649
				'size'          => $size,
1650
				'default'       => $default,
1651
				'force_default' => $force_display,
1652
			)
1653
		);
1654
	}
1655
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1656
	/**
1657
	 * jetpack_updates is saved in the following schema:
1658
	 *
1659
	 * array (
1660
	 *      'plugins'                       => (int) Number of plugin updates available.
1661
	 *      'themes'                        => (int) Number of theme updates available.
1662
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1663
	 *      'translations'                  => (int) Number of translation updates available.
1664
	 *      'total'                         => (int) Total of all available updates.
1665
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1666
	 * )
1667
	 *
1668
	 * @return array
1669
	 */
1670
	public static function get_updates() {
1671
		$update_data = wp_get_update_data();
1672
1673
		// Stores the individual update counts as well as the total count.
1674
		if ( isset( $update_data['counts'] ) ) {
1675
			$updates = $update_data['counts'];
1676
		}
1677
1678
		// If we need to update WordPress core, let's find the latest version number.
1679 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1680
			$cur = get_preferred_from_update_core();
1681
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1682
				$updates['wp_update_version'] = $cur->current;
1683
			}
1684
		}
1685
		return isset( $updates ) ? $updates : array();
1686
	}
1687
	// phpcs:enable
1688
1689
	public static function get_update_details() {
1690
		$update_details = array(
1691
			'update_core'    => get_site_transient( 'update_core' ),
1692
			'update_plugins' => get_site_transient( 'update_plugins' ),
1693
			'update_themes'  => get_site_transient( 'update_themes' ),
1694
		);
1695
		return $update_details;
1696
	}
1697
1698
	public static function refresh_update_data() {
1699
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1700
1701
	}
1702
1703
	public static function refresh_theme_data() {
1704
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1705
	}
1706
1707
	/**
1708
	 * Is Jetpack active?
1709
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1710
	 *
1711
	 * @return bool
1712
	 */
1713
	public static function is_active() {
1714
		return self::connection()->is_active();
1715
	}
1716
1717
	/**
1718
	 * Make an API call to WordPress.com for plan status
1719
	 *
1720
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1721
	 *
1722
	 * @return bool True if plan is updated, false if no update
1723
	 */
1724
	public static function refresh_active_plan_from_wpcom() {
1725
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1726
		return Jetpack_Plan::refresh_from_wpcom();
1727
	}
1728
1729
	/**
1730
	 * Get the plan that this Jetpack site is currently using
1731
	 *
1732
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1733
	 * @return array Active Jetpack plan details.
1734
	 */
1735
	public static function get_active_plan() {
1736
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1737
		return Jetpack_Plan::get();
1738
	}
1739
1740
	/**
1741
	 * Determine whether the active plan supports a particular feature
1742
	 *
1743
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1744
	 * @return bool True if plan supports feature, false if not.
1745
	 */
1746
	public static function active_plan_supports( $feature ) {
1747
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1748
		return Jetpack_Plan::supports( $feature );
1749
	}
1750
1751
	/**
1752
	 * Deprecated: Is Jetpack in development (offline) mode?
1753
	 *
1754
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1755
	 * and themes still use it, and we do not want to flood them with notices.
1756
	 *
1757
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1758
	 *
1759
	 * @deprecated since 8.0.
1760
	 */
1761
	public static function is_development_mode() {
1762
		_deprecated_function( __METHOD__, 'jetpack-8.0', '\Automattic\Jetpack\Status->is_offline_mode' );
1763
		return ( new Status() )->is_offline_mode();
1764
	}
1765
1766
	/**
1767
	 * Whether the site is currently onboarding or not.
1768
	 * A site is considered as being onboarded if it currently has an onboarding token.
1769
	 *
1770
	 * @since 5.8
1771
	 *
1772
	 * @access public
1773
	 * @static
1774
	 *
1775
	 * @return bool True if the site is currently onboarding, false otherwise
1776
	 */
1777
	public static function is_onboarding() {
1778
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1779
	}
1780
1781
	/**
1782
	 * Determines reason for Jetpack offline mode.
1783
	 */
1784
	public static function development_mode_trigger_text() {
1785
		$status = new Status();
1786
1787
		if ( ! $status->is_offline_mode() ) {
1788
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1789
		}
1790
1791
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1792
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1793
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1794
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1795
		} elseif ( $status->is_local_site() ) {
1796
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1797
			/** This filter is documented in packages/status/src/class-status.php */
1798
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1799
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1800
		} else {
1801
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1802
		}
1803
1804
		return $notice;
1805
1806
	}
1807
	/**
1808
	 * Get Jetpack offline mode notice text and notice class.
1809
	 *
1810
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1811
	 */
1812
	public static function show_development_mode_notice() {
1813 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1814
			$notice = sprintf(
1815
				/* translators: %s is a URL */
1816
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1817
				Redirect::get_url( 'jetpack-support-development-mode' )
1818
			);
1819
1820
			$notice .= ' ' . self::development_mode_trigger_text();
1821
1822
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1823
		}
1824
1825
		// Throw up a notice if using a development version and as for feedback.
1826
		if ( self::is_development_version() ) {
1827
			/* translators: %s is a URL */
1828
			$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' ) );
1829
1830
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1831
		}
1832
		// Throw up a notice if using staging mode
1833 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1834
			/* translators: %s is a URL */
1835
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1836
1837
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1838
		}
1839
	}
1840
1841
	/**
1842
	 * Whether Jetpack's version maps to a public release, or a development version.
1843
	 */
1844
	public static function is_development_version() {
1845
		/**
1846
		 * Allows filtering whether this is a development version of Jetpack.
1847
		 *
1848
		 * This filter is especially useful for tests.
1849
		 *
1850
		 * @since 4.3.0
1851
		 *
1852
		 * @param bool $development_version Is this a develoment version of Jetpack?
1853
		 */
1854
		return (bool) apply_filters(
1855
			'jetpack_development_version',
1856
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1857
		);
1858
	}
1859
1860
	/**
1861
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1862
	 */
1863
	public static function is_user_connected( $user_id = false ) {
1864
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1865
		return self::connection()->is_user_connected( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1866
	}
1867
1868
	/**
1869
	 * Get the wpcom user data of the current|specified connected user.
1870
	 */
1871
	public static function get_connected_user_data( $user_id = null ) {
1872
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\get_connected_user_data' );
1873
		return self::connection()->get_connected_user_data( $user_id );
1874
	}
1875
1876
	/**
1877
	 * Get the wpcom email of the current|specified connected user.
1878
	 */
1879
	public static function get_connected_user_email( $user_id = null ) {
1880
		if ( ! $user_id ) {
1881
			$user_id = get_current_user_id();
1882
		}
1883
1884
		$xml = new Jetpack_IXR_Client(
1885
			array(
1886
				'user_id' => $user_id,
1887
			)
1888
		);
1889
		$xml->query( 'wpcom.getUserEmail' );
1890
		if ( ! $xml->isError() ) {
1891
			return $xml->getResponse();
1892
		}
1893
		return false;
1894
	}
1895
1896
	/**
1897
	 * Get the wpcom email of the master user.
1898
	 */
1899
	public static function get_master_user_email() {
1900
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1901
		if ( $master_user_id ) {
1902
			return self::get_connected_user_email( $master_user_id );
1903
		}
1904
		return '';
1905
	}
1906
1907
	/**
1908
	 * Whether the current user is the connection owner.
1909
	 *
1910
	 * @deprecated since 7.7
1911
	 *
1912
	 * @return bool Whether the current user is the connection owner.
1913
	 */
1914
	public function current_user_is_connection_owner() {
1915
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1916
		return self::connection()->is_connection_owner();
1917
	}
1918
1919
	/**
1920
	 * Gets current user IP address.
1921
	 *
1922
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1923
	 *
1924
	 * @return string                  Current user IP address.
1925
	 */
1926
	public static function current_user_ip( $check_all_headers = false ) {
1927
		if ( $check_all_headers ) {
1928
			foreach ( array(
1929
				'HTTP_CF_CONNECTING_IP',
1930
				'HTTP_CLIENT_IP',
1931
				'HTTP_X_FORWARDED_FOR',
1932
				'HTTP_X_FORWARDED',
1933
				'HTTP_X_CLUSTER_CLIENT_IP',
1934
				'HTTP_FORWARDED_FOR',
1935
				'HTTP_FORWARDED',
1936
				'HTTP_VIA',
1937
			) as $key ) {
1938
				if ( ! empty( $_SERVER[ $key ] ) ) {
1939
					return $_SERVER[ $key ];
1940
				}
1941
			}
1942
		}
1943
1944
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1945
	}
1946
1947
	/**
1948
	 * Synchronize connected user role changes
1949
	 */
1950
	function user_role_change( $user_id ) {
1951
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1952
		Users::user_role_change( $user_id );
1953
	}
1954
1955
	/**
1956
	 * Loads the currently active modules.
1957
	 */
1958
	public static function load_modules() {
1959
		$is_offline_mode = ( new Status() )->is_offline_mode();
1960
		if (
1961
			! self::is_active()
1962
			&& ! $is_offline_mode
1963
			&& ! self::is_onboarding()
1964
			&& (
1965
				! is_multisite()
1966
				|| ! get_site_option( 'jetpack_protect_active' )
1967
			)
1968
		) {
1969
			return;
1970
		}
1971
1972
		$version = Jetpack_Options::get_option( 'version' );
1973 View Code Duplication
		if ( ! $version ) {
1974
			$version = $old_version = JETPACK__VERSION . ':' . time();
1975
			/** This action is documented in class.jetpack.php */
1976
			do_action( 'updating_jetpack_version', $version, false );
1977
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1978
		}
1979
		list( $version ) = explode( ':', $version );
1980
1981
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1982
1983
		$modules_data = array();
1984
1985
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1986
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1987
			$updated_modules = array();
1988
			foreach ( $modules as $module ) {
1989
				$modules_data[ $module ] = self::get_module( $module );
1990
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1991
					continue;
1992
				}
1993
1994
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1995
					continue;
1996
				}
1997
1998
				$updated_modules[] = $module;
1999
			}
2000
2001
			$modules = array_diff( $modules, $updated_modules );
2002
		}
2003
2004
		foreach ( $modules as $index => $module ) {
2005
			// If we're in offline mode, disable modules requiring a connection.
2006
			if ( $is_offline_mode ) {
2007
				// Prime the pump if we need to
2008
				if ( empty( $modules_data[ $module ] ) ) {
2009
					$modules_data[ $module ] = self::get_module( $module );
2010
				}
2011
				// If the module requires a connection, but we're in local mode, don't include it.
2012
				if ( $modules_data[ $module ]['requires_connection'] ) {
2013
					continue;
2014
				}
2015
			}
2016
2017
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2018
				continue;
2019
			}
2020
2021
			if ( ! include_once self::get_module_path( $module ) ) {
2022
				unset( $modules[ $index ] );
2023
				self::update_active_modules( array_values( $modules ) );
2024
				continue;
2025
			}
2026
2027
			/**
2028
			 * Fires when a specific module is loaded.
2029
			 * The dynamic part of the hook, $module, is the module slug.
2030
			 *
2031
			 * @since 1.1.0
2032
			 */
2033
			do_action( 'jetpack_module_loaded_' . $module );
2034
		}
2035
2036
		/**
2037
		 * Fires when all the modules are loaded.
2038
		 *
2039
		 * @since 1.1.0
2040
		 */
2041
		do_action( 'jetpack_modules_loaded' );
2042
2043
		// 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.
2044
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2045
	}
2046
2047
	/**
2048
	 * Check if Jetpack's REST API compat file should be included
2049
	 *
2050
	 * @action plugins_loaded
2051
	 * @return null
2052
	 */
2053
	public function check_rest_api_compat() {
2054
		/**
2055
		 * Filters the list of REST API compat files to be included.
2056
		 *
2057
		 * @since 2.2.5
2058
		 *
2059
		 * @param array $args Array of REST API compat files to include.
2060
		 */
2061
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2062
2063
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2064
			require_once $_jetpack_rest_api_compat_include;
2065
		}
2066
	}
2067
2068
	/**
2069
	 * Gets all plugins currently active in values, regardless of whether they're
2070
	 * traditionally activated or network activated.
2071
	 *
2072
	 * @todo Store the result in core's object cache maybe?
2073
	 */
2074
	public static function get_active_plugins() {
2075
		$active_plugins = (array) get_option( 'active_plugins', array() );
2076
2077
		if ( is_multisite() ) {
2078
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2079
			// whereas active_plugins stores them in the values.
2080
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2081
			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...
2082
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2083
			}
2084
		}
2085
2086
		sort( $active_plugins );
2087
2088
		return array_unique( $active_plugins );
2089
	}
2090
2091
	/**
2092
	 * Gets and parses additional plugin data to send with the heartbeat data
2093
	 *
2094
	 * @since 3.8.1
2095
	 *
2096
	 * @return array Array of plugin data
2097
	 */
2098
	public static function get_parsed_plugin_data() {
2099
		if ( ! function_exists( 'get_plugins' ) ) {
2100
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2101
		}
2102
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2103
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2104
		$active_plugins = self::get_active_plugins();
2105
2106
		$plugins = array();
2107
		foreach ( $all_plugins as $path => $plugin_data ) {
2108
			$plugins[ $path ] = array(
2109
				'is_active' => in_array( $path, $active_plugins ),
2110
				'file'      => $path,
2111
				'name'      => $plugin_data['Name'],
2112
				'version'   => $plugin_data['Version'],
2113
				'author'    => $plugin_data['Author'],
2114
			);
2115
		}
2116
2117
		return $plugins;
2118
	}
2119
2120
	/**
2121
	 * Gets and parses theme data to send with the heartbeat data
2122
	 *
2123
	 * @since 3.8.1
2124
	 *
2125
	 * @return array Array of theme data
2126
	 */
2127
	public static function get_parsed_theme_data() {
2128
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2129
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2130
2131
		$themes = array();
2132
		foreach ( $all_themes as $slug => $theme_data ) {
2133
			$theme_headers = array();
2134
			foreach ( $header_keys as $header_key ) {
2135
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2136
			}
2137
2138
			$themes[ $slug ] = array(
2139
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2140
				'slug'            => $slug,
2141
				'theme_root'      => $theme_data->get_theme_root_uri(),
2142
				'parent'          => $theme_data->parent(),
2143
				'headers'         => $theme_headers,
2144
			);
2145
		}
2146
2147
		return $themes;
2148
	}
2149
2150
	/**
2151
	 * Checks whether a specific plugin is active.
2152
	 *
2153
	 * We don't want to store these in a static variable, in case
2154
	 * there are switch_to_blog() calls involved.
2155
	 */
2156
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2157
		return in_array( $plugin, self::get_active_plugins() );
2158
	}
2159
2160
	/**
2161
	 * Check if Jetpack's Open Graph tags should be used.
2162
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2163
	 *
2164
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2165
	 * @action plugins_loaded
2166
	 * @return null
2167
	 */
2168
	public function check_open_graph() {
2169
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2170
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2171
		}
2172
2173
		$active_plugins = self::get_active_plugins();
2174
2175
		if ( ! empty( $active_plugins ) ) {
2176
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2177
				if ( in_array( $plugin, $active_plugins ) ) {
2178
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2179
					break;
2180
				}
2181
			}
2182
		}
2183
2184
		/**
2185
		 * Allow the addition of Open Graph Meta Tags to all pages.
2186
		 *
2187
		 * @since 2.0.3
2188
		 *
2189
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2190
		 */
2191
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2192
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2193
		}
2194
	}
2195
2196
	/**
2197
	 * Check if Jetpack's Twitter tags should be used.
2198
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2199
	 *
2200
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2201
	 * @action plugins_loaded
2202
	 * @return null
2203
	 */
2204
	public function check_twitter_tags() {
2205
2206
		$active_plugins = self::get_active_plugins();
2207
2208
		if ( ! empty( $active_plugins ) ) {
2209
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2210
				if ( in_array( $plugin, $active_plugins ) ) {
2211
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2212
					break;
2213
				}
2214
			}
2215
		}
2216
2217
		/**
2218
		 * Allow Twitter Card Meta tags to be disabled.
2219
		 *
2220
		 * @since 2.6.0
2221
		 *
2222
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2223
		 */
2224
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2225
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2226
		}
2227
	}
2228
2229
	/**
2230
	 * Allows plugins to submit security reports.
2231
	 *
2232
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2233
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2234
	 * @param array  $args         See definitions above
2235
	 */
2236
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2237
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2238
	}
2239
2240
	/* Jetpack Options API */
2241
2242
	public static function get_option_names( $type = 'compact' ) {
2243
		return Jetpack_Options::get_option_names( $type );
2244
	}
2245
2246
	/**
2247
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2248
	 *
2249
	 * @param string $name    Option name
2250
	 * @param mixed  $default (optional)
2251
	 */
2252
	public static function get_option( $name, $default = false ) {
2253
		return Jetpack_Options::get_option( $name, $default );
2254
	}
2255
2256
	/**
2257
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2258
	 *
2259
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2260
	 * @param string $name  Option name
2261
	 * @param mixed  $value Option value
2262
	 */
2263
	public static function update_option( $name, $value ) {
2264
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2265
		return Jetpack_Options::update_option( $name, $value );
2266
	}
2267
2268
	/**
2269
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2270
	 *
2271
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2272
	 * @param array $array array( option name => option value, ... )
2273
	 */
2274
	public static function update_options( $array ) {
2275
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2276
		return Jetpack_Options::update_options( $array );
2277
	}
2278
2279
	/**
2280
	 * Deletes the given option.  May be passed multiple option names as an array.
2281
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2282
	 *
2283
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2284
	 * @param string|array $names
2285
	 */
2286
	public static function delete_option( $names ) {
2287
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2288
		return Jetpack_Options::delete_option( $names );
2289
	}
2290
2291
	/**
2292
	 * Enters a user token into the user_tokens option
2293
	 *
2294
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Tokens->update_user_token() instead.
2295
	 *
2296
	 * @param int    $user_id The user id.
2297
	 * @param string $token The user token.
2298
	 * @param bool   $is_master_user Whether the user is the master user.
2299
	 * @return bool
2300
	 */
2301
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2302
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Tokens->update_user_token' );
2303
		return ( new Tokens() )->update_user_token( $user_id, $token, $is_master_user );
2304
	}
2305
2306
	/**
2307
	 * Returns an array of all PHP files in the specified absolute path.
2308
	 * Equivalent to glob( "$absolute_path/*.php" ).
2309
	 *
2310
	 * @param string $absolute_path The absolute path of the directory to search.
2311
	 * @return array Array of absolute paths to the PHP files.
2312
	 */
2313
	public static function glob_php( $absolute_path ) {
2314
		if ( function_exists( 'glob' ) ) {
2315
			return glob( "$absolute_path/*.php" );
2316
		}
2317
2318
		$absolute_path = untrailingslashit( $absolute_path );
2319
		$files         = array();
2320
		if ( ! $dir = @opendir( $absolute_path ) ) {
2321
			return $files;
2322
		}
2323
2324
		while ( false !== $file = readdir( $dir ) ) {
2325
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2326
				continue;
2327
			}
2328
2329
			$file = "$absolute_path/$file";
2330
2331
			if ( ! is_file( $file ) ) {
2332
				continue;
2333
			}
2334
2335
			$files[] = $file;
2336
		}
2337
2338
		closedir( $dir );
2339
2340
		return $files;
2341
	}
2342
2343
	public static function activate_new_modules( $redirect = false ) {
2344
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2345
			return;
2346
		}
2347
2348
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2349 View Code Duplication
		if ( ! $jetpack_old_version ) {
2350
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2351
			/** This action is documented in class.jetpack.php */
2352
			do_action( 'updating_jetpack_version', $version, false );
2353
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2354
		}
2355
2356
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2357
2358
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2359
			return;
2360
		}
2361
2362
		$active_modules     = self::get_active_modules();
2363
		$reactivate_modules = array();
2364
		foreach ( $active_modules as $active_module ) {
2365
			$module = self::get_module( $active_module );
2366
			if ( ! isset( $module['changed'] ) ) {
2367
				continue;
2368
			}
2369
2370
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2371
				continue;
2372
			}
2373
2374
			$reactivate_modules[] = $active_module;
2375
			self::deactivate_module( $active_module );
2376
		}
2377
2378
		$new_version = JETPACK__VERSION . ':' . time();
2379
		/** This action is documented in class.jetpack.php */
2380
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2381
		Jetpack_Options::update_options(
2382
			array(
2383
				'version'     => $new_version,
2384
				'old_version' => $jetpack_old_version,
2385
			)
2386
		);
2387
2388
		self::state( 'message', 'modules_activated' );
2389
2390
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2391
2392
		if ( $redirect ) {
2393
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2394
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2395
				$page = $_GET['page'];
2396
			}
2397
2398
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2399
			exit;
2400
		}
2401
	}
2402
2403
	/**
2404
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2405
	 * Make sure to tuck away module "library" files in a sub-directory.
2406
	 */
2407
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2408
		static $modules = null;
2409
2410
		if ( ! isset( $modules ) ) {
2411
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2412
			// Use the cache if we're on the front-end and it's available...
2413
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2414
				$modules = $available_modules_option[ JETPACK__VERSION ];
2415
			} else {
2416
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2417
2418
				$modules = array();
2419
2420
				foreach ( $files as $file ) {
2421
					if ( ! $headers = self::get_module( $file ) ) {
2422
						continue;
2423
					}
2424
2425
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2426
				}
2427
2428
				Jetpack_Options::update_option(
2429
					'available_modules',
2430
					array(
2431
						JETPACK__VERSION => $modules,
2432
					)
2433
				);
2434
			}
2435
		}
2436
2437
		/**
2438
		 * Filters the array of modules available to be activated.
2439
		 *
2440
		 * @since 2.4.0
2441
		 *
2442
		 * @param array $modules Array of available modules.
2443
		 * @param string $min_version Minimum version number required to use modules.
2444
		 * @param string $max_version Maximum version number required to use modules.
2445
		 */
2446
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2447
2448
		if ( ! $min_version && ! $max_version ) {
2449
			return array_keys( $mods );
2450
		}
2451
2452
		$r = array();
2453
		foreach ( $mods as $slug => $introduced ) {
2454
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2455
				continue;
2456
			}
2457
2458
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2459
				continue;
2460
			}
2461
2462
			$r[] = $slug;
2463
		}
2464
2465
		return $r;
2466
	}
2467
2468
	/**
2469
	 * Default modules loaded on activation.
2470
	 */
2471
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2472
		$return = array();
2473
2474
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2475
			$module_data = self::get_module( $module );
2476
2477
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2478
				case 'yes':
2479
					$return[] = $module;
2480
					break;
2481
				case 'public':
2482
					if ( Jetpack_Options::get_option( 'public' ) ) {
2483
						$return[] = $module;
2484
					}
2485
					break;
2486
				case 'no':
2487
				default:
2488
					break;
2489
			}
2490
		}
2491
		/**
2492
		 * Filters the array of default modules.
2493
		 *
2494
		 * @since 2.5.0
2495
		 *
2496
		 * @param array $return Array of default modules.
2497
		 * @param string $min_version Minimum version number required to use modules.
2498
		 * @param string $max_version Maximum version number required to use modules.
2499
		 */
2500
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2501
	}
2502
2503
	/**
2504
	 * Checks activated modules during auto-activation to determine
2505
	 * if any of those modules are being deprecated.  If so, close
2506
	 * them out, and add any replacement modules.
2507
	 *
2508
	 * Runs at priority 99 by default.
2509
	 *
2510
	 * This is run late, so that it can still activate a module if
2511
	 * the new module is a replacement for another that the user
2512
	 * currently has active, even if something at the normal priority
2513
	 * would kibosh everything.
2514
	 *
2515
	 * @since 2.6
2516
	 * @uses jetpack_get_default_modules filter
2517
	 * @param array $modules
2518
	 * @return array
2519
	 */
2520
	function handle_deprecated_modules( $modules ) {
2521
		$deprecated_modules = array(
2522
			'debug'            => null,  // Closed out and moved to the debugger library.
2523
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2524
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2525
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2526
		);
2527
2528
		// Don't activate SSO if they never completed activating WPCC.
2529
		if ( self::is_module_active( 'wpcc' ) ) {
2530
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2531
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2532
				$deprecated_modules['wpcc'] = null;
2533
			}
2534
		}
2535
2536
		foreach ( $deprecated_modules as $module => $replacement ) {
2537
			if ( self::is_module_active( $module ) ) {
2538
				self::deactivate_module( $module );
2539
				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...
2540
					$modules[] = $replacement;
2541
				}
2542
			}
2543
		}
2544
2545
		return array_unique( $modules );
2546
	}
2547
2548
	/**
2549
	 * Checks activated plugins during auto-activation to determine
2550
	 * if any of those plugins are in the list with a corresponding module
2551
	 * that is not compatible with the plugin. The module will not be allowed
2552
	 * to auto-activate.
2553
	 *
2554
	 * @since 2.6
2555
	 * @uses jetpack_get_default_modules filter
2556
	 * @param array $modules
2557
	 * @return array
2558
	 */
2559
	function filter_default_modules( $modules ) {
2560
2561
		$active_plugins = self::get_active_plugins();
2562
2563
		if ( ! empty( $active_plugins ) ) {
2564
2565
			// For each module we'd like to auto-activate...
2566
			foreach ( $modules as $key => $module ) {
2567
				// If there are potential conflicts for it...
2568
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2569
					// For each potential conflict...
2570
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2571
						// If that conflicting plugin is active...
2572
						if ( in_array( $plugin, $active_plugins ) ) {
2573
							// Remove that item from being auto-activated.
2574
							unset( $modules[ $key ] );
2575
						}
2576
					}
2577
				}
2578
			}
2579
		}
2580
2581
		return $modules;
2582
	}
2583
2584
	/**
2585
	 * Extract a module's slug from its full path.
2586
	 */
2587
	public static function get_module_slug( $file ) {
2588
		return str_replace( '.php', '', basename( $file ) );
2589
	}
2590
2591
	/**
2592
	 * Generate a module's path from its slug.
2593
	 */
2594
	public static function get_module_path( $slug ) {
2595
		/**
2596
		 * Filters the path of a modules.
2597
		 *
2598
		 * @since 7.4.0
2599
		 *
2600
		 * @param array $return The absolute path to a module's root php file
2601
		 * @param string $slug The module slug
2602
		 */
2603
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

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

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

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

Loading history...
2604
	}
2605
2606
	/**
2607
	 * Load module data from module file. Headers differ from WordPress
2608
	 * plugin headers to avoid them being identified as standalone
2609
	 * plugins on the WordPress plugins page.
2610
	 */
2611
	public static function get_module( $module ) {
2612
		$headers = array(
2613
			'name'                      => 'Module Name',
2614
			'description'               => 'Module Description',
2615
			'sort'                      => 'Sort Order',
2616
			'recommendation_order'      => 'Recommendation Order',
2617
			'introduced'                => 'First Introduced',
2618
			'changed'                   => 'Major Changes In',
2619
			'deactivate'                => 'Deactivate',
2620
			'free'                      => 'Free',
2621
			'requires_connection'       => 'Requires Connection',
2622
			'requires_user_connection'  => 'Requires User Connection',
2623
			'auto_activate'             => 'Auto Activate',
2624
			'module_tags'               => 'Module Tags',
2625
			'feature'                   => 'Feature',
2626
			'additional_search_queries' => 'Additional Search Queries',
2627
			'plan_classes'              => 'Plans',
2628
		);
2629
2630
		$file = self::get_module_path( self::get_module_slug( $module ) );
2631
2632
		$mod = self::get_file_data( $file, $headers );
2633
		if ( empty( $mod['name'] ) ) {
2634
			return false;
2635
		}
2636
2637
		$mod['sort']                     = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2638
		$mod['recommendation_order']     = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2639
		$mod['deactivate']               = empty( $mod['deactivate'] );
2640
		$mod['free']                     = empty( $mod['free'] );
2641
		$mod['requires_connection']      = ( ! empty( $mod['requires_connection'] ) && 'No' === $mod['requires_connection'] ) ? false : true;
2642
		$mod['requires_user_connection'] = ( empty( $mod['requires_user_connection'] ) || 'No' === $mod['requires_user_connection'] ) ? false : true;
2643
2644
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2645
			$mod['auto_activate'] = 'No';
2646
		} else {
2647
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2648
		}
2649
2650
		if ( $mod['module_tags'] ) {
2651
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2652
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2653
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2654
		} else {
2655
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2656
		}
2657
2658 View Code Duplication
		if ( $mod['plan_classes'] ) {
2659
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2660
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2661
		} else {
2662
			$mod['plan_classes'] = array( 'free' );
2663
		}
2664
2665 View Code Duplication
		if ( $mod['feature'] ) {
2666
			$mod['feature'] = explode( ',', $mod['feature'] );
2667
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2668
		} else {
2669
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2670
		}
2671
2672
		/**
2673
		 * Filters the feature array on a module.
2674
		 *
2675
		 * This filter allows you to control where each module is filtered: Recommended,
2676
		 * and the default "Other" listing.
2677
		 *
2678
		 * @since 3.5.0
2679
		 *
2680
		 * @param array   $mod['feature'] The areas to feature this module:
2681
		 *     'Recommended' shows on the main Jetpack admin screen.
2682
		 *     'Other' should be the default if no other value is in the array.
2683
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2684
		 * @param array   $mod All the currently assembled module data.
2685
		 */
2686
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

Loading history...
2687
2688
		/**
2689
		 * Filter the returned data about a module.
2690
		 *
2691
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2692
		 * so please be careful.
2693
		 *
2694
		 * @since 3.6.0
2695
		 *
2696
		 * @param array   $mod    The details of the requested module.
2697
		 * @param string  $module The slug of the module, e.g. sharedaddy
2698
		 * @param string  $file   The path to the module source file.
2699
		 */
2700
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3121
		ob_end_clean();
3122
		self::catch_errors( false );
3123
3124
		if ( $redirect ) {
3125
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3126
		}
3127
		if ( $exit ) {
3128
			exit;
3129
		}
3130
		return true;
3131
	}
3132
3133
	function activate_module_actions( $module ) {
3134
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3135
	}
3136
3137
	public static function deactivate_module( $module ) {
3138
		/**
3139
		 * Fires when a module is deactivated.
3140
		 *
3141
		 * @since 1.9.0
3142
		 *
3143
		 * @param string $module Module slug.
3144
		 */
3145
		do_action( 'jetpack_pre_deactivate_module', $module );
3146
3147
		$jetpack = self::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3148
3149
		$active = self::get_active_modules();
3150
		$new    = array_filter( array_diff( $active, (array) $module ) );
3151
3152
		return self::update_active_modules( $new );
3153
	}
3154
3155
	public static function enable_module_configurable( $module ) {
3156
		$module = self::get_module_slug( $module );
3157
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3158
	}
3159
3160
	/**
3161
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3162
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3163
	 *
3164
	 * @param string $module Module slug
3165
	 * @return string $url module configuration URL
3166
	 */
3167
	public static function module_configuration_url( $module ) {
3168
		$module      = self::get_module_slug( $module );
3169
		$default_url = self::admin_url() . "#/settings?term=$module";
3170
		/**
3171
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3172
		 *
3173
		 * @since 6.9.0
3174
		 *
3175
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3176
		 */
3177
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3178
3179
		return $url;
3180
	}
3181
3182
	/* Installation */
3183
	public static function bail_on_activation( $message, $deactivate = true ) {
3184
		?>
3185
<!doctype html>
3186
<html>
3187
<head>
3188
<meta charset="<?php bloginfo( 'charset' ); ?>">
3189
<style>
3190
* {
3191
	text-align: center;
3192
	margin: 0;
3193
	padding: 0;
3194
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3195
}
3196
p {
3197
	margin-top: 1em;
3198
	font-size: 18px;
3199
}
3200
</style>
3201
<body>
3202
<p><?php echo esc_html( $message ); ?></p>
3203
</body>
3204
</html>
3205
		<?php
3206
		if ( $deactivate ) {
3207
			$plugins = get_option( 'active_plugins' );
3208
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3209
			$update  = false;
3210
			foreach ( $plugins as $i => $plugin ) {
3211
				if ( $plugin === $jetpack ) {
3212
					$plugins[ $i ] = false;
3213
					$update        = true;
3214
				}
3215
			}
3216
3217
			if ( $update ) {
3218
				update_option( 'active_plugins', array_filter( $plugins ) );
3219
			}
3220
		}
3221
		exit;
3222
	}
3223
3224
	/**
3225
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3226
	 *
3227
	 * @static
3228
	 */
3229
	public static function plugin_activation( $network_wide ) {
3230
		Jetpack_Options::update_option( 'activated', 1 );
3231
3232
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3233
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3234
		}
3235
3236
		if ( $network_wide ) {
3237
			self::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3238
		}
3239
3240
		// For firing one-off events (notices) immediately after activation
3241
		set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
3242
3243
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3244
3245
		Health::on_jetpack_activated();
3246
3247
		self::plugin_initialize();
3248
	}
3249
3250
	public static function get_activation_source( $referer_url ) {
3251
3252
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3253
			return array( 'wp-cli', null );
3254
		}
3255
3256
		$referer = wp_parse_url( $referer_url );
3257
3258
		$source_type  = 'unknown';
3259
		$source_query = null;
3260
3261
		if ( ! is_array( $referer ) ) {
3262
			return array( $source_type, $source_query );
3263
		}
3264
3265
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3266
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3267
3268
		if ( isset( $referer['query'] ) ) {
3269
			parse_str( $referer['query'], $query_parts );
3270
		} else {
3271
			$query_parts = array();
3272
		}
3273
3274
		if ( $plugins_path === $referer['path'] ) {
3275
			$source_type = 'list';
3276
		} elseif ( $plugins_install_path === $referer['path'] ) {
3277
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3278
			switch ( $tab ) {
3279
				case 'popular':
3280
					$source_type = 'popular';
3281
					break;
3282
				case 'recommended':
3283
					$source_type = 'recommended';
3284
					break;
3285
				case 'favorites':
3286
					$source_type = 'favorites';
3287
					break;
3288
				case 'search':
3289
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3290
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3291
					break;
3292
				default:
3293
					$source_type = 'featured';
3294
			}
3295
		}
3296
3297
		return array( $source_type, $source_query );
3298
	}
3299
3300
	/**
3301
	 * Runs before bumping version numbers up to a new version
3302
	 *
3303
	 * @param string $version    Version:timestamp.
3304
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3305
	 */
3306
	public static function do_version_bump( $version, $old_version ) {
3307
		if ( $old_version ) { // For existing Jetpack installations.
3308
3309
			// If a front end page is visited after the update, the 'wp' action will fire.
3310
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3311
3312
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3313
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3314
		}
3315
	}
3316
3317
	/**
3318
	 * Sets the display_update_modal state.
3319
	 */
3320
	public static function set_update_modal_display() {
3321
		self::state( 'display_update_modal', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3322
	}
3323
3324
	/**
3325
	 * Sets the internal version number and activation state.
3326
	 *
3327
	 * @static
3328
	 */
3329
	public static function plugin_initialize() {
3330
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3331
			Jetpack_Options::update_option( 'activated', 2 );
3332
		}
3333
3334 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3335
			$version = $old_version = JETPACK__VERSION . ':' . time();
3336
			/** This action is documented in class.jetpack.php */
3337
			do_action( 'updating_jetpack_version', $version, false );
3338
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3339
		}
3340
3341
		self::load_modules();
3342
3343
		Jetpack_Options::delete_option( 'do_activate' );
3344
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3345
	}
3346
3347
	/**
3348
	 * Removes all connection options
3349
	 *
3350
	 * @static
3351
	 */
3352
	public static function plugin_deactivation() {
3353
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3354
		$tracking = new Tracking();
3355
		$tracking->record_user_event( 'deactivate_plugin', array() );
3356
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3357
			Jetpack_Network::init()->deactivate();
3358
		} else {
3359
			self::disconnect( false );
3360
			// Jetpack_Heartbeat::init()->deactivate();
3361
		}
3362
	}
3363
3364
	/**
3365
	 * Disconnects from the Jetpack servers.
3366
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3367
	 *
3368
	 * @static
3369
	 */
3370
	public static function disconnect( $update_activated_state = true ) {
3371
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3372
3373
		$connection = self::connection();
3374
3375
		( new Nonce_Handler() )->clean_all();
3376
3377
		// If the site is in an IDC because sync is not allowed,
3378
		// let's make sure to not disconnect the production site.
3379
		if ( ! self::validate_sync_error_idc_option() ) {
3380
			$tracking = new Tracking();
3381
			$tracking->record_user_event( 'disconnect_site', array() );
3382
3383
			$connection->disconnect_site_wpcom( true );
3384
		}
3385
3386
		$connection->delete_all_connection_tokens( true );
3387
		Jetpack_IDC::clear_all_idc_options();
3388
3389
		if ( $update_activated_state ) {
3390
			Jetpack_Options::update_option( 'activated', 4 );
3391
		}
3392
3393
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3394
			// Check then record unique disconnection if site has never been disconnected previously
3395
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3396
				$jetpack_unique_connection['disconnected'] = 1;
3397
			} else {
3398
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3399
					// track unique disconnect
3400
					$jetpack = self::init();
3401
3402
					$jetpack->stat( 'connections', 'unique-disconnect' );
3403
					$jetpack->do_stats( 'server_side' );
3404
				}
3405
				// increment number of times disconnected
3406
				$jetpack_unique_connection['disconnected'] += 1;
3407
			}
3408
3409
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3410
		}
3411
3412
		// Delete all the sync related data. Since it could be taking up space.
3413
		Sender::get_instance()->uninstall();
3414
3415
	}
3416
3417
	/**
3418
	 * Disconnects the user
3419
	 *
3420
	 * @param int $user_id The user ID to disconnect.
3421
	 */
3422
	public function disconnect_user( $user_id ) {
3423
		$this->connection_manager->disconnect_user( $user_id );
3424
	}
3425
3426
	/**
3427
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3428
	 */
3429
	public static function try_registration() {
3430
		$terms_of_service = new Terms_Of_Service();
3431
		// The user has agreed to the TOS at some point by now.
3432
		$terms_of_service->agree();
3433
3434
		// Let's get some testing in beta versions and such.
3435
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3436
			// Before attempting to connect, let's make sure that the domains are viable.
3437
			$domains_to_check = array_unique(
3438
				array(
3439
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3440
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3441
				)
3442
			);
3443
			foreach ( $domains_to_check as $domain ) {
3444
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3443 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

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

Consider the follow example

<?php

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

    return false;
}

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

Loading history...
3445
				if ( is_wp_error( $result ) ) {
3446
					return $result;
3447
				}
3448
			}
3449
		}
3450
3451
		$result = self::register();
3452
3453
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3454
		if ( ! $result || is_wp_error( $result ) ) {
3455
			return $result;
3456
		} else {
3457
			return true;
3458
		}
3459
	}
3460
3461
	/**
3462
	 * Tracking an internal event log. Try not to put too much chaff in here.
3463
	 *
3464
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3465
	 */
3466
	public static function log( $code, $data = null ) {
3467
		// only grab the latest 200 entries
3468
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3469
3470
		// Append our event to the log
3471
		$log_entry = array(
3472
			'time'    => time(),
3473
			'user_id' => get_current_user_id(),
3474
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3475
			'code'    => $code,
3476
		);
3477
		// Don't bother storing it unless we've got some.
3478
		if ( ! is_null( $data ) ) {
3479
			$log_entry['data'] = $data;
3480
		}
3481
		$log[] = $log_entry;
3482
3483
		// Try add_option first, to make sure it's not autoloaded.
3484
		// @todo: Add an add_option method to Jetpack_Options
3485
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3486
			Jetpack_Options::update_option( 'log', $log );
3487
		}
3488
3489
		/**
3490
		 * Fires when Jetpack logs an internal event.
3491
		 *
3492
		 * @since 3.0.0
3493
		 *
3494
		 * @param array $log_entry {
3495
		 *  Array of details about the log entry.
3496
		 *
3497
		 *  @param string time Time of the event.
3498
		 *  @param int user_id ID of the user who trigerred the event.
3499
		 *  @param int blog_id Jetpack Blog ID.
3500
		 *  @param string code Unique name for the event.
3501
		 *  @param string data Data about the event.
3502
		 * }
3503
		 */
3504
		do_action( 'jetpack_log_entry', $log_entry );
3505
	}
3506
3507
	/**
3508
	 * Get the internal event log.
3509
	 *
3510
	 * @param $event (string) - only return the specific log events
3511
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3512
	 *
3513
	 * @return array of log events || WP_Error for invalid params
3514
	 */
3515
	public static function get_log( $event = false, $num = false ) {
3516
		if ( $event && ! is_string( $event ) ) {
3517
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

Loading history...
3518
		}
3519
3520
		if ( $num && ! is_numeric( $num ) ) {
3521
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

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

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

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

Loading history...
3522
		}
3523
3524
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3525
3526
		// If nothing set - act as it did before, otherwise let's start customizing the output
3527
		if ( ! $num && ! $event ) {
3528
			return $entire_log;
3529
		} else {
3530
			$entire_log = array_reverse( $entire_log );
3531
		}
3532
3533
		$custom_log_output = array();
3534
3535
		if ( $event ) {
3536
			foreach ( $entire_log as $log_event ) {
3537
				if ( $event == $log_event['code'] ) {
3538
					$custom_log_output[] = $log_event;
3539
				}
3540
			}
3541
		} else {
3542
			$custom_log_output = $entire_log;
3543
		}
3544
3545
		if ( $num ) {
3546
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3547
		}
3548
3549
		return $custom_log_output;
3550
	}
3551
3552
	/**
3553
	 * Log modification of important settings.
3554
	 */
3555
	public static function log_settings_change( $option, $old_value, $value ) {
3556
		switch ( $option ) {
3557
			case 'jetpack_sync_non_public_post_stati':
3558
				self::log( $option, $value );
3559
				break;
3560
		}
3561
	}
3562
3563
	/**
3564
	 * Return stat data for WPCOM sync
3565
	 */
3566
	public static function get_stat_data( $encode = true, $extended = true ) {
3567
		$data = Jetpack_Heartbeat::generate_stats_array();
3568
3569
		if ( $extended ) {
3570
			$additional_data = self::get_additional_stat_data();
3571
			$data            = array_merge( $data, $additional_data );
3572
		}
3573
3574
		if ( $encode ) {
3575
			return json_encode( $data );
3576
		}
3577
3578
		return $data;
3579
	}
3580
3581
	/**
3582
	 * Get additional stat data to sync to WPCOM
3583
	 */
3584
	public static function get_additional_stat_data( $prefix = '' ) {
3585
		$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...
3586
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3587
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3588
		$return[ "{$prefix}site-count" ]    = 0;
3589
3590
		if ( function_exists( 'get_blog_count' ) ) {
3591
			$return[ "{$prefix}site-count" ] = get_blog_count();
3592
		}
3593
		return $return;
3594
	}
3595
3596
	private static function get_site_user_count() {
3597
		global $wpdb;
3598
3599
		if ( function_exists( 'wp_is_large_network' ) ) {
3600
			if ( wp_is_large_network( 'users' ) ) {
3601
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3602
			}
3603
		}
3604
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3605
			// It wasn't there, so regenerate the data and save the transient
3606
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3607
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3608
		}
3609
		return $user_count;
3610
	}
3611
3612
	/* Admin Pages */
3613
3614
	function admin_init() {
3615
		// If the plugin is not connected, display a connect message.
3616
		if (
3617
			// the plugin was auto-activated and needs its candy
3618
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3619
		||
3620
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3621
			! Jetpack_Options::get_option( 'activated' )
3622
		) {
3623
			self::plugin_initialize();
3624
		}
3625
3626
		$is_offline_mode = ( new Status() )->is_offline_mode();
3627
		if ( ! self::is_active() && ! $is_offline_mode ) {
3628
			Jetpack_Connection_Banner::init();
3629
			/** Already documented in automattic/jetpack-connection::src/class-client.php */
3630
		} elseif ( ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) && ! apply_filters( 'jetpack_client_verify_ssl_certs', false ) ) {
3631
			// Upgrade: 1.1 -> 1.1.1
3632
			// Check and see if host can verify the Jetpack servers' SSL certificate
3633
			$args = array();
3634
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3635
		}
3636
3637
		Jetpack_Recommendations_Banner::init();
3638
3639
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3640
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3641
		}
3642
3643
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3644
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3645
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3646
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3647
3648
		if ( self::is_active() || $is_offline_mode ) {
3649
			// Artificially throw errors in certain specific cases during plugin activation.
3650
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3651
		}
3652
3653
		// Add custom column in wp-admin/users.php to show whether user is linked.
3654
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3655
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3656
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3657
	}
3658
3659
	function admin_body_class( $admin_body_class = '' ) {
3660
		$classes = explode( ' ', trim( $admin_body_class ) );
3661
3662
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3663
3664
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3665
		return " $admin_body_class ";
3666
	}
3667
3668
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3669
		return $admin_body_class . ' jetpack-pagestyles ';
3670
	}
3671
3672
	/**
3673
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3674
	 * This function artificially throws errors for such cases (per a specific list).
3675
	 *
3676
	 * @param string $plugin The activated plugin.
3677
	 */
3678
	function throw_error_on_activate_plugin( $plugin ) {
3679
		$active_modules = self::get_active_modules();
3680
3681
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3682
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3683
			$throw = false;
3684
3685
			// Try and make sure it really was the stats plugin
3686
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3687
				if ( 'stats.php' == basename( $plugin ) ) {
3688
					$throw = true;
3689
				}
3690
			} else {
3691
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3692
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3693
					$throw = true;
3694
				}
3695
			}
3696
3697
			if ( $throw ) {
3698
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3699
			}
3700
		}
3701
	}
3702
3703
	function intercept_plugin_error_scrape_init() {
3704
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3705
	}
3706
3707
	function intercept_plugin_error_scrape( $action, $result ) {
3708
		if ( ! $result ) {
3709
			return;
3710
		}
3711
3712
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3713
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3714
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3715
			}
3716
		}
3717
	}
3718
3719
	/**
3720
	 * Register the remote file upload request handlers, if needed.
3721
	 *
3722
	 * @access public
3723
	 */
3724
	public function add_remote_request_handlers() {
3725
		// Remote file uploads are allowed only via AJAX requests.
3726
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3727
			return;
3728
		}
3729
3730
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3731
		$remote_request_actions = array(
3732
			'jetpack_upload_file',
3733
			'jetpack_update_file',
3734
		);
3735
3736
		// phpcs:ignore WordPress.Security.NonceVerification
3737
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3738
			return;
3739
		}
3740
3741
		// Require Jetpack authentication for the remote file upload AJAX requests.
3742
		if ( ! $this->connection_manager ) {
3743
			$this->connection_manager = new Connection_Manager();
3744
		}
3745
3746
		$this->connection_manager->require_jetpack_authentication();
3747
3748
		// Register the remote file upload AJAX handlers.
3749
		foreach ( $remote_request_actions as $action ) {
3750
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3751
		}
3752
	}
3753
3754
	/**
3755
	 * Handler for Jetpack remote file uploads.
3756
	 *
3757
	 * @access public
3758
	 */
3759
	public function remote_request_handlers() {
3760
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3761
3762
		switch ( current_filter() ) {
3763
			case 'wp_ajax_nopriv_jetpack_upload_file':
3764
				$response = $this->upload_handler();
3765
				break;
3766
3767
			case 'wp_ajax_nopriv_jetpack_update_file':
3768
				$response = $this->upload_handler( true );
3769
				break;
3770
			default:
3771
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_handler'.

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

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

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

Loading history...
3772
				break;
3773
		}
3774
3775
		if ( ! $response ) {
3776
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
3777
		}
3778
3779
		if ( is_wp_error( $response ) ) {
3780
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<WP_Error>.

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

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

Loading history...
3781
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

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

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

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

Loading history...
3783
3784
			if ( ! is_int( $status_code ) ) {
3785
				$status_code = 400;
3786
			}
3787
3788
			status_header( $status_code );
3789
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3790
		}
3791
3792
		status_header( 200 );
3793
		if ( true === $response ) {
3794
			exit;
3795
		}
3796
3797
		die( json_encode( (object) $response ) );
3798
	}
3799
3800
	/**
3801
	 * Uploads a file gotten from the global $_FILES.
3802
	 * If `$update_media_item` is true and `post_id` is defined
3803
	 * the attachment file of the media item (gotten through of the post_id)
3804
	 * will be updated instead of add a new one.
3805
	 *
3806
	 * @param  boolean $update_media_item - update media attachment
3807
	 * @return array - An array describing the uploadind files process
3808
	 */
3809
	function upload_handler( $update_media_item = false ) {
3810
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3811
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 405.

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

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

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

Loading history...
3812
		}
3813
3814
		$user = wp_authenticate( '', '' );
3815
		if ( ! $user || is_wp_error( $user ) ) {
3816
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 403.

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

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

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

Loading history...
3817
		}
3818
3819
		wp_set_current_user( $user->ID );
3820
3821
		if ( ! current_user_can( 'upload_files' ) ) {
3822
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

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

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

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

Loading history...
3823
		}
3824
3825
		if ( empty( $_FILES ) ) {
3826
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

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

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

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

Loading history...
3827
		}
3828
3829
		foreach ( array_keys( $_FILES ) as $files_key ) {
3830
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3831
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_hmac'.

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

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

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

Loading history...
3832
			}
3833
		}
3834
3835
		$media_keys = array_keys( $_FILES['media'] );
3836
3837
		$token = ( new Tokens() )->get_access_token( get_current_user_id() );
3838
		if ( ! $token || is_wp_error( $token ) ) {
3839
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
3840
		}
3841
3842
		$uploaded_files = array();
3843
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3844
		unset( $GLOBALS['post'] );
3845
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3846
			$file = array();
3847
			foreach ( $media_keys as $media_key ) {
3848
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3849
			}
3850
3851
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3852
3853
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3854
			if ( $hmac_provided !== $hmac_file ) {
3855
				$uploaded_files[ $index ] = (object) array(
3856
					'error'             => 'invalid_hmac',
3857
					'error_description' => 'The corresponding HMAC for this file does not match',
3858
				);
3859
				continue;
3860
			}
3861
3862
			$_FILES['.jetpack.upload.'] = $file;
3863
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3864
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3865
				$post_id = 0;
3866
			}
3867
3868
			if ( $update_media_item ) {
3869
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3870
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_input'.

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

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

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

Loading history...
3871
				}
3872
3873
				$media_array = $_FILES['media'];
3874
3875
				$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...
3876
				$file_array['type']     = $media_array['type'][0];
3877
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3878
				$file_array['error']    = $media_array['error'][0];
3879
				$file_array['size']     = $media_array['size'][0];
3880
3881
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3882
3883
				if ( is_wp_error( $edited_media_item ) ) {
3884
					return $edited_media_item;
3885
				}
3886
3887
				$response = (object) array(
3888
					'id'   => (string) $post_id,
3889
					'file' => (string) $edited_media_item->post_title,
3890
					'url'  => (string) wp_get_attachment_url( $post_id ),
3891
					'type' => (string) $edited_media_item->post_mime_type,
3892
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3893
				);
3894
3895
				return (array) array( $response );
3896
			}
3897
3898
			$attachment_id = media_handle_upload(
3899
				'.jetpack.upload.',
3900
				$post_id,
3901
				array(),
3902
				array(
3903
					'action' => 'jetpack_upload_file',
3904
				)
3905
			);
3906
3907
			if ( ! $attachment_id ) {
3908
				$uploaded_files[ $index ] = (object) array(
3909
					'error'             => 'unknown',
3910
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3911
				);
3912
			} elseif ( is_wp_error( $attachment_id ) ) {
3913
				$uploaded_files[ $index ] = (object) array(
3914
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3915
					'error_description' => $attachment_id->get_error_message(),
3916
				);
3917
			} else {
3918
				$attachment               = get_post( $attachment_id );
3919
				$uploaded_files[ $index ] = (object) array(
3920
					'id'   => (string) $attachment_id,
3921
					'file' => $attachment->post_title,
3922
					'url'  => wp_get_attachment_url( $attachment_id ),
3923
					'type' => $attachment->post_mime_type,
3924
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3925
				);
3926
				// Zip files uploads are not supported unless they are done for installation purposed
3927
				// lets delete them in case something goes wrong in this whole process
3928
				if ( 'application/zip' === $attachment->post_mime_type ) {
3929
					// Schedule a cleanup for 2 hours from now in case of failed install.
3930
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3931
				}
3932
			}
3933
		}
3934
		if ( ! is_null( $global_post ) ) {
3935
			$GLOBALS['post'] = $global_post;
3936
		}
3937
3938
		return $uploaded_files;
3939
	}
3940
3941
	/**
3942
	 * Add help to the Jetpack page
3943
	 *
3944
	 * @since Jetpack (1.2.3)
3945
	 * @return false if not the Jetpack page
3946
	 */
3947
	function admin_help() {
3948
		$current_screen = get_current_screen();
3949
3950
		// Overview
3951
		$current_screen->add_help_tab(
3952
			array(
3953
				'id'      => 'home',
3954
				'title'   => __( 'Home', 'jetpack' ),
3955
				'content' =>
3956
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3957
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3958
					'<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>',
3959
			)
3960
		);
3961
3962
		// Screen Content
3963
		if ( current_user_can( 'manage_options' ) ) {
3964
			$current_screen->add_help_tab(
3965
				array(
3966
					'id'      => 'settings',
3967
					'title'   => __( 'Settings', 'jetpack' ),
3968
					'content' =>
3969
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3970
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3971
						'<ol>' .
3972
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3973
							'<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>' .
3974
						'</ol>' .
3975
						'<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>',
3976
				)
3977
			);
3978
		}
3979
3980
		// Help Sidebar
3981
		$support_url = Redirect::get_url( 'jetpack-support' );
3982
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3983
		$current_screen->set_help_sidebar(
3984
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3985
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3986
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3987
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3988
		);
3989
	}
3990
3991
	function admin_menu_css() {
3992
		wp_enqueue_style( 'jetpack-icons' );
3993
	}
3994
3995
	function admin_menu_order() {
3996
		return true;
3997
	}
3998
3999
	function jetpack_menu_order( $menu_order ) {
4000
		$jp_menu_order = array();
4001
4002
		foreach ( $menu_order as $index => $item ) {
4003
			if ( $item != 'jetpack' ) {
4004
				$jp_menu_order[] = $item;
4005
			}
4006
4007
			if ( $index == 0 ) {
4008
				$jp_menu_order[] = 'jetpack';
4009
			}
4010
		}
4011
4012
		return $jp_menu_order;
4013
	}
4014
4015
	function admin_banner_styles() {
4016
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4017
4018
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4019
			wp_register_style(
4020
				'jetpack-dops-style',
4021
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4022
				array(),
4023
				JETPACK__VERSION
4024
			);
4025
		}
4026
4027
		wp_enqueue_style(
4028
			'jetpack',
4029
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4030
			array( 'jetpack-dops-style' ),
4031
			JETPACK__VERSION . '-20121016'
4032
		);
4033
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4034
		wp_style_add_data( 'jetpack', 'suffix', $min );
4035
	}
4036
4037
	function plugin_action_links( $actions ) {
4038
4039
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4040
4041
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
4042
			return array_merge(
4043
				$jetpack_home,
4044
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4045
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4046
				$actions
4047
			);
4048
		}
4049
4050
		return array_merge( $jetpack_home, $actions );
4051
	}
4052
4053
	/**
4054
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4055
	 *
4056
	 * @param string $hook The current admin page.
4057
	 *
4058
	 * @return void
4059
	 */
4060
	public function deactivate_dialog( $hook ) {
4061
		if (
4062
			'plugins.php' === $hook
4063
			&& self::is_active()
4064
		) {
4065
4066
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4067
4068
			if ( count( $active_plugins_using_connection ) > 1 ) {
4069
4070
				add_thickbox();
4071
4072
				wp_register_script(
4073
					'jp-tracks',
4074
					'//stats.wp.com/w.js',
4075
					array(),
4076
					gmdate( 'YW' ),
4077
					true
4078
				);
4079
4080
				wp_register_script(
4081
					'jp-tracks-functions',
4082
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4083
					array( 'jp-tracks' ),
4084
					JETPACK__VERSION,
4085
					false
4086
				);
4087
4088
				wp_enqueue_script(
4089
					'jetpack-deactivate-dialog-js',
4090
					Assets::get_file_url_for_environment(
4091
						'_inc/build/jetpack-deactivate-dialog.min.js',
4092
						'_inc/jetpack-deactivate-dialog.js'
4093
					),
4094
					array( 'jquery', 'jp-tracks-functions' ),
4095
					JETPACK__VERSION,
4096
					true
4097
				);
4098
4099
				wp_localize_script(
4100
					'jetpack-deactivate-dialog-js',
4101
					'deactivate_dialog',
4102
					array(
4103
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4104
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4105
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4106
					)
4107
				);
4108
4109
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4110
4111
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4112
			}
4113
		}
4114
	}
4115
4116
	/**
4117
	 * Outputs the content of the deactivation modal
4118
	 *
4119
	 * @return void
4120
	 */
4121
	public function deactivate_dialog_content() {
4122
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4123
		unset( $active_plugins_using_connection['jetpack'] );
4124
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Bug introduced by
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4122 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...
4125
	}
4126
4127
	/**
4128
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4129
	 *
4130
	 * @param string $login_url The wp-login URL.
4131
	 * @param string $redirect  URL to redirect users after logging in.
4132
	 * @since Jetpack 8.4
4133
	 * @return string
4134
	 */
4135
	public function login_url( $login_url, $redirect ) {
4136
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4137
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4138
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4139
		}
4140
		return $login_url;
4141
	}
4142
4143
	/**
4144
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4145
	 *
4146
	 * @since Jetpack 8.4
4147
	 */
4148
	public function login_init() {
4149
		// phpcs:ignore WordPress.Security.NonceVerification
4150
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4151
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4152
			wp_safe_redirect(
4153
				add_query_arg(
4154
					array(
4155
						'forceInstall' => 1,
4156
						'url'          => rawurlencode( get_site_url() ),
4157
					),
4158
					// @todo provide way to go to specific calypso env.
4159
					self::get_calypso_host() . 'jetpack/connect'
4160
				)
4161
			);
4162
			exit;
4163
		}
4164
	}
4165
4166
	/*
4167
	 * Registration flow:
4168
	 * 1 - ::admin_page_load() action=register
4169
	 * 2 - ::try_registration()
4170
	 * 3 - ::register()
4171
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4172
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4173
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4174
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4175
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4176
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4177
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4178
	 *       jetpack_id, jetpack_secret, jetpack_public
4179
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4180
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4181
	 * 5 - user logs in with WP.com account
4182
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4183
	 *		- Manager::authorize()
4184
	 *		- Manager::get_token()
4185
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4186
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4187
	 *			- which responds with access_token, token_type, scope
4188
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4189
	 *		- Jetpack::activate_default_modules()
4190
	 *     		- Deactivates deprecated plugins
4191
	 *     		- Activates all default modules
4192
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4193
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4194
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4195
	 *     Done!
4196
	 */
4197
4198
	/**
4199
	 * Handles the page load events for the Jetpack admin page
4200
	 */
4201
	function admin_page_load() {
4202
		$error = false;
4203
4204
		// Make sure we have the right body class to hook stylings for subpages off of.
4205
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4206
4207
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4208
			// Should only be used in intermediate redirects to preserve state across redirects
4209
			self::restate();
4210
		}
4211
4212
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4213
			// @todo: Add validation against a known allowed list.
4214
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4215
			// User clicked in the iframe to link their accounts
4216
			if ( ! self::connection()->is_user_connected() ) {
4217
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4218
4219
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4220
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4221
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4222
4223
				if ( isset( $_GET['notes_iframe'] ) ) {
4224
					$connect_url .= '&notes_iframe';
4225
				}
4226
				wp_redirect( $connect_url );
4227
				exit;
4228
			} else {
4229
				if ( ! isset( $_GET['calypso_env'] ) ) {
4230
					self::state( 'message', 'already_authorized' );
4231
					wp_safe_redirect( self::admin_url() );
4232
					exit;
4233
				} else {
4234
					$connect_url  = $this->build_connect_url( true, false, $from );
4235
					$connect_url .= '&already_authorized=true';
4236
					wp_redirect( $connect_url );
4237
					exit;
4238
				}
4239
			}
4240
		}
4241
4242
		if ( isset( $_GET['action'] ) ) {
4243
			switch ( $_GET['action'] ) {
4244
				case 'authorize_redirect':
4245
					self::log( 'authorize_redirect' );
4246
4247
					add_filter(
4248
						'allowed_redirect_hosts',
4249
						function ( $domains ) {
4250
							$domains[] = 'jetpack.com';
4251
							$domains[] = 'jetpack.wordpress.com';
4252
							$domains[] = 'wordpress.com';
4253
							$domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4254
							return array_unique( $domains );
4255
						}
4256
					);
4257
4258
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
4259
					$dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4260
4261
					if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4262
						// The destination URL is missing or invalid, nothing to do here.
4263
						exit;
4264
					}
4265
4266
					if ( static::is_active() && static::connection()->is_user_connected() ) {
4267
						// The user is either already connected, or finished the connection process.
4268
						wp_safe_redirect( $dest_url );
4269
						exit;
4270
					} elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4271
						// The user decided not to proceed with setting up the connection.
4272
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4273
						exit;
4274
					}
4275
4276
					$redirect_url = self::admin_url(
4277
						array(
4278
							'page'     => 'jetpack',
4279
							'action'   => 'authorize_redirect',
4280
							'dest_url' => rawurlencode( $dest_url ),
4281
							'done'     => '1',
4282
						)
4283
					);
4284
4285
					wp_safe_redirect( static::build_authorize_url( $redirect_url ) );
0 ignored issues
show
Documentation introduced by
$redirect_url is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4286
					exit;
4287
				case 'authorize':
4288
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4289
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4290
					exit;
4291
				case 'register':
4292
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4293
						$error = 'cheatin';
4294
						break;
4295
					}
4296
					check_admin_referer( 'jetpack-register' );
4297
					self::log( 'register' );
4298
					self::maybe_set_version_option();
4299
					$registered = self::try_registration();
4300
					if ( is_wp_error( $registered ) ) {
4301
						$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

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

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

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

Loading history...
4304
4305
						/**
4306
						 * Jetpack registration Error.
4307
						 *
4308
						 * @since 7.5.0
4309
						 *
4310
						 * @param string|int $error The error code.
4311
						 * @param \WP_Error $registered The error object.
4312
						 */
4313
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4314
						break;
4315
					}
4316
4317
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4318
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4319
4320
					/**
4321
					 * Jetpack registration Success.
4322
					 *
4323
					 * @since 7.5.0
4324
					 *
4325
					 * @param string $from 'from' GET parameter;
4326
					 */
4327
					do_action( 'jetpack_connection_register_success', $from );
4328
4329
					$url = $this->build_connect_url( true, $redirect, $from );
4330
4331
					if ( ! empty( $_GET['onboarding'] ) ) {
4332
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4333
					}
4334
4335
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4336
						$url = add_query_arg( 'auth_approved', 'true', $url );
4337
					}
4338
4339
					wp_redirect( $url );
4340
					exit;
4341
				case 'activate':
4342
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4343
						$error = 'cheatin';
4344
						break;
4345
					}
4346
4347
					$module = stripslashes( $_GET['module'] );
4348
					check_admin_referer( "jetpack_activate-$module" );
4349
					self::log( 'activate', $module );
4350
					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...
4351
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4352
					}
4353
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4354
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4355
					exit;
4356
				case 'activate_default_modules':
4357
					check_admin_referer( 'activate_default_modules' );
4358
					self::log( 'activate_default_modules' );
4359
					self::restate();
4360
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4361
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4362
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4363
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4364
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4365
					exit;
4366 View Code Duplication
				case 'disconnect':
4367
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4368
						$error = 'cheatin';
4369
						break;
4370
					}
4371
4372
					check_admin_referer( 'jetpack-disconnect' );
4373
					self::log( 'disconnect' );
4374
					self::disconnect();
4375
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4376
					exit;
4377 View Code Duplication
				case 'reconnect':
4378
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4379
						$error = 'cheatin';
4380
						break;
4381
					}
4382
4383
					check_admin_referer( 'jetpack-reconnect' );
4384
					self::log( 'reconnect' );
4385
					self::disconnect();
4386
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4387
					exit;
4388 View Code Duplication
				case 'deactivate':
4389
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4390
						$error = 'cheatin';
4391
						break;
4392
					}
4393
4394
					$modules = stripslashes( $_GET['module'] );
4395
					check_admin_referer( "jetpack_deactivate-$modules" );
4396
					foreach ( explode( ',', $modules ) as $module ) {
4397
						self::log( 'deactivate', $module );
4398
						self::deactivate_module( $module );
4399
						self::state( 'message', 'module_deactivated' );
4400
					}
4401
					self::state( 'module', $modules );
4402
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4403
					exit;
4404
				case 'unlink':
4405
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4406
					check_admin_referer( 'jetpack-unlink' );
4407
					self::log( 'unlink' );
4408
					$this->connection_manager->disconnect_user();
4409
					self::state( 'message', 'unlinked' );
4410
					if ( 'sub-unlink' == $redirect ) {
4411
						wp_safe_redirect( admin_url() );
4412
					} else {
4413
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4414
					}
4415
					exit;
4416
				case 'onboard':
4417
					if ( ! current_user_can( 'manage_options' ) ) {
4418
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4419
					} else {
4420
						self::create_onboarding_token();
4421
						$url = $this->build_connect_url( true );
4422
4423
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4424
							$url = add_query_arg( 'onboarding', $token, $url );
4425
						}
4426
4427
						$calypso_env = $this->get_calypso_env();
4428
						if ( ! empty( $calypso_env ) ) {
4429
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4430
						}
4431
4432
						wp_redirect( $url );
4433
						exit;
4434
					}
4435
					exit;
4436
				default:
4437
					/**
4438
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4439
					 *
4440
					 * @since 2.6.0
4441
					 *
4442
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4443
					 */
4444
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4445
			}
4446
		}
4447
4448
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4449
			self::activate_new_modules( true );
4450
		}
4451
4452
		$message_code = self::state( 'message' );
4453
		if ( self::state( 'optin-manage' ) ) {
4454
			$activated_manage = $message_code;
4455
			$message_code     = 'jetpack-manage';
4456
		}
4457
4458
		switch ( $message_code ) {
4459
			case 'jetpack-manage':
4460
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4461
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4462
				$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>';
4463
				if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

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

Loading history...
4660
			: 'should-not-happen';
4661
4662
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4663
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4664
			// No need to update the option if we already have
4665
			// this code stored.
4666
			return;
4667
		}
4668
		$xmlrpc_errors[ $code ] = true;
4669
4670
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4671
	}
4672
4673
	/**
4674
	 * Initialize the jetpack stats instance only when needed
4675
	 *
4676
	 * @return void
4677
	 */
4678
	private function initialize_stats() {
4679
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4680
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4681
		}
4682
	}
4683
4684
	/**
4685
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4686
	 */
4687
	function stat( $group, $detail ) {
4688
		$this->initialize_stats();
4689
		$this->a8c_mc_stats_instance->add( $group, $detail );
4690
4691
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4692
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4693
	}
4694
4695
	/**
4696
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4697
	 */
4698
	function do_stats( $method = '' ) {
4699
		$this->initialize_stats();
4700
		if ( 'server_side' === $method ) {
4701
			$this->a8c_mc_stats_instance->do_server_side_stats();
4702
		} else {
4703
			$this->a8c_mc_stats_instance->do_stats();
4704
		}
4705
4706
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4707
		$this->stats = array();
4708
	}
4709
4710
	/**
4711
	 * Runs stats code for a one-off, server-side.
4712
	 *
4713
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4714
	 *
4715
	 * @return bool If it worked.
4716
	 */
4717
	static function do_server_side_stat( $args ) {
4718
		$url                   = self::build_stats_url( $args );
4719
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4720
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4721
	}
4722
4723
	/**
4724
	 * Builds the stats url.
4725
	 *
4726
	 * @param $args array|string The arguments to append to the URL.
4727
	 *
4728
	 * @return string The URL to be pinged.
4729
	 */
4730
	static function build_stats_url( $args ) {
4731
4732
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4733
		return $a8c_mc_stats_instance->build_stats_url( $args );
4734
4735
	}
4736
4737
	/**
4738
	 * Builds a URL to the Jetpack connection auth page
4739
	 *
4740
	 * @since 3.9.5
4741
	 *
4742
	 * @param bool        $raw If true, URL will not be escaped.
4743
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4744
	 *                              If string, will be a custom redirect.
4745
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4746
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4747
	 *
4748
	 * @return string Connect URL
4749
	 */
4750
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4751
		$site_id    = Jetpack_Options::get_option( 'id' );
4752
		$blog_token = ( new Tokens() )->get_access_token();
4753
4754
		if ( $register || ! $blog_token || ! $site_id ) {
4755
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4756
4757
			if ( ! empty( $redirect ) ) {
4758
				$url = add_query_arg(
4759
					'redirect',
4760
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4761
					$url
4762
				);
4763
			}
4764
4765
			if ( is_network_admin() ) {
4766
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4767
			}
4768
4769
			$calypso_env = self::get_calypso_env();
4770
4771
			if ( ! empty( $calypso_env ) ) {
4772
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4773
			}
4774
		} else {
4775
4776
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4777
			// because otherwise this logic can get us in to a loop.
4778
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4779
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4780
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4781
4782
				$response = Client::wpcom_json_api_request_as_blog(
4783
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4784
					'1.1'
4785
				);
4786
4787
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4788
4789
					// Generating a register URL instead to refresh the existing token
4790
					return $this->build_connect_url( $raw, $redirect, $from, true );
4791
				}
4792
			}
4793
4794
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4750 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...
4795
		}
4796
4797
		if ( $from ) {
4798
			$url = add_query_arg( 'from', $from, $url );
4799
		}
4800
4801
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4802
		/**
4803
		 * Filter the URL used when connecting a user to a WordPress.com account.
4804
		 *
4805
		 * @since 8.1.0
4806
		 *
4807
		 * @param string $url Connection URL.
4808
		 * @param bool   $raw If true, URL will not be escaped.
4809
		 */
4810
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $raw.

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

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

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

Loading history...
4811
	}
4812
4813
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4814
4815
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4816
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4817
4818
		if ( $iframe ) {
4819
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4820
		}
4821
4822
		$c8n = self::connection();
4823
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
Documentation introduced by
$redirect is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4824
4825
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4826
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4827
4828
		if ( $iframe ) {
4829
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4830
		}
4831
4832
		/**
4833
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4834
		 *
4835
		 * @since 8.9.0
4836
		 *
4837
		 * @param string $url Connection URL.
4838
		 */
4839
		return apply_filters( 'jetpack_build_authorize_url', $url );
4840
	}
4841
4842
	/**
4843
	 * Filters the connection URL parameter array.
4844
	 *
4845
	 * @param array $args default URL parameters used by the package.
4846
	 * @return array the modified URL arguments array.
4847
	 */
4848
	public static function filter_connect_request_body( $args ) {
4849
		if (
4850
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4851
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4852
		) {
4853
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4854
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4855
				? $gp_locale->slug
4856
				: '';
4857
		}
4858
4859
		$tracking        = new Tracking();
4860
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4861
4862
		$args = array_merge(
4863
			$args,
4864
			array(
4865
				'_ui' => $tracks_identity['_ui'],
4866
				'_ut' => $tracks_identity['_ut'],
4867
			)
4868
		);
4869
4870
		$calypso_env = self::get_calypso_env();
4871
4872
		if ( ! empty( $calypso_env ) ) {
4873
			$args['calypso_env'] = $calypso_env;
4874
		}
4875
4876
		return $args;
4877
	}
4878
4879
	/**
4880
	 * Filters the URL that will process the connection data. It can be different from the URL
4881
	 * that we send the user to after everything is done.
4882
	 *
4883
	 * @param String $processing_url the default redirect URL used by the package.
4884
	 * @return String the modified URL.
4885
	 *
4886
	 * @deprecated since Jetpack 9.5.0
4887
	 */
4888
	public static function filter_connect_processing_url( $processing_url ) {
4889
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4890
4891
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4892
		return $processing_url;
4893
	}
4894
4895
	/**
4896
	 * Filters the redirection URL that is used for connect requests. The redirect
4897
	 * URL should return the user back to the Jetpack console.
4898
	 *
4899
	 * @param String $redirect the default redirect URL used by the package.
4900
	 * @return String the modified URL.
4901
	 */
4902
	public static function filter_connect_redirect_url( $redirect ) {
4903
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4904
		$redirect           = $redirect
4905
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4906
			: $jetpack_admin_page;
4907
4908
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4909
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4910
		}
4911
4912
		return $redirect;
4913
	}
4914
4915
	/**
4916
	 * This action fires at the beginning of the Manager::authorize method.
4917
	 */
4918
	public static function authorize_starting() {
4919
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4920
		// Checking if site has been active/connected previously before recording unique connection.
4921
		if ( ! $jetpack_unique_connection ) {
4922
			// jetpack_unique_connection option has never been set.
4923
			$jetpack_unique_connection = array(
4924
				'connected'    => 0,
4925
				'disconnected' => 0,
4926
				'version'      => '3.6.1',
4927
			);
4928
4929
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4930
4931
			// Track unique connection.
4932
			$jetpack = self::init();
4933
4934
			$jetpack->stat( 'connections', 'unique-connection' );
4935
			$jetpack->do_stats( 'server_side' );
4936
		}
4937
4938
		// Increment number of times connected.
4939
		$jetpack_unique_connection['connected'] += 1;
4940
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4941
	}
4942
4943
	/**
4944
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4945
	 * linked.
4946
	 */
4947
	public static function authorize_ending_linked() {
4948
		// Don't activate anything since we are just connecting a user.
4949
		self::state( 'message', 'linked' );
4950
	}
4951
4952
	/**
4953
	 * This action fires at the end of the Manager::authorize method when the master user is
4954
	 * authorized.
4955
	 *
4956
	 * @param array $data The request data.
4957
	 */
4958
	public static function authorize_ending_authorized( $data ) {
4959
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4960
		self::invalidate_onboarding_token();
4961
4962
		// If redirect_uri is SSO, ensure SSO module is enabled.
4963
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4964
4965
		/** This filter is documented in class.jetpack-cli.php */
4966
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4967
4968
		$activate_sso = (
4969
			isset( $redirect_options['action'] ) &&
4970
			'jetpack-sso' === $redirect_options['action'] &&
4971
			$jetpack_start_enable_sso
4972
		);
4973
4974
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4975
4976
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4977
	}
4978
4979
	/**
4980
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4981
	 * reconnect process is completed.
4982
	 * Note that this currently only happens when we don't need the user to re-authorize
4983
	 * their WP.com account, eg in cases where we are restoring a connection with
4984
	 * unhealthy blog token.
4985
	 */
4986
	public static function reconnection_completed() {
4987
		self::state( 'message', 'reconnection_completed' );
4988
	}
4989
4990
	/**
4991
	 * Get our assumed site creation date.
4992
	 * Calculated based on the earlier date of either:
4993
	 * - Earliest admin user registration date.
4994
	 * - Earliest date of post of any post type.
4995
	 *
4996
	 * @since 7.2.0
4997
	 * @deprecated since 7.8.0
4998
	 *
4999
	 * @return string Assumed site creation date and time.
5000
	 */
5001
	public static function get_assumed_site_creation_date() {
5002
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5003
		return self::connection()->get_assumed_site_creation_date();
5004
	}
5005
5006 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5007
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5008
5009
		if ( $activation_source_name ) {
5010
			$args['_as'] = urlencode( $activation_source_name );
5011
		}
5012
5013
		if ( $activation_source_keyword ) {
5014
			$args['_ak'] = urlencode( $activation_source_keyword );
5015
		}
5016
	}
5017
5018
	function build_reconnect_url( $raw = false ) {
5019
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5020
		return $raw ? $url : esc_url( $url );
5021
	}
5022
5023
	public static function admin_url( $args = null ) {
5024
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
Documentation introduced by
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

Loading history...
5320
	 * @param Integer $exp     Expiration time in seconds.
5321
	 * @return array
5322
	 */
5323
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5324
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5325
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5326
	}
5327
5328
	public static function get_secrets( $action, $user_id ) {
5329
		$secrets = ( new Secrets() )->get( $action, $user_id );
5330
5331
		if ( Secrets::SECRETS_MISSING === $secrets ) {
5332
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

Loading history...
5333
		}
5334
5335
		if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5336
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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

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

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

Loading history...
5337
		}
5338
5339
		return $secrets;
5340
	}
5341
5342
	/**
5343
	 * Builds the timeout limit for queries talking with the wpcom servers.
5344
	 *
5345
	 * Based on local php max_execution_time in php.ini
5346
	 *
5347
	 * @since 2.6
5348
	 * @return int
5349
	 * @deprecated
5350
	 **/
5351
	public function get_remote_query_timeout_limit() {
5352
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5353
		return self::get_max_execution_time();
5354
	}
5355
5356
	/**
5357
	 * Builds the timeout limit for queries talking with the wpcom servers.
5358
	 *
5359
	 * Based on local php max_execution_time in php.ini
5360
	 *
5361
	 * @since 5.4
5362
	 * @return int
5363
	 **/
5364
	public static function get_max_execution_time() {
5365
		$timeout = (int) ini_get( 'max_execution_time' );
5366
5367
		// Ensure exec time set in php.ini
5368
		if ( ! $timeout ) {
5369
			$timeout = 30;
5370
		}
5371
		return $timeout;
5372
	}
5373
5374
	/**
5375
	 * Sets a minimum request timeout, and returns the current timeout
5376
	 *
5377
	 * @since 5.4
5378
	 **/
5379 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5380
		$timeout = self::get_max_execution_time();
5381
		if ( $timeout < $min_timeout ) {
5382
			$timeout = $min_timeout;
5383
			set_time_limit( $timeout );
5384
		}
5385
		return $timeout;
5386
	}
5387
5388
	/**
5389
	 * Takes the response from the Jetpack register new site endpoint and
5390
	 * verifies it worked properly.
5391
	 *
5392
	 * @since 2.6
5393
	 * @deprecated since 7.7.0
5394
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5395
	 **/
5396
	public function validate_remote_register_response() {
5397
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5398
	}
5399
5400
	/**
5401
	 * @return bool|WP_Error
5402
	 */
5403
	public static function register() {
5404
		$tracking = new Tracking();
5405
		$tracking->record_user_event( 'jpc_register_begin' );
5406
5407
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5408
5409
		$connection   = self::connection();
5410
		$registration = $connection->register();
5411
5412
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5413
5414
		if ( ! $registration || is_wp_error( $registration ) ) {
5415
			return $registration;
5416
		}
5417
5418
		return true;
5419
	}
5420
5421
	/**
5422
	 * Filters the registration request body to include tracking properties.
5423
	 *
5424
	 * @param array $properties
5425
	 * @return array amended properties.
5426
	 */
5427 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5428
		$tracking        = new Tracking();
5429
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5430
5431
		return array_merge(
5432
			$properties,
5433
			array(
5434
				'_ui' => $tracks_identity['_ui'],
5435
				'_ut' => $tracks_identity['_ut'],
5436
			)
5437
		);
5438
	}
5439
5440
	/**
5441
	 * Filters the token request body to include tracking properties.
5442
	 *
5443
	 * @param array $properties
5444
	 * @return array amended properties.
5445
	 */
5446 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5447
		$tracking        = new Tracking();
5448
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5449
5450
		return array_merge(
5451
			$properties,
5452
			array(
5453
				'_ui' => $tracks_identity['_ui'],
5454
				'_ut' => $tracks_identity['_ut'],
5455
			)
5456
		);
5457
	}
5458
5459
	/**
5460
	 * If the db version is showing something other that what we've got now, bump it to current.
5461
	 *
5462
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5463
	 */
5464
	public static function maybe_set_version_option() {
5465
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5466
		if ( JETPACK__VERSION != $version ) {
5467
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5468
5469
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5470
				/** This action is documented in class.jetpack.php */
5471
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5472
			}
5473
5474
			return true;
5475
		}
5476
		return false;
5477
	}
5478
5479
	/* Client Server API */
5480
5481
	/**
5482
	 * Loads the Jetpack XML-RPC client.
5483
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5484
	 *
5485
	 * @deprecated since 7.7.0
5486
	 */
5487
	public static function load_xml_rpc_client() {
5488
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5489
	}
5490
5491
	/**
5492
	 * Resets the saved authentication state in between testing requests.
5493
	 *
5494
	 * @deprecated since 8.9.0
5495
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5496
	 */
5497
	public function reset_saved_auth_state() {
5498
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5499
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5500
	}
5501
5502
	/**
5503
	 * Verifies the signature of the current request.
5504
	 *
5505
	 * @deprecated since 7.7.0
5506
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5507
	 *
5508
	 * @return false|array
5509
	 */
5510
	public function verify_xml_rpc_signature() {
5511
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5512
		return self::connection()->verify_xml_rpc_signature();
5513
	}
5514
5515
	/**
5516
	 * Verifies the signature of the current request.
5517
	 *
5518
	 * This function has side effects and should not be used. Instead,
5519
	 * use the memoized version `->verify_xml_rpc_signature()`.
5520
	 *
5521
	 * @deprecated since 7.7.0
5522
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5523
	 * @internal
5524
	 */
5525
	private function internal_verify_xml_rpc_signature() {
5526
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5527
	}
5528
5529
	/**
5530
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5531
	 *
5532
	 * @deprecated since 7.7.0
5533
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5534
	 *
5535
	 * @param \WP_User|mixed $user     User object if authenticated.
5536
	 * @param string         $username Username.
5537
	 * @param string         $password Password string.
5538
	 * @return \WP_User|mixed Authenticated user or error.
5539
	 */
5540 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5541
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5542
5543
		if ( ! $this->connection_manager ) {
5544
			$this->connection_manager = new Connection_Manager();
5545
		}
5546
5547
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5548
	}
5549
5550
	/**
5551
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5552
	 * Uses the existing XMLRPC request signing implementation.
5553
	 *
5554
	 * @deprecated since 8.9.0
5555
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5556
	 */
5557
	function wp_rest_authenticate( $user ) {
5558
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5559
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5560
	}
5561
5562
	/**
5563
	 * Report authentication status to the WP REST API.
5564
	 *
5565
	 * @deprecated since 8.9.0
5566
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5567
	 *
5568
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5569
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5570
	 */
5571
	public function wp_rest_authentication_errors( $value ) {
5572
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5573
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5574
	}
5575
5576
	/**
5577
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5578
	 * Capture it here so we can verify the signature later.
5579
	 *
5580
	 * @deprecated since 7.7.0
5581
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5582
	 *
5583
	 * @param array $methods XMLRPC methods.
5584
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5585
	 */
5586 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5587
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5588
5589
		if ( ! $this->connection_manager ) {
5590
			$this->connection_manager = new Connection_Manager();
5591
		}
5592
5593
		return $this->connection_manager->xmlrpc_methods( $methods );
5594
	}
5595
5596
	/**
5597
	 * Register additional public XMLRPC methods.
5598
	 *
5599
	 * @deprecated since 7.7.0
5600
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5601
	 *
5602
	 * @param array $methods Public XMLRPC methods.
5603
	 * @return array Public XMLRPC methods, with the getOptions one.
5604
	 */
5605 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5606
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5607
5608
		if ( ! $this->connection_manager ) {
5609
			$this->connection_manager = new Connection_Manager();
5610
		}
5611
5612
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5613
	}
5614
5615
	/**
5616
	 * Handles a getOptions XMLRPC method call.
5617
	 *
5618
	 * @deprecated since 7.7.0
5619
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5620
	 *
5621
	 * @param array $args method call arguments.
5622
	 * @return array an amended XMLRPC server options array.
5623
	 */
5624 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5625
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5626
5627
		if ( ! $this->connection_manager ) {
5628
			$this->connection_manager = new Connection_Manager();
5629
		}
5630
5631
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

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

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

Loading history...
5632
	}
5633
5634
	/**
5635
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5636
	 *
5637
	 * @deprecated since 7.7.0
5638
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5639
	 *
5640
	 * @param array $options Standard Core options.
5641
	 * @return array Amended options.
5642
	 */
5643 View Code Duplication
	public function xmlrpc_options( $options ) {
5644
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5645
5646
		if ( ! $this->connection_manager ) {
5647
			$this->connection_manager = new Connection_Manager();
5648
		}
5649
5650
		return $this->connection_manager->xmlrpc_options( $options );
5651
	}
5652
5653
	/**
5654
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5655
	 * SET: state( $key, $value );
5656
	 * GET: $value = state( $key );
5657
	 *
5658
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

Loading history...
5660
	 * @param bool   $restate private
5661
	 */
5662
	public static function state( $key = null, $value = null, $restate = false ) {
5663
		static $state = array();
5664
		static $path, $domain;
5665
		if ( ! isset( $path ) ) {
5666
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5667
			$admin_url = self::admin_url();
5668
			$bits      = wp_parse_url( $admin_url );
5669
5670
			if ( is_array( $bits ) ) {
5671
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5672
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5673
			} else {
5674
				$path = $domain = null;
5675
			}
5676
		}
5677
5678
		// Extract state from cookies and delete cookies
5679
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5680
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5681
			unset( $_COOKIE['jetpackState'] );
5682
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
Bug introduced by
The expression $yum of type string|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
5683
				if ( strlen( $v ) ) {
5684
					$state[ $k ] = $v;
5685
				}
5686
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5687
			}
5688
		}
5689
5690
		if ( $restate ) {
5691
			foreach ( $state as $k => $v ) {
5692
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5693
			}
5694
			return;
5695
		}
5696
5697
		// Get a state variable.
5698
		if ( isset( $key ) && ! isset( $value ) ) {
5699
			if ( array_key_exists( $key, $state ) ) {
5700
				return $state[ $key ];
5701
			}
5702
			return null;
5703
		}
5704
5705
		// Set a state variable.
5706
		if ( isset( $key ) && isset( $value ) ) {
5707
			if ( is_array( $value ) && isset( $value[0] ) ) {
5708
				$value = $value[0];
5709
			}
5710
			$state[ $key ] = $value;
5711
			if ( ! headers_sent() ) {
5712
				if ( self::should_set_cookie( $key ) ) {
5713
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5714
				}
5715
			}
5716
		}
5717
	}
5718
5719
	public static function restate() {
5720
		self::state( null, null, true );
5721
	}
5722
5723
	/**
5724
	 * Determines whether the jetpackState[$key] value should be added to the
5725
	 * cookie.
5726
	 *
5727
	 * @param string $key The state key.
5728
	 *
5729
	 * @return boolean Whether the value should be added to the cookie.
5730
	 */
5731
	public static function should_set_cookie( $key ) {
5732
		global $current_screen;
5733
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5734
5735
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5736
			return false;
5737
		}
5738
5739
		return true;
5740
	}
5741
5742
	public static function check_privacy( $file ) {
5743
		static $is_site_publicly_accessible = null;
5744
5745
		if ( is_null( $is_site_publicly_accessible ) ) {
5746
			$is_site_publicly_accessible = false;
5747
5748
			$rpc = new Jetpack_IXR_Client();
5749
5750
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5751
			if ( $success ) {
5752
				$response = $rpc->getResponse();
5753
				if ( $response ) {
5754
					$is_site_publicly_accessible = true;
5755
				}
5756
			}
5757
5758
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5759
		}
5760
5761
		if ( $is_site_publicly_accessible ) {
5762
			return;
5763
		}
5764
5765
		$module_slug = self::get_module_slug( $file );
5766
5767
		$privacy_checks = self::state( 'privacy_checks' );
5768
		if ( ! $privacy_checks ) {
5769
			$privacy_checks = $module_slug;
5770
		} else {
5771
			$privacy_checks .= ",$module_slug";
5772
		}
5773
5774
		self::state( 'privacy_checks', $privacy_checks );
5775
	}
5776
5777
	/**
5778
	 * Helper method for multicall XMLRPC.
5779
	 *
5780
	 * @deprecated since 8.9.0
5781
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5782
	 *
5783
	 * @param ...$args Args for the async_call.
5784
	 */
5785
	public static function xmlrpc_async_call( ...$args ) {
5786
5787
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5788
5789
		global $blog_id;
5790
		static $clients = array();
5791
5792
		$client_blog_id = is_multisite() ? $blog_id : 0;
5793
5794
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5795
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5796
			if ( function_exists( 'ignore_user_abort' ) ) {
5797
				ignore_user_abort( true );
5798
			}
5799
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5800
		}
5801
5802
		if ( ! empty( $args[0] ) ) {
5803
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5804
		} elseif ( is_multisite() ) {
5805
			foreach ( $clients as $client_blog_id => $client ) {
5806
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5807
					continue;
5808
				}
5809
5810
				$switch_success = switch_to_blog( $client_blog_id, true );
5811
				if ( ! $switch_success ) {
5812
					continue;
5813
				}
5814
5815
				flush();
5816
				$client->query();
5817
5818
				restore_current_blog();
5819
			}
5820
		} else {
5821
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5822
				flush();
5823
				$clients[0]->query();
5824
			}
5825
		}
5826
	}
5827
5828
	/**
5829
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5830
	 *
5831
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5832
	 *
5833
	 * @param string $url WordPress.com static resource URL.
5834
	 */
5835
	public static function staticize_subdomain( $url ) {
5836
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5837
		return Assets::staticize_subdomain( $url );
5838
	}
5839
5840
	/* JSON API Authorization */
5841
5842
	/**
5843
	 * Handles the login action for Authorizing the JSON API
5844
	 */
5845
	function login_form_json_api_authorization() {
5846
		$this->verify_json_api_authorization_request();
5847
5848
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5849
5850
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5851
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5852
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5853
	}
5854
5855
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5856
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5857
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5858
			return $url;
5859
		}
5860
5861
		$parsed_url = wp_parse_url( $url );
5862
		$url        = strtok( $url, '?' );
5863
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5864
		if ( ! empty( $parsed_url['query'] ) ) {
5865
			$url .= "&{$parsed_url['query']}";
5866
		}
5867
5868
		return $url;
5869
	}
5870
5871
	// Make sure the POSTed request is handled by the same action
5872
	function preserve_action_in_login_form_for_json_api_authorization() {
5873
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5874
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5875
	}
5876
5877
	// If someone logs in to approve API access, store the Access Code in usermeta
5878
	function store_json_api_authorization_token( $user_login, $user ) {
5879
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5880
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5881
		$token = wp_generate_password( 32, false );
5882
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5883
	}
5884
5885
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5886
	function allow_wpcom_public_api_domain( $domains ) {
5887
		$domains[] = 'public-api.wordpress.com';
5888
		return $domains;
5889
	}
5890
5891
	static function is_redirect_encoded( $redirect_url ) {
5892
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5893
	}
5894
5895
	// Add all wordpress.com environments to the safe redirect allowed list.
5896
	function allow_wpcom_environments( $domains ) {
5897
		$domains[] = 'wordpress.com';
5898
		$domains[] = 'wpcalypso.wordpress.com';
5899
		$domains[] = 'horizon.wordpress.com';
5900
		$domains[] = 'calypso.localhost';
5901
		return $domains;
5902
	}
5903
5904
	// Add the Access Code details to the public-api.wordpress.com redirect
5905
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5906
		return add_query_arg(
5907
			urlencode_deep(
5908
				array(
5909
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5910
					'jetpack-user-id' => (int) $user->ID,
5911
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5912
				)
5913
			),
5914
			$redirect_to
5915
		);
5916
	}
5917
5918
	/**
5919
	 * Verifies the request by checking the signature
5920
	 *
5921
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5922
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5923
	 *
5924
	 * @param null|array $environment
5925
	 */
5926
	function verify_json_api_authorization_request( $environment = null ) {
5927
		$environment = is_null( $environment )
5928
			? $_REQUEST
5929
			: $environment;
5930
5931
		//phpcs:ignore MediaWiki.Classes.UnusedUseStatement.UnusedUse,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
5932
		list( $env_token, $env_version, $env_user_id ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $env_version is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5933
		$token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
5934
		if ( ! $token || empty( $token->secret ) ) {
5935
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5936
		}
5937
5938
		$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' );
5939
5940
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5941
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5942
			/**
5943
			 * Jetpack authorisation request Error.
5944
			 *
5945
			 * @since 7.5.0
5946
			 */
5947
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5948
			$die_error = sprintf(
5949
				/* translators: %s is a URL */
5950
				__( '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' ),
5951
				Redirect::get_url( 'jetpack-support-double-encoding' )
5952
			);
5953
		}
5954
5955
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5956
5957
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5958
			$signature = $jetpack_signature->sign_request(
5959
				$environment['token'],
5960
				$environment['timestamp'],
5961
				$environment['nonce'],
5962
				'',
5963
				'GET',
5964
				$environment['jetpack_json_api_original_query'],
5965
				null,
5966
				true
5967
			);
5968
		} else {
5969
			$signature = $jetpack_signature->sign_current_request(
5970
				array(
5971
					'body'   => null,
5972
					'method' => 'GET',
5973
				)
5974
			);
5975
		}
5976
5977
		if ( ! $signature ) {
5978
			wp_die( $die_error );
5979
		} elseif ( is_wp_error( $signature ) ) {
5980
			wp_die( $die_error );
5981
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5982
			if ( is_ssl() ) {
5983
				// 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
5984
				$signature = $jetpack_signature->sign_current_request(
5985
					array(
5986
						'scheme' => 'http',
5987
						'body'   => null,
5988
						'method' => 'GET',
5989
					)
5990
				);
5991
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5992
					wp_die( $die_error );
5993
				}
5994
			} else {
5995
				wp_die( $die_error );
5996
			}
5997
		}
5998
5999
		$timestamp = (int) $environment['timestamp'];
6000
		$nonce     = stripslashes( (string) $environment['nonce'] );
6001
6002
		if ( ! $this->connection_manager ) {
6003
			$this->connection_manager = new Connection_Manager();
6004
		}
6005
6006
		if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6007
			// De-nonce the nonce, at least for 5 minutes.
6008
			// 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)
6009
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6010
			if ( $old_nonce_time < time() - 300 ) {
6011
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6012
			}
6013
		}
6014
6015
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6016
		$data_filters = array(
6017
			'state'        => 'opaque',
6018
			'client_id'    => 'int',
6019
			'client_title' => 'string',
6020
			'client_image' => 'url',
6021
		);
6022
6023
		foreach ( $data_filters as $key => $sanitation ) {
6024
			if ( ! isset( $data->$key ) ) {
6025
				wp_die( $die_error );
6026
			}
6027
6028
			switch ( $sanitation ) {
6029
				case 'int':
6030
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6031
					break;
6032
				case 'opaque':
6033
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6034
					break;
6035
				case 'string':
6036
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6037
					break;
6038
				case 'url':
6039
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6040
					break;
6041
			}
6042
		}
6043
6044
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6045
			wp_die( $die_error );
6046
		}
6047
	}
6048
6049
	function login_message_json_api_authorization( $message ) {
6050
		return '<p class="message">' . sprintf(
6051
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6052
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6053
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6054
	}
6055
6056
	/**
6057
	 * Get $content_width, but with a <s>twist</s> filter.
6058
	 */
6059
	public static function get_content_width() {
6060
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6061
			? $GLOBALS['content_width']
6062
			: false;
6063
		/**
6064
		 * Filter the Content Width value.
6065
		 *
6066
		 * @since 2.2.3
6067
		 *
6068
		 * @param string $content_width Content Width value.
6069
		 */
6070
		return apply_filters( 'jetpack_content_width', $content_width );
6071
	}
6072
6073
	/**
6074
	 * Pings the WordPress.com Mirror Site for the specified options.
6075
	 *
6076
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6077
	 *
6078
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6079
	 */
6080
	public function get_cloud_site_options( $option_names ) {
6081
		$option_names = array_filter( (array) $option_names, 'is_string' );
6082
6083
		$xml = new Jetpack_IXR_Client();
6084
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6085
		if ( $xml->isError() ) {
6086
			return array(
6087
				'error_code' => $xml->getErrorCode(),
6088
				'error_msg'  => $xml->getErrorMessage(),
6089
			);
6090
		}
6091
		$cloud_site_options = $xml->getResponse();
6092
6093
		return $cloud_site_options;
6094
	}
6095
6096
	/**
6097
	 * Checks if the site is currently in an identity crisis.
6098
	 *
6099
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6100
	 */
6101
	public static function check_identity_crisis() {
6102
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6103
			return false;
6104
		}
6105
6106
		return Jetpack_Options::get_option( 'sync_error_idc' );
6107
	}
6108
6109
	/**
6110
	 * Checks whether the home and siteurl specifically are allowed.
6111
	 * Written so that we don't have re-check $key and $value params every time
6112
	 * we want to check if this site is allowed, for example in footer.php
6113
	 *
6114
	 * @since  3.8.0
6115
	 * @return bool True = already allowed False = not on the allowed list.
6116
	 */
6117
	public static function is_staging_site() {
6118
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6119
		return ( new Status() )->is_staging_site();
6120
	}
6121
6122
	/**
6123
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6124
	 *
6125
	 * @since 4.4.0
6126
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6127
	 *
6128
	 * @return bool
6129
	 */
6130
	public static function validate_sync_error_idc_option() {
6131
		$is_valid = false;
6132
6133
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6134
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6135
		if ( $sync_error && self::sync_idc_optin() ) {
6136
			$local_options = self::get_sync_error_idc_option();
6137
			// Ensure all values are set.
6138
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6139
6140
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6141
				if (
6142
						isset( $sync_error['wpcom_home'] ) &&
6143
						isset( $sync_error['wpcom_siteurl'] ) &&
6144
						$sync_error['wpcom_home'] === $local_options['home'] &&
6145
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6146
				) {
6147
					$is_valid = false;
6148
					// Enable migrate_for_idc so that sync actions are accepted.
6149
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6150
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6151
					$is_valid = true;
6152
				}
6153
			}
6154
		}
6155
6156
		/**
6157
		 * Filters whether the sync_error_idc option is valid.
6158
		 *
6159
		 * @since 4.4.0
6160
		 *
6161
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6162
		 */
6163
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6164
6165
		if ( ! $is_valid && $sync_error ) {
6166
			// Since the option exists, and did not validate, delete it
6167
			Jetpack_Options::delete_option( 'sync_error_idc' );
6168
		}
6169
6170
		return $is_valid;
6171
	}
6172
6173
	/**
6174
	 * Normalizes a url by doing three things:
6175
	 *  - Strips protocol
6176
	 *  - Strips www
6177
	 *  - Adds a trailing slash
6178
	 *
6179
	 * @since 4.4.0
6180
	 * @param string $url
6181
	 * @return WP_Error|string
6182
	 */
6183
	public static function normalize_url_protocol_agnostic( $url ) {
6184
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6185
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
6186
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

Loading history...
6187
		}
6188
6189
		// Strip www and protocols
6190
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6191
		return $url;
6192
	}
6193
6194
	/**
6195
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6196
	 *
6197
	 * @since 4.4.0
6198
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6199
	 *
6200
	 * @param array $response
6201
	 * @return array Array of the local urls, wpcom urls, and error code
6202
	 */
6203
	public static function get_sync_error_idc_option( $response = array() ) {
6204
		// Since the local options will hit the database directly, store the values
6205
		// in a transient to allow for autoloading and caching on subsequent views.
6206
		$local_options = get_transient( 'jetpack_idc_local' );
6207
		if ( false === $local_options ) {
6208
			$local_options = array(
6209
				'home'    => Functions::home_url(),
6210
				'siteurl' => Functions::site_url(),
6211
			);
6212
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6213
		}
6214
6215
		$options = array_merge( $local_options, $response );
6216
6217
		$returned_values = array();
6218
		foreach ( $options as $key => $option ) {
6219
			if ( 'error_code' === $key ) {
6220
				$returned_values[ $key ] = $option;
6221
				continue;
6222
			}
6223
6224
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6225
				continue;
6226
			}
6227
6228
			$returned_values[ $key ] = $normalized_url;
6229
		}
6230
6231
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6232
6233
		return $returned_values;
6234
	}
6235
6236
	/**
6237
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6238
	 * If set to true, the site will be put into staging mode.
6239
	 *
6240
	 * @since 4.3.2
6241
	 * @return bool
6242
	 */
6243
	public static function sync_idc_optin() {
6244
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6245
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6246
		} else {
6247
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6248
		}
6249
6250
		/**
6251
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6252
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6253
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6254
		 *
6255
		 * @since 4.3.2
6256
		 *
6257
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6258
		 */
6259
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6260
	}
6261
6262
	/**
6263
	 * Maybe Use a .min.css stylesheet, maybe not.
6264
	 *
6265
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6266
	 */
6267
	public static function maybe_min_asset( $url, $path, $plugin ) {
6268
		// Short out on things trying to find actual paths.
6269
		if ( ! $path || empty( $plugin ) ) {
6270
			return $url;
6271
		}
6272
6273
		$path = ltrim( $path, '/' );
6274
6275
		// Strip out the abspath.
6276
		$base = dirname( plugin_basename( $plugin ) );
6277
6278
		// Short out on non-Jetpack assets.
6279
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6280
			return $url;
6281
		}
6282
6283
		// File name parsing.
6284
		$file              = "{$base}/{$path}";
6285
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6286
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6287
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6288
		$extension         = array_shift( $file_name_parts_r );
6289
6290
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6291
			// Already pointing at the minified version.
6292
			if ( 'min' === $file_name_parts_r[0] ) {
6293
				return $url;
6294
			}
6295
6296
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6297
			if ( file_exists( $min_full_path ) ) {
6298
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6299
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6300
				if ( 'css' === $extension ) {
6301
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6302
					self::$min_assets[ $key ] = $path;
6303
				}
6304
			}
6305
		}
6306
6307
		return $url;
6308
	}
6309
6310
	/**
6311
	 * If the asset is minified, let's flag .min as the suffix.
6312
	 *
6313
	 * Attached to `style_loader_src` filter.
6314
	 *
6315
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
6948
	 */
6949
	public static function dns_prefetch( $urls = null ) {
6950
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6951
		if ( $urls ) {
6952
			Assets::add_resource_hint( $urls );
6953
		}
6954
	}
6955
6956
	public function wp_dashboard_setup() {
6957
		if ( self::is_active() ) {
6958
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6959
		}
6960
6961
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6962
			$jetpack_logo = new Jetpack_Logo();
6963
			$widget_title = sprintf(
6964
				/* translators: Placeholder is a Jetpack logo. */
6965
				__( 'Stats by %s', 'jetpack' ),
6966
				$jetpack_logo->get_jp_emblem( true )
6967
			);
6968
6969
			// Wrap title in span so Logo can be properly styled.
6970
			$widget_title = sprintf(
6971
				'<span>%s</span>',
6972
				$widget_title
6973
			);
6974
6975
			wp_add_dashboard_widget(
6976
				'jetpack_summary_widget',
6977
				$widget_title,
6978
				array( __CLASS__, 'dashboard_widget' )
6979
			);
6980
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6981
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6982
6983
			// If we're inactive and not in offline mode, sort our box to the top.
6984
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6985
				global $wp_meta_boxes;
6986
6987
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6988
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6989
6990
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6991
			}
6992
		}
6993
	}
6994
6995
	/**
6996
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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