Completed
Push — add/connection-package-json-ap... ( 457d59 )
by Marin
14:50 queued 07:14
created

Jetpack::verify_json_api_authorization_request()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * Contains all assets that have had their URL rewritten to minified versions.
86
	 *
87
	 * @var array
88
	 */
89
	static $min_assets = array();
90
91
	public $plugins_to_deactivate = array(
92
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
93
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
94
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
95
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
96
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
97
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
98
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
99
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
100
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
101
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
102
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
103
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
104
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
105
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
106
	);
107
108
	/**
109
	 * Map of roles we care about, and their corresponding minimum capabilities.
110
	 *
111
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
112
	 *
113
	 * @access public
114
	 * @static
115
	 *
116
	 * @var array
117
	 */
118
	public static $capability_translations = array(
119
		'administrator' => 'manage_options',
120
		'editor'        => 'edit_others_posts',
121
		'author'        => 'publish_posts',
122
		'contributor'   => 'edit_posts',
123
		'subscriber'    => 'read',
124
	);
125
126
	/**
127
	 * Map of modules that have conflicts with plugins and should not be auto-activated
128
	 * if the plugins are active.  Used by filter_default_modules
129
	 *
130
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
131
	 * change `module-slug` and add this to your plugin:
132
	 *
133
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
134
	 * function my_jetpack_get_default_modules( $modules ) {
135
	 *     return array_diff( $modules, array( 'module-slug' ) );
136
	 * }
137
	 *
138
	 * @var array
139
	 */
140
	private $conflicting_plugins = array(
141
		'comments'          => array(
142
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
143
			'Disqus'                               => 'disqus-comment-system/disqus.php',
144
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
145
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
146
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
147
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
148
		),
149
		'comment-likes' => array(
150
			'Epoch'                                => 'epoch/plugincore.php',
151
		),
152
		'contact-form'      => array(
153
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
154
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
155
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
156
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
157
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
158
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
159
		),
160
		'minileven'         => array(
161
			'WPtouch'                              => 'wptouch/wptouch.php',
162
		),
163
		'latex'             => array(
164
			'LaTeX for WordPress'                  => 'latex/latex.php',
165
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
166
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
167
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
168
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
169
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
170
		),
171
		'protect'           => array(
172
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
173
			'Captcha'                              => 'captcha/captcha.php',
174
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
175
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
176
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
177
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
178
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
179
			'Security-protection'                  => 'security-protection/security-protection.php',
180
			'Login Security'                       => 'login-security/login-security.php',
181
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
182
			'Wordfence Security'                   => 'wordfence/wordfence.php',
183
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
184
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
185
		),
186
		'random-redirect'   => array(
187
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
188
		),
189
		'related-posts'     => array(
190
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
191
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
192
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
193
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
194
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
195
			'outbrain'                             => 'outbrain/outbrain.php',
196
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
197
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
198
		),
199
		'sharedaddy'        => array(
200
			'AddThis'                              => 'addthis/addthis_social_widget.php',
201
			'Add To Any'                           => 'add-to-any/add-to-any.php',
202
			'ShareThis'                            => 'share-this/sharethis.php',
203
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
204
		),
205
		'seo-tools' => array(
206
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
207
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
208
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
209
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
210
			'The SEO Framework'                    => 'autodescription/autodescription.php',
211
		),
212
		'verification-tools' => array(
213
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
214
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
215
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
216
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
217
			'The SEO Framework'                    => 'autodescription/autodescription.php',
218
		),
219
		'widget-visibility' => array(
220
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
221
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
222
		),
223
		'sitemaps' => array(
224
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
225
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
226
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
227
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
228
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
229
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
230
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
231
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
232
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
233
			'The SEO Framework'                    => 'autodescription/autodescription.php',
234
			'Sitemap'                              => 'sitemap/sitemap.php',
235
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
236
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
237
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
238
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
239
		),
240
		'lazy-images' => array(
241
			'Lazy Load'              => 'lazy-load/lazy-load.php',
242
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
243
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
244
		),
245
	);
246
247
	/**
248
	 * Plugins for which we turn off our Facebook OG Tags implementation.
249
	 *
250
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
251
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
252
	 *
253
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
254
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
255
	 */
256
	private $open_graph_conflicting_plugins = array(
257
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
258
		                                                         // 2 Click Social Media Buttons
259
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
260
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
261
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
262
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
263
		                                                         // Open Graph Meta Tags by Heateor
264
		'facebook/facebook.php',                                 // Facebook (official plugin)
265
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
266
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
267
		                                                         // Facebook Featured Image & OG Meta Tags
268
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
269
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
270
		                                                         // Facebook Open Graph Meta Tags for WordPress
271
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
272
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
273
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
274
		                                                         // Fedmich's Facebook Open Graph Meta
275
		'network-publisher/networkpub.php',                      // Network Publisher
276
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
277
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
278
		                                                         // NextScripts SNAP
279
		'og-tags/og-tags.php',                                   // OG Tags
280
		'opengraph/opengraph.php',                               // Open Graph
281
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
282
		                                                         // Open Graph Protocol Framework
283
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
284
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
285
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
286
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
287
		'sharepress/sharepress.php',                             // SharePress
288
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
289
		'social-discussions/social-discussions.php',             // Social Discussions
290
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
291
		'socialize/socialize.php',                               // Socialize
292
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
293
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
294
		                                                         // Tweet, Like, Google +1 and Share
295
		'wordbooker/wordbooker.php',                             // Wordbooker
296
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
297
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
298
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
299
		                                                         // WP Facebook Like Send & Open Graph Meta
300
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
301
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
302
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
303
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
304
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
305
	);
306
307
	/**
308
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
309
	 */
310
	private $twitter_cards_conflicting_plugins = array(
311
	//	'twitter/twitter.php',                       // The official one handles this on its own.
312
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
313
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
314
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
315
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
316
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
317
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
318
		'twitter-cards/twitter-cards.php',           // Twitter Cards
319
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
320
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
321
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
322
	);
323
324
	/**
325
	 * Message to display in admin_notice
326
	 * @var string
327
	 */
328
	public $message = '';
329
330
	/**
331
	 * Error to display in admin_notice
332
	 * @var string
333
	 */
334
	public $error = '';
335
336
	/**
337
	 * Modules that need more privacy description.
338
	 * @var string
339
	 */
340
	public $privacy_checks = '';
341
342
	/**
343
	 * Stats to record once the page loads
344
	 *
345
	 * @var array
346
	 */
347
	public $stats = array();
348
349
	/**
350
	 * Jetpack_Sync object
351
	 */
352
	public $sync;
353
354
	/**
355
	 * Verified data for JSON authorization request
356
	 */
357
	public $json_api_authorization_request = array();
358
359
	/**
360
	 * @var \Automattic\Jetpack\Connection\Manager
361
	 */
362
	protected $connection_manager;
363
364
	/**
365
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
366
	 */
367
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
368
369
	/**
370
	 * Holds the singleton instance of this class
371
	 * @since 2.3.3
372
	 * @var Jetpack
373
	 */
374
	static $instance = false;
375
376
	/**
377
	 * Singleton
378
	 * @static
379
	 */
380
	public static function init() {
381
		if ( ! self::$instance ) {
382
			self::$instance = new Jetpack;
383
384
			self::$instance->plugin_upgrade();
385
		}
386
387
		return self::$instance;
388
	}
389
390
	/**
391
	 * Must never be called statically
392
	 */
393
	function plugin_upgrade() {
394
		if ( Jetpack::is_active() ) {
395
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
396
			if ( JETPACK__VERSION != $version ) {
397
				// Prevent multiple upgrades at once - only a single process should trigger
398
				// an upgrade to avoid stampedes
399
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
400
					return;
401
				}
402
403
				// Set a short lock to prevent multiple instances of the upgrade
404
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
405
406
				// check which active modules actually exist and remove others from active_modules list
407
				$unfiltered_modules = Jetpack::get_active_modules();
408
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
409
				if ( array_diff( $unfiltered_modules, $modules ) ) {
410
					Jetpack::update_active_modules( $modules );
411
				}
412
413
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
414
415
				// Upgrade to 4.3.0
416
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
417
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
418
				}
419
420
				// Make sure Markdown for posts gets turned back on
421
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
422
					update_option( 'wpcom_publish_posts_with_markdown', true );
423
				}
424
425
				if ( did_action( 'wp_loaded' ) ) {
426
					self::upgrade_on_load();
427
				} else {
428
					add_action(
429
						'wp_loaded',
430
						array( __CLASS__, 'upgrade_on_load' )
431
					);
432
				}
433
			}
434
		}
435
	}
436
437
	/**
438
	 * Runs upgrade routines that need to have modules loaded.
439
	 */
440
	static function upgrade_on_load() {
441
442
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
443
		// This can happen in case Jetpack has been just upgraded and is
444
		// being initialized late during the page load. In this case we wait
445
		// until the next proper admin page load with Jetpack active.
446
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
447
			delete_transient( self::$plugin_upgrade_lock_key );
448
449
			return;
450
		}
451
452
		Jetpack::maybe_set_version_option();
453
454
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
455
			Jetpack_Widget_Conditions::migrate_post_type_rules();
456
		}
457
458
		if (
459
			class_exists( 'Jetpack_Sitemap_Manager' )
460
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
461
		) {
462
			do_action( 'jetpack_sitemaps_purge_data' );
463
		}
464
465
		// Delete old stats cache
466
		delete_option( 'jetpack_restapi_stats_cache' );
467
468
		delete_transient( self::$plugin_upgrade_lock_key );
469
	}
470
471
	/**
472
	 * Saves all the currently active modules to options.
473
	 * Also fires Action hooks for each newly activated and deactivated module.
474
	 *
475
	 * @param $modules Array Array of active modules to be saved in options.
476
	 *
477
	 * @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...
478
	 */
479
	static function update_active_modules( $modules ) {
480
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
481
		$active_modules       = Jetpack::get_active_modules();
482
		$new_active_modules   = array_diff( $modules, $current_modules );
483
		$new_inactive_modules = array_diff( $active_modules, $modules );
484
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
485
		$reindexed_modules    = array_values( $new_current_modules );
486
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
487
488
		foreach ( $new_active_modules as $module ) {
489
			/**
490
			 * Fires when a specific module is activated.
491
			 *
492
			 * @since 1.9.0
493
			 *
494
			 * @param string $module Module slug.
495
			 * @param boolean $success whether the module was activated. @since 4.2
496
			 */
497
			do_action( 'jetpack_activate_module', $module, $success );
498
			/**
499
			 * Fires when a module is activated.
500
			 * The dynamic part of the filter, $module, is the module slug.
501
			 *
502
			 * @since 1.9.0
503
			 *
504
			 * @param string $module Module slug.
505
			 */
506
			do_action( "jetpack_activate_module_$module", $module );
507
		}
508
509
		foreach ( $new_inactive_modules as $module ) {
510
			/**
511
			 * Fired after a module has been deactivated.
512
			 *
513
			 * @since 4.2.0
514
			 *
515
			 * @param string $module Module slug.
516
			 * @param boolean $success whether the module was deactivated.
517
			 */
518
			do_action( 'jetpack_deactivate_module', $module, $success );
519
			/**
520
			 * Fires when a module is deactivated.
521
			 * The dynamic part of the filter, $module, is the module slug.
522
			 *
523
			 * @since 1.9.0
524
			 *
525
			 * @param string $module Module slug.
526
			 */
527
			do_action( "jetpack_deactivate_module_$module", $module );
528
		}
529
530
		return $success;
531
	}
532
533
	static function delete_active_modules() {
534
		self::update_active_modules( array() );
535
	}
536
537
	/**
538
	 * Constructor.  Initializes WordPress hooks
539
	 */
540
	private function __construct() {
541
		/*
542
		 * Check for and alert any deprecated hooks
543
		 */
544
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
545
546
		/*
547
		 * Enable enhanced handling of previewing sites in Calypso
548
		 */
549
		if ( Jetpack::is_active() ) {
550
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
551
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
552
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
553
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
554
		}
555
556
		if ( self::jetpack_tos_agreed() ) {
557
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
558
			add_action( 'init', array( $tracking, 'init' ) );
559
		}
560
561
562
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
563
			return function() {
564
				return wp_generate_password( 32, false );
565
			};
566
		} );
567
568
		$this->connection_manager = new Connection_Manager();
569
		$this->connection_manager->init();
570
571
		/*
572
		 * Load things that should only be in Network Admin.
573
		 *
574
		 * For now blow away everything else until a more full
575
		 * understanding of what is needed at the network level is
576
		 * available
577
		 */
578
		if ( is_multisite() ) {
579
			$network = Jetpack_Network::init();
580
			$network->set_connection( $this->connection_manager );
581
		}
582
583
		add_filter(
584
			'jetpack_signature_check_token',
585
			array( __CLASS__, 'verify_onboarding_token' ),
586
			10,
587
			3
588
		);
589
590
		/**
591
		 * Prepare Gutenberg Editor functionality
592
		 */
593
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
594
		Jetpack_Gutenberg::init();
595
		Jetpack_Gutenberg::load_independent_blocks();
596
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
597
598
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
599
600
		// Unlink user before deleting the user from .com
601
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
602
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
603
604
		if ( Jetpack::is_active() ) {
605
			Jetpack_Heartbeat::init();
606
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
607
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
608
				Jetpack_Search_Performance_Logger::init();
609
			}
610
		}
611
612
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
613
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
614
615
		add_action( 'admin_init', array( $this, 'admin_init' ) );
616
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
617
618
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
619
620
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
621
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
622
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
623
624
		// returns HTTPS support status
625
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
626
627
		// JITM AJAX callback function
628
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
629
630
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
631
632
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
633
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
634
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
635
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
636
637
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
638
639
		/**
640
		 * These actions run checks to load additional files.
641
		 * They check for external files or plugins, so they need to run as late as possible.
642
		 */
643
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
644
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
645
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
646
647
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
648
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
649
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
650
651
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
652
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
653
654
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
655
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
656
657
		// A filter to control all just in time messages
658
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
659
660
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
661
662
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
663
		// We should make sure to only do this for front end links.
664
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
665
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
666
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
667
668
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
669
			//so they point moderation links on emails to Calypso
670
			jetpack_require_lib( 'functions.wp-notify' );
671
		}
672
673
		// Hide edit post link if mobile app.
674
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
675
			add_filter( 'edit_post_link', '__return_empty_string' );
676
		}
677
678
		// Update the Jetpack plan from API on heartbeats
679
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
680
681
		/**
682
		 * This is the hack to concatenate all css files into one.
683
		 * For description and reasoning see the implode_frontend_css method
684
		 *
685
		 * Super late priority so we catch all the registered styles
686
		 */
687
		if( !is_admin() ) {
688
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
689
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
690
		}
691
692
693
		/**
694
		 * These are sync actions that we need to keep track of for jitms
695
		 */
696
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
697
698
		// Actually push the stats on shutdown.
699
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
700
			add_action( 'shutdown', array( $this, 'push_stats' ) );
701
		}
702
	}
703
704
	/**
705
	 * Sets up the XMLRPC request handlers.
706
	 *
707
	 * @todo Deprecate this method in favor of Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers().
708
	 *
709
	 * @param Array                 $request_params Incoming request parameters.
710
	 * @param Boolean               $is_active      Whether the connection is currently active.
711
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
712
	 * @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...
713
	 */
714
	public function setup_xmlrpc_handlers(
715
		$request_params,
716
		$is_active,
717
		$is_signed,
718
		Jetpack_XMLRPC_Server $xmlrpc_server = null
719
	) {
720
		return $this->connection_manager->setup_xmlrpc_handlers(
721
			$request_params,
722
			$is_active,
723
			$is_signed,
724
			$xmlrpc_server
725
		);
726
	}
727
728
	/**
729
	 * Initialize REST API registration connector.
730
	 *
731
	 * @deprecated since 7.7.0
732
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
733
	 */
734
	public function initialize_rest_api_registration_connector() {
735
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
736
		$this->connection_manager->initialize_rest_api_registration_connector();
737
	}
738
739
	/**
740
	 * This is ported over from the manage module, which has been deprecated and baked in here.
741
	 *
742
	 * @param $domains
743
	 */
744
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
745
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
746
	}
747
748
	/**
749
	 * Return $domains, with 'wordpress.com' appended.
750
	 * This is ported over from the manage module, which has been deprecated and baked in here.
751
	 *
752
	 * @param $domains
753
	 * @return array
754
	 */
755
	function allow_wpcom_domain( $domains ) {
756
		if ( empty( $domains ) ) {
757
			$domains = array();
758
		}
759
		$domains[] = 'wordpress.com';
760
		return array_unique( $domains );
761
	}
762
763
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
764
		$post = get_post( $post_id );
765
766
		if ( empty( $post ) ) {
767
			return $default_url;
768
		}
769
770
		$post_type = $post->post_type;
771
772
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
773
		// https://en.support.wordpress.com/custom-post-types/
774
		$allowed_post_types = array(
775
			'post' => 'post',
776
			'page' => 'page',
777
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
778
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
779
		);
780
781
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
782
			return $default_url;
783
		}
784
785
		$path_prefix = $allowed_post_types[ $post_type ];
786
787
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
788
789
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
790
	}
791
792
	function point_edit_comment_links_to_calypso( $url ) {
793
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
794
		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...
795
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
796
			Jetpack::build_raw_urls( get_home_url() ),
797
			$query_args['amp;c']
798
		) );
799
	}
800
801
	function jetpack_track_last_sync_callback( $params ) {
802
		/**
803
		 * Filter to turn off jitm caching
804
		 *
805
		 * @since 5.4.0
806
		 *
807
		 * @param bool false Whether to cache just in time messages
808
		 */
809
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
810
			return $params;
811
		}
812
813
		if ( is_array( $params ) && isset( $params[0] ) ) {
814
			$option = $params[0];
815
			if ( 'active_plugins' === $option ) {
816
				// use the cache if we can, but not terribly important if it gets evicted
817
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
818
			}
819
		}
820
821
		return $params;
822
	}
823
824
	function jetpack_connection_banner_callback() {
825
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
826
827
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
828
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
829
			wp_send_json_success();
830
		}
831
832
		wp_die();
833
	}
834
835
	/**
836
	 * Removes all XML-RPC methods that are not `jetpack.*`.
837
	 * Only used in our alternate XML-RPC endpoint, where we want to
838
	 * ensure that Core and other plugins' methods are not exposed.
839
	 *
840
	 * @deprecated since 7.7.0
841
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
842
	 *
843
	 * @param array $methods A list of registered WordPress XMLRPC methods.
844
	 * @return array Filtered $methods
845
	 */
846
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
847
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
848
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
849
	}
850
851
	/**
852
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
853
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
854
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
855
	 * which is accessible via a different URI. Most of the below is copied directly
856
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
857
	 *
858
	 * @deprecated since 7.7.0
859
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
860
	 */
861
	public function alternate_xmlrpc() {
862
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
863
		$this->connection_manager->alternate_xmlrpc();
864
	}
865
866
	/**
867
	 * The callback for the JITM ajax requests.
868
	 */
869
	function jetpack_jitm_ajax_callback() {
870
		// Check for nonce
871
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
872
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
873
		}
874
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
875
			$module_slug = $_REQUEST['jitmModule'];
876
			Jetpack::log( 'activate', $module_slug );
877
			Jetpack::activate_module( $module_slug, false, false );
878
			Jetpack::state( 'message', 'no_message' );
879
880
			//A Jetpack module is being activated through a JITM, track it
881
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
882
			$this->do_stats( 'server_side' );
883
884
			wp_send_json_success();
885
		}
886
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
887
			// get the hide_jitm options array
888
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
889
			$module_slug = $_REQUEST['jitmModule'];
890
891
			if( ! $jetpack_hide_jitm ) {
892
				$jetpack_hide_jitm = array(
893
					$module_slug => 'hide'
894
				);
895
			} else {
896
				$jetpack_hide_jitm[$module_slug] = 'hide';
897
			}
898
899
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
900
901
			//jitm is being dismissed forever, track it
902
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
903
			$this->do_stats( 'server_side' );
904
905
			wp_send_json_success();
906
		}
907 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
908
			$module_slug = $_REQUEST['jitmModule'];
909
910
			// User went to WordPress.com, track this
911
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
912
			$this->do_stats( 'server_side' );
913
914
			wp_send_json_success();
915
		}
916 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
917
			$track = $_REQUEST['jitmModule'];
918
919
			// User is viewing JITM, track it.
920
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
921
			$this->do_stats( 'server_side' );
922
923
			wp_send_json_success();
924
		}
925
	}
926
927
	/**
928
	 * If there are any stats that need to be pushed, but haven't been, push them now.
929
	 */
930
	function push_stats() {
931
		if ( ! empty( $this->stats ) ) {
932
			$this->do_stats( 'server_side' );
933
		}
934
	}
935
936
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
937
		switch( $cap ) {
938
			case 'jetpack_connect' :
939
			case 'jetpack_reconnect' :
940
				if ( Jetpack::is_development_mode() ) {
941
					$caps = array( 'do_not_allow' );
942
					break;
943
				}
944
				/**
945
				 * Pass through. If it's not development mode, these should match disconnect.
946
				 * Let users disconnect if it's development mode, just in case things glitch.
947
				 */
948
			case 'jetpack_disconnect' :
949
				/**
950
				 * In multisite, can individual site admins manage their own connection?
951
				 *
952
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
953
				 */
954
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
955
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
956
						/**
957
						 * We need to update the option name -- it's terribly unclear which
958
						 * direction the override goes.
959
						 *
960
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
961
						 */
962
						$caps = array( 'do_not_allow' );
963
						break;
964
					}
965
				}
966
967
				$caps = array( 'manage_options' );
968
				break;
969
			case 'jetpack_manage_modules' :
970
			case 'jetpack_activate_modules' :
971
			case 'jetpack_deactivate_modules' :
972
				$caps = array( 'manage_options' );
973
				break;
974
			case 'jetpack_configure_modules' :
975
				$caps = array( 'manage_options' );
976
				break;
977
			case 'jetpack_manage_autoupdates' :
978
				$caps = array(
979
					'manage_options',
980
					'update_plugins',
981
				);
982
				break;
983
			case 'jetpack_network_admin_page':
984
			case 'jetpack_network_settings_page':
985
				$caps = array( 'manage_network_plugins' );
986
				break;
987
			case 'jetpack_network_sites_page':
988
				$caps = array( 'manage_sites' );
989
				break;
990
			case 'jetpack_admin_page' :
991
				if ( Jetpack::is_development_mode() ) {
992
					$caps = array( 'manage_options' );
993
					break;
994
				} else {
995
					$caps = array( 'read' );
996
				}
997
				break;
998
			case 'jetpack_connect_user' :
999
				if ( Jetpack::is_development_mode() ) {
1000
					$caps = array( 'do_not_allow' );
1001
					break;
1002
				}
1003
				$caps = array( 'read' );
1004
				break;
1005
		}
1006
		return $caps;
1007
	}
1008
1009
	/**
1010
	 * Require a Jetpack authentication.
1011
	 *
1012
	 * @deprecated since 7.7.0
1013
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1014
	 */
1015
	public function require_jetpack_authentication() {
1016
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1017
		$this->connection_manager->require_jetpack_authentication();
1018
	}
1019
1020
	/**
1021
	 * Load language files
1022
	 * @action plugins_loaded
1023
	 */
1024
	public static function plugin_textdomain() {
1025
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1026
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1027
	}
1028
1029
	/**
1030
	 * Register assets for use in various modules and the Jetpack admin page.
1031
	 *
1032
	 * @uses wp_script_is, wp_register_script, plugins_url
1033
	 * @action wp_loaded
1034
	 * @return null
1035
	 */
1036
	public function register_assets() {
1037
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1038
			wp_register_script(
1039
				'spin',
1040
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1041
				false,
1042
				'1.3'
1043
			);
1044
		}
1045
1046 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1047
			wp_register_script(
1048
				'jquery.spin',
1049
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1050
				array( 'jquery', 'spin' ),
1051
				'1.3'
1052
			);
1053
		}
1054
1055 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1056
			wp_register_script(
1057
				'jetpack-gallery-settings',
1058
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1059
				array( 'media-views' ),
1060
				'20121225'
1061
			);
1062
		}
1063
1064 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1065
			wp_register_script(
1066
				'jetpack-twitter-timeline',
1067
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1068
				array( 'jquery' ),
1069
				'4.0.0',
1070
				true
1071
			);
1072
		}
1073
1074
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1075
			wp_register_script(
1076
				'jetpack-facebook-embed',
1077
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1078
				array( 'jquery' ),
1079
				null,
1080
				true
1081
			);
1082
1083
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1084
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1085
			if ( ! is_numeric( $fb_app_id ) ) {
1086
				$fb_app_id = '';
1087
			}
1088
			wp_localize_script(
1089
				'jetpack-facebook-embed',
1090
				'jpfbembed',
1091
				array(
1092
					'appid' => $fb_app_id,
1093
					'locale' => $this->get_locale(),
1094
				)
1095
			);
1096
		}
1097
1098
		/**
1099
		 * As jetpack_register_genericons is by default fired off a hook,
1100
		 * the hook may have already fired by this point.
1101
		 * So, let's just trigger it manually.
1102
		 */
1103
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1104
		jetpack_register_genericons();
1105
1106
		/**
1107
		 * Register the social logos
1108
		 */
1109
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1110
		jetpack_register_social_logos();
1111
1112 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1113
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1114
	}
1115
1116
	/**
1117
	 * Guess locale from language code.
1118
	 *
1119
	 * @param string $lang Language code.
1120
	 * @return string|bool
1121
	 */
1122 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1123
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1124
			return 'en_US';
1125
		}
1126
1127
		if ( ! class_exists( 'GP_Locales' ) ) {
1128
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1129
				return false;
1130
			}
1131
1132
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1133
		}
1134
1135
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1136
			// WP.com: get_locale() returns 'it'
1137
			$locale = GP_Locales::by_slug( $lang );
1138
		} else {
1139
			// Jetpack: get_locale() returns 'it_IT';
1140
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1141
		}
1142
1143
		if ( ! $locale ) {
1144
			return false;
1145
		}
1146
1147
		if ( empty( $locale->facebook_locale ) ) {
1148
			if ( empty( $locale->wp_locale ) ) {
1149
				return false;
1150
			} else {
1151
				// Facebook SDK is smart enough to fall back to en_US if a
1152
				// locale isn't supported. Since supported Facebook locales
1153
				// can fall out of sync, we'll attempt to use the known
1154
				// wp_locale value and rely on said fallback.
1155
				return $locale->wp_locale;
1156
			}
1157
		}
1158
1159
		return $locale->facebook_locale;
1160
	}
1161
1162
	/**
1163
	 * Get the locale.
1164
	 *
1165
	 * @return string|bool
1166
	 */
1167
	function get_locale() {
1168
		$locale = $this->guess_locale_from_lang( get_locale() );
1169
1170
		if ( ! $locale ) {
1171
			$locale = 'en_US';
1172
		}
1173
1174
		return $locale;
1175
	}
1176
1177
	/**
1178
	 * Device Pixels support
1179
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1180
	 */
1181
	function devicepx() {
1182
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1183
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1184
		}
1185
	}
1186
1187
	/**
1188
	 * Return the network_site_url so that .com knows what network this site is a part of.
1189
	 * @param  bool $option
1190
	 * @return string
1191
	 */
1192
	public function jetpack_main_network_site_option( $option ) {
1193
		return network_site_url();
1194
	}
1195
	/**
1196
	 * Network Name.
1197
	 */
1198
	static function network_name( $option = null ) {
1199
		global $current_site;
1200
		return $current_site->site_name;
1201
	}
1202
	/**
1203
	 * Does the network allow new user and site registrations.
1204
	 * @return string
1205
	 */
1206
	static function network_allow_new_registrations( $option = null ) {
1207
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1208
	}
1209
	/**
1210
	 * Does the network allow admins to add new users.
1211
	 * @return boolian
1212
	 */
1213
	static function network_add_new_users( $option = null ) {
1214
		return (bool) get_site_option( 'add_new_users' );
1215
	}
1216
	/**
1217
	 * File upload psace left per site in MB.
1218
	 *  -1 means NO LIMIT.
1219
	 * @return number
1220
	 */
1221
	static function network_site_upload_space( $option = null ) {
1222
		// value in MB
1223
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1224
	}
1225
1226
	/**
1227
	 * Network allowed file types.
1228
	 * @return string
1229
	 */
1230
	static function network_upload_file_types( $option = null ) {
1231
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1232
	}
1233
1234
	/**
1235
	 * Maximum file upload size set by the network.
1236
	 * @return number
1237
	 */
1238
	static function network_max_upload_file_size( $option = null ) {
1239
		// value in KB
1240
		return get_site_option( 'fileupload_maxk', 300 );
1241
	}
1242
1243
	/**
1244
	 * Lets us know if a site allows admins to manage the network.
1245
	 * @return array
1246
	 */
1247
	static function network_enable_administration_menus( $option = null ) {
1248
		return get_site_option( 'menu_items' );
1249
	}
1250
1251
	/**
1252
	 * If a user has been promoted to or demoted from admin, we need to clear the
1253
	 * jetpack_other_linked_admins transient.
1254
	 *
1255
	 * @since 4.3.2
1256
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1257
	 *
1258
	 * @param int    $user_id   The user ID whose role changed.
1259
	 * @param string $role      The new role.
1260
	 * @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...
1261
	 */
1262
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1263
		if ( 'administrator' == $role
1264
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1265
			|| is_null( $old_roles )
1266
		) {
1267
			delete_transient( 'jetpack_other_linked_admins' );
1268
		}
1269
	}
1270
1271
	/**
1272
	 * Checks to see if there are any other users available to become primary
1273
	 * Users must both:
1274
	 * - Be linked to wpcom
1275
	 * - Be an admin
1276
	 *
1277
	 * @return mixed False if no other users are linked, Int if there are.
1278
	 */
1279
	static function get_other_linked_admins() {
1280
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1281
1282
		if ( false === $other_linked_users ) {
1283
			$admins = get_users( array( 'role' => 'administrator' ) );
1284
			if ( count( $admins ) > 1 ) {
1285
				$available = array();
1286
				foreach ( $admins as $admin ) {
1287
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1288
						$available[] = $admin->ID;
1289
					}
1290
				}
1291
1292
				$count_connected_admins = count( $available );
1293
				if ( count( $available ) > 1 ) {
1294
					$other_linked_users = $count_connected_admins;
1295
				} else {
1296
					$other_linked_users = 0;
1297
				}
1298
			} else {
1299
				$other_linked_users = 0;
1300
			}
1301
1302
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1303
		}
1304
1305
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1306
	}
1307
1308
	/**
1309
	 * Return whether we are dealing with a multi network setup or not.
1310
	 * The reason we are type casting this is because we want to avoid the situation where
1311
	 * the result is false since when is_main_network_option return false it cases
1312
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1313
	 * database which could be set to anything as opposed to what this function returns.
1314
	 * @param  bool  $option
1315
	 *
1316
	 * @return boolean
1317
	 */
1318
	public function is_main_network_option( $option ) {
1319
		// return '1' or ''
1320
		return (string) (bool) Jetpack::is_multi_network();
1321
	}
1322
1323
	/**
1324
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1325
	 *
1326
	 * @param  string  $option
1327
	 * @return boolean
1328
	 */
1329
	public function is_multisite( $option ) {
1330
		return (string) (bool) is_multisite();
1331
	}
1332
1333
	/**
1334
	 * Implemented since there is no core is multi network function
1335
	 * Right now there is no way to tell if we which network is the dominant network on the system
1336
	 *
1337
	 * @since  3.3
1338
	 * @return boolean
1339
	 */
1340 View Code Duplication
	public static function is_multi_network() {
1341
		global  $wpdb;
1342
1343
		// if we don't have a multi site setup no need to do any more
1344
		if ( ! is_multisite() ) {
1345
			return false;
1346
		}
1347
1348
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1349
		if ( $num_sites > 1 ) {
1350
			return true;
1351
		} else {
1352
			return false;
1353
		}
1354
	}
1355
1356
	/**
1357
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1358
	 * @return null
1359
	 */
1360
	function update_jetpack_main_network_site_option() {
1361
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1362
	}
1363
	/**
1364
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1365
	 *
1366
	 */
1367
	function update_jetpack_network_settings() {
1368
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1369
		// Only sync this info for the main network site.
1370
	}
1371
1372
	/**
1373
	 * Get back if the current site is single user site.
1374
	 *
1375
	 * @return bool
1376
	 */
1377 View Code Duplication
	public static function is_single_user_site() {
1378
		global $wpdb;
1379
1380
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1381
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1382
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1383
		}
1384
		return 1 === (int) $some_users;
1385
	}
1386
1387
	/**
1388
	 * Returns true if the site has file write access false otherwise.
1389
	 * @return string ( '1' | '0' )
1390
	 **/
1391
	public static function file_system_write_access() {
1392
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1393
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1394
		}
1395
1396
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1397
1398
		$filesystem_method = get_filesystem_method();
1399
		if ( $filesystem_method === 'direct' ) {
1400
			return 1;
1401
		}
1402
1403
		ob_start();
1404
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1405
		ob_end_clean();
1406
		if ( $filesystem_credentials_are_stored ) {
1407
			return 1;
1408
		}
1409
		return 0;
1410
	}
1411
1412
	/**
1413
	 * Finds out if a site is using a version control system.
1414
	 * @return string ( '1' | '0' )
1415
	 **/
1416
	public static function is_version_controlled() {
1417
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1418
		return (string) (int) Functions::is_version_controlled();
1419
	}
1420
1421
	/**
1422
	 * Determines whether the current theme supports featured images or not.
1423
	 * @return string ( '1' | '0' )
1424
	 */
1425
	public static function featured_images_enabled() {
1426
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1427
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1428
	}
1429
1430
	/**
1431
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1432
	 *
1433
	 * @deprecated 4.7 use get_avatar_url instead.
1434
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1435
	 * @param int $size Size of the avatar image
1436
	 * @param string $default URL to a default image to use if no avatar is available
1437
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1438
	 *
1439
	 * @return array
1440
	 */
1441
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1442
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1443
		return get_avatar_url( $id_or_email, array(
1444
			'size' => $size,
1445
			'default' => $default,
1446
			'force_default' => $force_display,
1447
		) );
1448
	}
1449
1450
	/**
1451
	 * jetpack_updates is saved in the following schema:
1452
	 *
1453
	 * array (
1454
	 *      'plugins'                       => (int) Number of plugin updates available.
1455
	 *      'themes'                        => (int) Number of theme updates available.
1456
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1457
	 *      'translations'                  => (int) Number of translation updates available.
1458
	 *      'total'                         => (int) Total of all available updates.
1459
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1460
	 * )
1461
	 * @return array
1462
	 */
1463
	public static function get_updates() {
1464
		$update_data = wp_get_update_data();
1465
1466
		// Stores the individual update counts as well as the total count.
1467
		if ( isset( $update_data['counts'] ) ) {
1468
			$updates = $update_data['counts'];
1469
		}
1470
1471
		// If we need to update WordPress core, let's find the latest version number.
1472 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1473
			$cur = get_preferred_from_update_core();
1474
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1475
				$updates['wp_update_version'] = $cur->current;
1476
			}
1477
		}
1478
		return isset( $updates ) ? $updates : array();
1479
	}
1480
1481
	public static function get_update_details() {
1482
		$update_details = array(
1483
			'update_core' => get_site_transient( 'update_core' ),
1484
			'update_plugins' => get_site_transient( 'update_plugins' ),
1485
			'update_themes' => get_site_transient( 'update_themes' ),
1486
		);
1487
		return $update_details;
1488
	}
1489
1490
	public static function refresh_update_data() {
1491
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1492
1493
	}
1494
1495
	public static function refresh_theme_data() {
1496
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1497
	}
1498
1499
	/**
1500
	 * Is Jetpack active?
1501
	 */
1502
	public static function is_active() {
1503
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
1504
	}
1505
1506
	/**
1507
	 * Make an API call to WordPress.com for plan status
1508
	 *
1509
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1510
	 *
1511
	 * @return bool True if plan is updated, false if no update
1512
	 */
1513
	public static function refresh_active_plan_from_wpcom() {
1514
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1515
		return Jetpack_Plan::refresh_from_wpcom();
1516
	}
1517
1518
	/**
1519
	 * Get the plan that this Jetpack site is currently using
1520
	 *
1521
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1522
	 * @return array Active Jetpack plan details.
1523
	 */
1524
	public static function get_active_plan() {
1525
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1526
		return Jetpack_Plan::get();
1527
	}
1528
1529
	/**
1530
	 * Determine whether the active plan supports a particular feature
1531
	 *
1532
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1533
	 * @return bool True if plan supports feature, false if not.
1534
	 */
1535
	public static function active_plan_supports( $feature ) {
1536
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1537
		return Jetpack_Plan::supports( $feature );
1538
	}
1539
1540
	/**
1541
	 * Is Jetpack in development (offline) mode?
1542
	 */
1543 View Code Duplication
	public static function is_development_mode() {
1544
		$development_mode = false;
1545
1546
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1547
			$development_mode = JETPACK_DEV_DEBUG;
1548
		} elseif ( $site_url = site_url() ) {
1549
			$development_mode = false === strpos( $site_url, '.' );
1550
		}
1551
1552
		/**
1553
		 * Filters Jetpack's development mode.
1554
		 *
1555
		 * @see https://jetpack.com/support/development-mode/
1556
		 *
1557
		 * @since 2.2.1
1558
		 *
1559
		 * @param bool $development_mode Is Jetpack's development mode active.
1560
		 */
1561
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1562
		return $development_mode;
1563
	}
1564
1565
	/**
1566
	 * Whether the site is currently onboarding or not.
1567
	 * A site is considered as being onboarded if it currently has an onboarding token.
1568
	 *
1569
	 * @since 5.8
1570
	 *
1571
	 * @access public
1572
	 * @static
1573
	 *
1574
	 * @return bool True if the site is currently onboarding, false otherwise
1575
	 */
1576
	public static function is_onboarding() {
1577
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1578
	}
1579
1580
	/**
1581
	 * Determines reason for Jetpack development mode.
1582
	 */
1583
	public static function development_mode_trigger_text() {
1584
		if ( ! Jetpack::is_development_mode() ) {
1585
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1586
		}
1587
1588
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1589
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1590
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1591
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1592
		} else {
1593
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1594
		}
1595
1596
		return $notice;
1597
1598
	}
1599
	/**
1600
	* Get Jetpack development mode notice text and notice class.
1601
	*
1602
	* Mirrors the checks made in Jetpack::is_development_mode
1603
	*
1604
	*/
1605
	public static function show_development_mode_notice() {
1606 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1607
			$notice = sprintf(
1608
			/* translators: %s is a URL */
1609
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1610
				'https://jetpack.com/support/development-mode/'
1611
			);
1612
1613
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1614
1615
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1616
		}
1617
1618
		// Throw up a notice if using a development version and as for feedback.
1619
		if ( Jetpack::is_development_version() ) {
1620
			/* translators: %s is a URL */
1621
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1622
1623
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1624
		}
1625
		// Throw up a notice if using staging mode
1626
		if ( Jetpack::is_staging_site() ) {
1627
			/* translators: %s is a URL */
1628
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1629
1630
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1631
		}
1632
	}
1633
1634
	/**
1635
	 * Whether Jetpack's version maps to a public release, or a development version.
1636
	 */
1637
	public static function is_development_version() {
1638
		/**
1639
		 * Allows filtering whether this is a development version of Jetpack.
1640
		 *
1641
		 * This filter is especially useful for tests.
1642
		 *
1643
		 * @since 4.3.0
1644
		 *
1645
		 * @param bool $development_version Is this a develoment version of Jetpack?
1646
		 */
1647
		return (bool) apply_filters(
1648
			'jetpack_development_version',
1649
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1650
		);
1651
	}
1652
1653
	/**
1654
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1655
	 */
1656
	public static function is_user_connected( $user_id = false ) {
1657
		return self::connection()->is_user_connected( $user_id );
1658
	}
1659
1660
	/**
1661
	 * Get the wpcom user data of the current|specified connected user.
1662
	 */
1663 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1664
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1665
		if ( ! $user_id ) {
1666
			$user_id = get_current_user_id();
1667
		}
1668
1669
		$transient_key = "jetpack_connected_user_data_$user_id";
1670
1671
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1672
			return $cached_user_data;
1673
		}
1674
1675
		Jetpack::load_xml_rpc_client();
1676
		$xml = new Jetpack_IXR_Client( array(
1677
			'user_id' => $user_id,
1678
		) );
1679
		$xml->query( 'wpcom.getUser' );
1680
		if ( ! $xml->isError() ) {
1681
			$user_data = $xml->getResponse();
1682
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1683
			return $user_data;
1684
		}
1685
1686
		return false;
1687
	}
1688
1689
	/**
1690
	 * Get the wpcom email of the current|specified connected user.
1691
	 */
1692 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1693
		if ( ! $user_id ) {
1694
			$user_id = get_current_user_id();
1695
		}
1696
		Jetpack::load_xml_rpc_client();
1697
		$xml = new Jetpack_IXR_Client( array(
1698
			'user_id' => $user_id,
1699
		) );
1700
		$xml->query( 'wpcom.getUserEmail' );
1701
		if ( ! $xml->isError() ) {
1702
			return $xml->getResponse();
1703
		}
1704
		return false;
1705
	}
1706
1707
	/**
1708
	 * Get the wpcom email of the master user.
1709
	 */
1710
	public static function get_master_user_email() {
1711
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1712
		if ( $master_user_id ) {
1713
			return self::get_connected_user_email( $master_user_id );
1714
		}
1715
		return '';
1716
	}
1717
1718
	/**
1719
	 * Whether the current user is the connection owner.
1720
	 *
1721
	 * @deprecated since 7.7
1722
	 *
1723
	 * @return bool Whether the current user is the connection owner.
1724
	 */
1725
	public function current_user_is_connection_owner() {
1726
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1727
		return self::connection()->is_connection_owner();
1728
	}
1729
1730
	/**
1731
	 * Gets current user IP address.
1732
	 *
1733
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1734
	 *
1735
	 * @return string                  Current user IP address.
1736
	 */
1737
	public static function current_user_ip( $check_all_headers = false ) {
1738
		if ( $check_all_headers ) {
1739
			foreach ( array(
1740
				'HTTP_CF_CONNECTING_IP',
1741
				'HTTP_CLIENT_IP',
1742
				'HTTP_X_FORWARDED_FOR',
1743
				'HTTP_X_FORWARDED',
1744
				'HTTP_X_CLUSTER_CLIENT_IP',
1745
				'HTTP_FORWARDED_FOR',
1746
				'HTTP_FORWARDED',
1747
				'HTTP_VIA',
1748
			) as $key ) {
1749
				if ( ! empty( $_SERVER[ $key ] ) ) {
1750
					return $_SERVER[ $key ];
1751
				}
1752
			}
1753
		}
1754
1755
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1756
	}
1757
1758
	/**
1759
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1760
	 */
1761
	function extra_oembed_providers() {
1762
		// Cloudup: https://dev.cloudup.com/#oembed
1763
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1764
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1765
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1766
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1767
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1768
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1769
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1770
	}
1771
1772
	/**
1773
	 * Synchronize connected user role changes
1774
	 */
1775
	function user_role_change( $user_id ) {
1776
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1777
		Users::user_role_change( $user_id );
1778
	}
1779
1780
	/**
1781
	 * Loads the currently active modules.
1782
	 */
1783
	public static function load_modules() {
1784
		if (
1785
			! self::is_active()
1786
			&& ! self::is_development_mode()
1787
			&& ! self::is_onboarding()
1788
			&& (
1789
				! is_multisite()
1790
				|| ! get_site_option( 'jetpack_protect_active' )
1791
			)
1792
		) {
1793
			return;
1794
		}
1795
1796
		$version = Jetpack_Options::get_option( 'version' );
1797 View Code Duplication
		if ( ! $version ) {
1798
			$version = $old_version = JETPACK__VERSION . ':' . time();
1799
			/** This action is documented in class.jetpack.php */
1800
			do_action( 'updating_jetpack_version', $version, false );
1801
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1802
		}
1803
		list( $version ) = explode( ':', $version );
1804
1805
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1806
1807
		$modules_data = array();
1808
1809
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1810
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1811
			$updated_modules = array();
1812
			foreach ( $modules as $module ) {
1813
				$modules_data[ $module ] = Jetpack::get_module( $module );
1814
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1815
					continue;
1816
				}
1817
1818
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1819
					continue;
1820
				}
1821
1822
				$updated_modules[] = $module;
1823
			}
1824
1825
			$modules = array_diff( $modules, $updated_modules );
1826
		}
1827
1828
		$is_development_mode = Jetpack::is_development_mode();
1829
1830
		foreach ( $modules as $index => $module ) {
1831
			// If we're in dev mode, disable modules requiring a connection
1832
			if ( $is_development_mode ) {
1833
				// Prime the pump if we need to
1834
				if ( empty( $modules_data[ $module ] ) ) {
1835
					$modules_data[ $module ] = Jetpack::get_module( $module );
1836
				}
1837
				// If the module requires a connection, but we're in local mode, don't include it.
1838
				if ( $modules_data[ $module ]['requires_connection'] ) {
1839
					continue;
1840
				}
1841
			}
1842
1843
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1844
				continue;
1845
			}
1846
1847
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1848
				unset( $modules[ $index ] );
1849
				self::update_active_modules( array_values( $modules ) );
1850
				continue;
1851
			}
1852
1853
			/**
1854
			 * Fires when a specific module is loaded.
1855
			 * The dynamic part of the hook, $module, is the module slug.
1856
			 *
1857
			 * @since 1.1.0
1858
			 */
1859
			do_action( 'jetpack_module_loaded_' . $module );
1860
		}
1861
1862
		/**
1863
		 * Fires when all the modules are loaded.
1864
		 *
1865
		 * @since 1.1.0
1866
		 */
1867
		do_action( 'jetpack_modules_loaded' );
1868
1869
		// 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.
1870
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1871
	}
1872
1873
	/**
1874
	 * Check if Jetpack's REST API compat file should be included
1875
	 * @action plugins_loaded
1876
	 * @return null
1877
	 */
1878
	public function check_rest_api_compat() {
1879
		/**
1880
		 * Filters the list of REST API compat files to be included.
1881
		 *
1882
		 * @since 2.2.5
1883
		 *
1884
		 * @param array $args Array of REST API compat files to include.
1885
		 */
1886
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1887
1888
		if ( function_exists( 'bbpress' ) )
1889
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1890
1891
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1892
			require_once $_jetpack_rest_api_compat_include;
1893
	}
1894
1895
	/**
1896
	 * Gets all plugins currently active in values, regardless of whether they're
1897
	 * traditionally activated or network activated.
1898
	 *
1899
	 * @todo Store the result in core's object cache maybe?
1900
	 */
1901
	public static function get_active_plugins() {
1902
		$active_plugins = (array) get_option( 'active_plugins', array() );
1903
1904
		if ( is_multisite() ) {
1905
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1906
			// whereas active_plugins stores them in the values.
1907
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1908
			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...
1909
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1910
			}
1911
		}
1912
1913
		sort( $active_plugins );
1914
1915
		return array_unique( $active_plugins );
1916
	}
1917
1918
	/**
1919
	 * Gets and parses additional plugin data to send with the heartbeat data
1920
	 *
1921
	 * @since 3.8.1
1922
	 *
1923
	 * @return array Array of plugin data
1924
	 */
1925
	public static function get_parsed_plugin_data() {
1926
		if ( ! function_exists( 'get_plugins' ) ) {
1927
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1928
		}
1929
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1930
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1931
		$active_plugins = Jetpack::get_active_plugins();
1932
1933
		$plugins = array();
1934
		foreach ( $all_plugins as $path => $plugin_data ) {
1935
			$plugins[ $path ] = array(
1936
					'is_active' => in_array( $path, $active_plugins ),
1937
					'file'      => $path,
1938
					'name'      => $plugin_data['Name'],
1939
					'version'   => $plugin_data['Version'],
1940
					'author'    => $plugin_data['Author'],
1941
			);
1942
		}
1943
1944
		return $plugins;
1945
	}
1946
1947
	/**
1948
	 * Gets and parses theme data to send with the heartbeat data
1949
	 *
1950
	 * @since 3.8.1
1951
	 *
1952
	 * @return array Array of theme data
1953
	 */
1954
	public static function get_parsed_theme_data() {
1955
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1956
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1957
1958
		$themes = array();
1959
		foreach ( $all_themes as $slug => $theme_data ) {
1960
			$theme_headers = array();
1961
			foreach ( $header_keys as $header_key ) {
1962
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1963
			}
1964
1965
			$themes[ $slug ] = array(
1966
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1967
					'slug' => $slug,
1968
					'theme_root' => $theme_data->get_theme_root_uri(),
1969
					'parent' => $theme_data->parent(),
1970
					'headers' => $theme_headers
1971
			);
1972
		}
1973
1974
		return $themes;
1975
	}
1976
1977
	/**
1978
	 * Checks whether a specific plugin is active.
1979
	 *
1980
	 * We don't want to store these in a static variable, in case
1981
	 * there are switch_to_blog() calls involved.
1982
	 */
1983
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1984
		return in_array( $plugin, self::get_active_plugins() );
1985
	}
1986
1987
	/**
1988
	 * Check if Jetpack's Open Graph tags should be used.
1989
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1990
	 *
1991
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1992
	 * @action plugins_loaded
1993
	 * @return null
1994
	 */
1995
	public function check_open_graph() {
1996
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1997
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1998
		}
1999
2000
		$active_plugins = self::get_active_plugins();
2001
2002
		if ( ! empty( $active_plugins ) ) {
2003
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2004
				if ( in_array( $plugin, $active_plugins ) ) {
2005
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2006
					break;
2007
				}
2008
			}
2009
		}
2010
2011
		/**
2012
		 * Allow the addition of Open Graph Meta Tags to all pages.
2013
		 *
2014
		 * @since 2.0.3
2015
		 *
2016
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2017
		 */
2018
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2019
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2020
		}
2021
	}
2022
2023
	/**
2024
	 * Check if Jetpack's Twitter tags should be used.
2025
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2026
	 *
2027
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2028
	 * @action plugins_loaded
2029
	 * @return null
2030
	 */
2031
	public function check_twitter_tags() {
2032
2033
		$active_plugins = self::get_active_plugins();
2034
2035
		if ( ! empty( $active_plugins ) ) {
2036
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2037
				if ( in_array( $plugin, $active_plugins ) ) {
2038
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2039
					break;
2040
				}
2041
			}
2042
		}
2043
2044
		/**
2045
		 * Allow Twitter Card Meta tags to be disabled.
2046
		 *
2047
		 * @since 2.6.0
2048
		 *
2049
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2050
		 */
2051
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2052
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2053
		}
2054
	}
2055
2056
	/**
2057
	 * Allows plugins to submit security reports.
2058
 	 *
2059
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2060
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2061
	 * @param array   $args         See definitions above
2062
	 */
2063
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2064
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2065
	}
2066
2067
/* Jetpack Options API */
2068
2069
	public static function get_option_names( $type = 'compact' ) {
2070
		return Jetpack_Options::get_option_names( $type );
2071
	}
2072
2073
	/**
2074
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2075
 	 *
2076
	 * @param string $name    Option name
2077
	 * @param mixed  $default (optional)
2078
	 */
2079
	public static function get_option( $name, $default = false ) {
2080
		return Jetpack_Options::get_option( $name, $default );
2081
	}
2082
2083
	/**
2084
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2085
 	 *
2086
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2087
	 * @param string $name  Option name
2088
	 * @param mixed  $value Option value
2089
	 */
2090
	public static function update_option( $name, $value ) {
2091
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2092
		return Jetpack_Options::update_option( $name, $value );
2093
	}
2094
2095
	/**
2096
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2097
 	 *
2098
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2099
	 * @param array $array array( option name => option value, ... )
2100
	 */
2101
	public static function update_options( $array ) {
2102
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2103
		return Jetpack_Options::update_options( $array );
2104
	}
2105
2106
	/**
2107
	 * Deletes the given option.  May be passed multiple option names as an array.
2108
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2109
	 *
2110
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2111
	 * @param string|array $names
2112
	 */
2113
	public static function delete_option( $names ) {
2114
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2115
		return Jetpack_Options::delete_option( $names );
2116
	}
2117
2118
	/**
2119
	 * Enters a user token into the user_tokens option
2120
	 *
2121
	 * @param int $user_id
2122
	 * @param string $token
2123
	 * return bool
2124
	 */
2125
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2126
		// not designed for concurrent updates
2127
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2128
		if ( ! is_array( $user_tokens ) )
2129
			$user_tokens = array();
2130
		$user_tokens[$user_id] = $token;
2131
		if ( $is_master_user ) {
2132
			$master_user = $user_id;
2133
			$options     = compact( 'user_tokens', 'master_user' );
2134
		} else {
2135
			$options = compact( 'user_tokens' );
2136
		}
2137
		return Jetpack_Options::update_options( $options );
2138
	}
2139
2140
	/**
2141
	 * Returns an array of all PHP files in the specified absolute path.
2142
	 * Equivalent to glob( "$absolute_path/*.php" ).
2143
	 *
2144
	 * @param string $absolute_path The absolute path of the directory to search.
2145
	 * @return array Array of absolute paths to the PHP files.
2146
	 */
2147
	public static function glob_php( $absolute_path ) {
2148
		if ( function_exists( 'glob' ) ) {
2149
			return glob( "$absolute_path/*.php" );
2150
		}
2151
2152
		$absolute_path = untrailingslashit( $absolute_path );
2153
		$files = array();
2154
		if ( ! $dir = @opendir( $absolute_path ) ) {
2155
			return $files;
2156
		}
2157
2158
		while ( false !== $file = readdir( $dir ) ) {
2159
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2160
				continue;
2161
			}
2162
2163
			$file = "$absolute_path/$file";
2164
2165
			if ( ! is_file( $file ) ) {
2166
				continue;
2167
			}
2168
2169
			$files[] = $file;
2170
		}
2171
2172
		closedir( $dir );
2173
2174
		return $files;
2175
	}
2176
2177
	public static function activate_new_modules( $redirect = false ) {
2178
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2179
			return;
2180
		}
2181
2182
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2183 View Code Duplication
		if ( ! $jetpack_old_version ) {
2184
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2185
			/** This action is documented in class.jetpack.php */
2186
			do_action( 'updating_jetpack_version', $version, false );
2187
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2188
		}
2189
2190
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2191
2192
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2193
			return;
2194
		}
2195
2196
		$active_modules     = Jetpack::get_active_modules();
2197
		$reactivate_modules = array();
2198
		foreach ( $active_modules as $active_module ) {
2199
			$module = Jetpack::get_module( $active_module );
2200
			if ( ! isset( $module['changed'] ) ) {
2201
				continue;
2202
			}
2203
2204
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2205
				continue;
2206
			}
2207
2208
			$reactivate_modules[] = $active_module;
2209
			Jetpack::deactivate_module( $active_module );
2210
		}
2211
2212
		$new_version = JETPACK__VERSION . ':' . time();
2213
		/** This action is documented in class.jetpack.php */
2214
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2215
		Jetpack_Options::update_options(
2216
			array(
2217
				'version'     => $new_version,
2218
				'old_version' => $jetpack_old_version,
2219
			)
2220
		);
2221
2222
		Jetpack::state( 'message', 'modules_activated' );
2223
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
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...
2224
2225
		if ( $redirect ) {
2226
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2227
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2228
				$page = $_GET['page'];
2229
			}
2230
2231
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2232
			exit;
2233
		}
2234
	}
2235
2236
	/**
2237
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2238
	 * Make sure to tuck away module "library" files in a sub-directory.
2239
	 */
2240
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2241
		static $modules = null;
2242
2243
		if ( ! isset( $modules ) ) {
2244
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2245
			// Use the cache if we're on the front-end and it's available...
2246
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2247
				$modules = $available_modules_option[ JETPACK__VERSION ];
2248
			} else {
2249
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2250
2251
				$modules = array();
2252
2253
				foreach ( $files as $file ) {
2254
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2255
						continue;
2256
					}
2257
2258
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2259
				}
2260
2261
				Jetpack_Options::update_option( 'available_modules', array(
2262
					JETPACK__VERSION => $modules,
2263
				) );
2264
			}
2265
		}
2266
2267
		/**
2268
		 * Filters the array of modules available to be activated.
2269
		 *
2270
		 * @since 2.4.0
2271
		 *
2272
		 * @param array $modules Array of available modules.
2273
		 * @param string $min_version Minimum version number required to use modules.
2274
		 * @param string $max_version Maximum version number required to use modules.
2275
		 */
2276
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2277
2278
		if ( ! $min_version && ! $max_version ) {
2279
			return array_keys( $mods );
2280
		}
2281
2282
		$r = array();
2283
		foreach ( $mods as $slug => $introduced ) {
2284
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2285
				continue;
2286
			}
2287
2288
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2289
				continue;
2290
			}
2291
2292
			$r[] = $slug;
2293
		}
2294
2295
		return $r;
2296
	}
2297
2298
	/**
2299
	 * Default modules loaded on activation.
2300
	 */
2301
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2302
		$return = array();
2303
2304
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2305
			$module_data = Jetpack::get_module( $module );
2306
2307
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2308
				case 'yes' :
2309
					$return[] = $module;
2310
					break;
2311
				case 'public' :
2312
					if ( Jetpack_Options::get_option( 'public' ) ) {
2313
						$return[] = $module;
2314
					}
2315
					break;
2316
				case 'no' :
2317
				default :
2318
					break;
2319
			}
2320
		}
2321
		/**
2322
		 * Filters the array of default modules.
2323
		 *
2324
		 * @since 2.5.0
2325
		 *
2326
		 * @param array $return Array of default modules.
2327
		 * @param string $min_version Minimum version number required to use modules.
2328
		 * @param string $max_version Maximum version number required to use modules.
2329
		 */
2330
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2331
	}
2332
2333
	/**
2334
	 * Checks activated modules during auto-activation to determine
2335
	 * if any of those modules are being deprecated.  If so, close
2336
	 * them out, and add any replacement modules.
2337
	 *
2338
	 * Runs at priority 99 by default.
2339
	 *
2340
	 * This is run late, so that it can still activate a module if
2341
	 * the new module is a replacement for another that the user
2342
	 * currently has active, even if something at the normal priority
2343
	 * would kibosh everything.
2344
	 *
2345
	 * @since 2.6
2346
	 * @uses jetpack_get_default_modules filter
2347
	 * @param array $modules
2348
	 * @return array
2349
	 */
2350
	function handle_deprecated_modules( $modules ) {
2351
		$deprecated_modules = array(
2352
			'debug'            => null,  // Closed out and moved to the debugger library.
2353
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2354
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2355
		);
2356
2357
		// Don't activate SSO if they never completed activating WPCC.
2358
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2359
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2360
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2361
				$deprecated_modules['wpcc'] = null;
2362
			}
2363
		}
2364
2365
		foreach ( $deprecated_modules as $module => $replacement ) {
2366
			if ( Jetpack::is_module_active( $module ) ) {
2367
				self::deactivate_module( $module );
2368
				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...
2369
					$modules[] = $replacement;
2370
				}
2371
			}
2372
		}
2373
2374
		return array_unique( $modules );
2375
	}
2376
2377
	/**
2378
	 * Checks activated plugins during auto-activation to determine
2379
	 * if any of those plugins are in the list with a corresponding module
2380
	 * that is not compatible with the plugin. The module will not be allowed
2381
	 * to auto-activate.
2382
	 *
2383
	 * @since 2.6
2384
	 * @uses jetpack_get_default_modules filter
2385
	 * @param array $modules
2386
	 * @return array
2387
	 */
2388
	function filter_default_modules( $modules ) {
2389
2390
		$active_plugins = self::get_active_plugins();
2391
2392
		if ( ! empty( $active_plugins ) ) {
2393
2394
			// For each module we'd like to auto-activate...
2395
			foreach ( $modules as $key => $module ) {
2396
				// If there are potential conflicts for it...
2397
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2398
					// For each potential conflict...
2399
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2400
						// If that conflicting plugin is active...
2401
						if ( in_array( $plugin, $active_plugins ) ) {
2402
							// Remove that item from being auto-activated.
2403
							unset( $modules[ $key ] );
2404
						}
2405
					}
2406
				}
2407
			}
2408
		}
2409
2410
		return $modules;
2411
	}
2412
2413
	/**
2414
	 * Extract a module's slug from its full path.
2415
	 */
2416
	public static function get_module_slug( $file ) {
2417
		return str_replace( '.php', '', basename( $file ) );
2418
	}
2419
2420
	/**
2421
	 * Generate a module's path from its slug.
2422
	 */
2423
	public static function get_module_path( $slug ) {
2424
		/**
2425
		 * Filters the path of a modules.
2426
		 *
2427
		 * @since 7.4.0
2428
		 *
2429
		 * @param array $return The absolute path to a module's root php file
2430
		 * @param string $slug The module slug
2431
		 */
2432
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2433
	}
2434
2435
	/**
2436
	 * Load module data from module file. Headers differ from WordPress
2437
	 * plugin headers to avoid them being identified as standalone
2438
	 * plugins on the WordPress plugins page.
2439
	 */
2440
	public static function get_module( $module ) {
2441
		$headers = array(
2442
			'name'                      => 'Module Name',
2443
			'description'               => 'Module Description',
2444
			'sort'                      => 'Sort Order',
2445
			'recommendation_order'      => 'Recommendation Order',
2446
			'introduced'                => 'First Introduced',
2447
			'changed'                   => 'Major Changes In',
2448
			'deactivate'                => 'Deactivate',
2449
			'free'                      => 'Free',
2450
			'requires_connection'       => 'Requires Connection',
2451
			'auto_activate'             => 'Auto Activate',
2452
			'module_tags'               => 'Module Tags',
2453
			'feature'                   => 'Feature',
2454
			'additional_search_queries' => 'Additional Search Queries',
2455
			'plan_classes'              => 'Plans',
2456
		);
2457
2458
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2459
2460
		$mod = Jetpack::get_file_data( $file, $headers );
2461
		if ( empty( $mod['name'] ) ) {
2462
			return false;
2463
		}
2464
2465
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2466
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2467
		$mod['deactivate']              = empty( $mod['deactivate'] );
2468
		$mod['free']                    = empty( $mod['free'] );
2469
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2470
2471
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2472
			$mod['auto_activate'] = 'No';
2473
		} else {
2474
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2475
		}
2476
2477
		if ( $mod['module_tags'] ) {
2478
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2479
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2480
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2481
		} else {
2482
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2483
		}
2484
2485 View Code Duplication
		if ( $mod['plan_classes'] ) {
2486
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2487
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2488
		} else {
2489
			$mod['plan_classes'] = array( 'free' );
2490
		}
2491
2492 View Code Duplication
		if ( $mod['feature'] ) {
2493
			$mod['feature'] = explode( ',', $mod['feature'] );
2494
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2495
		} else {
2496
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2497
		}
2498
2499
		/**
2500
		 * Filters the feature array on a module.
2501
		 *
2502
		 * This filter allows you to control where each module is filtered: Recommended,
2503
		 * and the default "Other" listing.
2504
		 *
2505
		 * @since 3.5.0
2506
		 *
2507
		 * @param array   $mod['feature'] The areas to feature this module:
2508
		 *     'Recommended' shows on the main Jetpack admin screen.
2509
		 *     'Other' should be the default if no other value is in the array.
2510
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2511
		 * @param array   $mod All the currently assembled module data.
2512
		 */
2513
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2514
2515
		/**
2516
		 * Filter the returned data about a module.
2517
		 *
2518
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2519
		 * so please be careful.
2520
		 *
2521
		 * @since 3.6.0
2522
		 *
2523
		 * @param array   $mod    The details of the requested module.
2524
		 * @param string  $module The slug of the module, e.g. sharedaddy
2525
		 * @param string  $file   The path to the module source file.
2526
		 */
2527
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2528
	}
2529
2530
	/**
2531
	 * Like core's get_file_data implementation, but caches the result.
2532
	 */
2533
	public static function get_file_data( $file, $headers ) {
2534
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2535
		$file_name = basename( $file );
2536
2537
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2538
2539
		$file_data_option = get_transient( $cache_key );
2540
2541
		if ( false === $file_data_option ) {
2542
			$file_data_option = array();
2543
		}
2544
2545
		$key           = md5( $file_name . serialize( $headers ) );
2546
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2547
2548
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2549
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2550
			return $file_data_option[ $key ];
2551
		}
2552
2553
		$data = get_file_data( $file, $headers );
2554
2555
		$file_data_option[ $key ] = $data;
2556
2557
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2558
2559
		return $data;
2560
	}
2561
2562
2563
	/**
2564
	 * Return translated module tag.
2565
	 *
2566
	 * @param string $tag Tag as it appears in each module heading.
2567
	 *
2568
	 * @return mixed
2569
	 */
2570
	public static function translate_module_tag( $tag ) {
2571
		return jetpack_get_module_i18n_tag( $tag );
2572
	}
2573
2574
	/**
2575
	 * Get i18n strings as a JSON-encoded string
2576
	 *
2577
	 * @return string The locale as JSON
2578
	 */
2579
	public static function get_i18n_data_json() {
2580
2581
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2582
		// JSON files with the file they should be included for. This is an md5
2583
		// of '_inc/build/admin.js'.
2584
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2585
2586
		$i18n_json =
2587
				   JETPACK__PLUGIN_DIR
2588
				   . 'languages/json/jetpack-'
2589
				   . get_user_locale()
2590
				   . '-'
2591
				   . $path_md5
2592
				   . '.json';
2593
2594
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2595
			$locale_data = @file_get_contents( $i18n_json );
2596
			if ( $locale_data ) {
2597
				return $locale_data;
2598
			}
2599
		}
2600
2601
		// Return valid empty Jed locale
2602
		return '{ "locale_data": { "messages": { "": {} } } }';
2603
	}
2604
2605
	/**
2606
	 * Add locale data setup to wp-i18n
2607
	 *
2608
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2609
	 *
2610
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2611
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2612
	 *
2613
	 * This method provides a safe way to request the setup multiple times but add the script at
2614
	 * most once.
2615
	 *
2616
	 * @since 6.7.0
2617
	 *
2618
	 * @return void
2619
	 */
2620
	public static function setup_wp_i18n_locale_data() {
2621
		static $script_added = false;
2622
		if ( ! $script_added ) {
2623
			$script_added = true;
2624
			wp_add_inline_script(
2625
				'wp-i18n',
2626
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2627
			);
2628
		}
2629
	}
2630
2631
	/**
2632
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2633
	 *
2634
	 * @since 3.9.2
2635
	 *
2636
	 * @param array $modules
2637
	 *
2638
	 * @return string|void
2639
	 */
2640
	public static function get_translated_modules( $modules ) {
2641
		foreach ( $modules as $index => $module ) {
2642
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2643
			if ( isset( $module['name'] ) ) {
2644
				$modules[ $index ]['name'] = $i18n_module['name'];
2645
			}
2646
			if ( isset( $module['description'] ) ) {
2647
				$modules[ $index ]['description'] = $i18n_module['description'];
2648
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2649
			}
2650
		}
2651
		return $modules;
2652
	}
2653
2654
	/**
2655
	 * Get a list of activated modules as an array of module slugs.
2656
	 */
2657
	public static function get_active_modules() {
2658
		$active = Jetpack_Options::get_option( 'active_modules' );
2659
2660
		if ( ! is_array( $active ) ) {
2661
			$active = array();
2662
		}
2663
2664
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2665
			$active[] = 'vaultpress';
2666
		} else {
2667
			$active = array_diff( $active, array( 'vaultpress' ) );
2668
		}
2669
2670
		//If protect is active on the main site of a multisite, it should be active on all sites.
2671
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2672
			$active[] = 'protect';
2673
		}
2674
2675
		/**
2676
		 * Allow filtering of the active modules.
2677
		 *
2678
		 * Gives theme and plugin developers the power to alter the modules that
2679
		 * are activated on the fly.
2680
		 *
2681
		 * @since 5.8.0
2682
		 *
2683
		 * @param array $active Array of active module slugs.
2684
		 */
2685
		$active = apply_filters( 'jetpack_active_modules', $active );
2686
2687
		return array_unique( $active );
2688
	}
2689
2690
	/**
2691
	 * Check whether or not a Jetpack module is active.
2692
	 *
2693
	 * @param string $module The slug of a Jetpack module.
2694
	 * @return bool
2695
	 *
2696
	 * @static
2697
	 */
2698
	public static function is_module_active( $module ) {
2699
		return in_array( $module, self::get_active_modules() );
2700
	}
2701
2702
	public static function is_module( $module ) {
2703
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2704
	}
2705
2706
	/**
2707
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2708
	 *
2709
	 * @param bool $catch True to start catching, False to stop.
2710
	 *
2711
	 * @static
2712
	 */
2713
	public static function catch_errors( $catch ) {
2714
		static $display_errors, $error_reporting;
2715
2716
		if ( $catch ) {
2717
			$display_errors  = @ini_set( 'display_errors', 1 );
2718
			$error_reporting = @error_reporting( E_ALL );
2719
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2720
		} else {
2721
			@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...
2722
			@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...
2723
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2724
		}
2725
	}
2726
2727
	/**
2728
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2729
	 */
2730
	public static function catch_errors_on_shutdown() {
2731
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2732
	}
2733
2734
	/**
2735
	 * Rewrite any string to make paths easier to read.
2736
	 *
2737
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2738
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2739
	 *
2740
	 * @param $string
2741
	 * @return mixed
2742
	 */
2743
	public static function alias_directories( $string ) {
2744
		// ABSPATH has a trailing slash.
2745
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2746
		// WP_CONTENT_DIR does not have a trailing slash.
2747
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2748
2749
		return $string;
2750
	}
2751
2752
	public static function activate_default_modules(
2753
		$min_version = false,
2754
		$max_version = false,
2755
		$other_modules = array(),
2756
		$redirect = true,
2757
		$send_state_messages = true
2758
	) {
2759
		$jetpack = Jetpack::init();
2760
2761
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2762
		$modules = array_merge( $other_modules, $modules );
2763
2764
		// Look for standalone plugins and disable if active.
2765
2766
		$to_deactivate = array();
2767
		foreach ( $modules as $module ) {
2768
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2769
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2770
			}
2771
		}
2772
2773
		$deactivated = array();
2774
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2775
			list( $probable_file, $probable_title ) = $deactivate_me;
2776
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2777
				$deactivated[] = $module;
2778
			}
2779
		}
2780
2781
		if ( $deactivated && $redirect ) {
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...
2782
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2783
2784
			$url = add_query_arg(
2785
				array(
2786
					'action'   => 'activate_default_modules',
2787
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2788
				),
2789
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2790
			);
2791
			wp_safe_redirect( $url );
2792
			exit;
2793
		}
2794
2795
		/**
2796
		 * Fires before default modules are activated.
2797
		 *
2798
		 * @since 1.9.0
2799
		 *
2800
		 * @param string $min_version Minimum version number required to use modules.
2801
		 * @param string $max_version Maximum version number required to use modules.
2802
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2803
		 */
2804
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2805
2806
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2807
		if ( $send_state_messages ) {
2808
			Jetpack::restate();
2809
			Jetpack::catch_errors( true );
2810
		}
2811
2812
		$active = Jetpack::get_active_modules();
2813
2814
		foreach ( $modules as $module ) {
2815
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2816
				$active[] = $module;
2817
				self::update_active_modules( $active );
2818
				continue;
2819
			}
2820
2821
			if ( $send_state_messages && in_array( $module, $active ) ) {
2822
				$module_info = Jetpack::get_module( $module );
2823 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2824
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2825
					if ( $active_state = Jetpack::state( $state ) ) {
2826
						$active_state = explode( ',', $active_state );
2827
					} else {
2828
						$active_state = array();
2829
					}
2830
					$active_state[] = $module;
2831
					Jetpack::state( $state, implode( ',', $active_state ) );
2832
				}
2833
				continue;
2834
			}
2835
2836
			$file = Jetpack::get_module_path( $module );
2837
			if ( ! file_exists( $file ) ) {
2838
				continue;
2839
			}
2840
2841
			// we'll override this later if the plugin can be included without fatal error
2842
			if ( $redirect ) {
2843
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2844
			}
2845
2846
			if ( $send_state_messages ) {
2847
				Jetpack::state( 'error', 'module_activation_failed' );
2848
				Jetpack::state( 'module', $module );
2849
			}
2850
2851
			ob_start();
2852
			require_once $file;
2853
2854
			$active[] = $module;
2855
2856 View Code Duplication
			if ( $send_state_messages ) {
2857
2858
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2859
				if ( $active_state = Jetpack::state( $state ) ) {
2860
					$active_state = explode( ',', $active_state );
2861
				} else {
2862
					$active_state = array();
2863
				}
2864
				$active_state[] = $module;
2865
				Jetpack::state( $state, implode( ',', $active_state ) );
2866
			}
2867
2868
			Jetpack::update_active_modules( $active );
2869
2870
			ob_end_clean();
2871
		}
2872
2873
		if ( $send_state_messages ) {
2874
			Jetpack::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...
2875
			Jetpack::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...
2876
		}
2877
2878
		Jetpack::catch_errors( false );
2879
		/**
2880
		 * Fires when default modules are activated.
2881
		 *
2882
		 * @since 1.9.0
2883
		 *
2884
		 * @param string $min_version Minimum version number required to use modules.
2885
		 * @param string $max_version Maximum version number required to use modules.
2886
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2887
		 */
2888
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2889
	}
2890
2891
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2892
		/**
2893
		 * Fires before a module is activated.
2894
		 *
2895
		 * @since 2.6.0
2896
		 *
2897
		 * @param string $module Module slug.
2898
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2899
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2900
		 */
2901
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2902
2903
		$jetpack = Jetpack::init();
2904
2905
		if ( ! strlen( $module ) )
2906
			return false;
2907
2908
		if ( ! Jetpack::is_module( $module ) )
2909
			return false;
2910
2911
		// If it's already active, then don't do it again
2912
		$active = Jetpack::get_active_modules();
2913
		foreach ( $active as $act ) {
2914
			if ( $act == $module )
2915
				return true;
2916
		}
2917
2918
		$module_data = Jetpack::get_module( $module );
2919
2920
		if ( ! Jetpack::is_active() ) {
2921
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2922
				return false;
2923
2924
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2925
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2926
				return false;
2927
		}
2928
2929
		// Check and see if the old plugin is active
2930
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2931
			// Deactivate the old plugin
2932
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2933
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2934
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2935
				Jetpack::state( 'deactivated_plugins', $module );
2936
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2937
				exit;
2938
			}
2939
		}
2940
2941
		// Protect won't work with mis-configured IPs
2942
		if ( 'protect' === $module ) {
2943
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2944
			if ( ! jetpack_protect_get_ip() ) {
2945
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2946
				return false;
2947
			}
2948
		}
2949
2950
		if ( ! Jetpack_Plan::supports( $module ) ) {
2951
			return false;
2952
		}
2953
2954
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2955
		Jetpack::state( 'module', $module );
2956
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2957
2958
		Jetpack::catch_errors( true );
2959
		ob_start();
2960
		require Jetpack::get_module_path( $module );
2961
		/** This action is documented in class.jetpack.php */
2962
		do_action( 'jetpack_activate_module', $module );
2963
		$active[] = $module;
2964
		Jetpack::update_active_modules( $active );
2965
2966
		Jetpack::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...
2967
		ob_end_clean();
2968
		Jetpack::catch_errors( false );
2969
2970
		if ( $redirect ) {
2971
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2972
		}
2973
		if ( $exit ) {
2974
			exit;
2975
		}
2976
		return true;
2977
	}
2978
2979
	function activate_module_actions( $module ) {
2980
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2981
	}
2982
2983
	public static function deactivate_module( $module ) {
2984
		/**
2985
		 * Fires when a module is deactivated.
2986
		 *
2987
		 * @since 1.9.0
2988
		 *
2989
		 * @param string $module Module slug.
2990
		 */
2991
		do_action( 'jetpack_pre_deactivate_module', $module );
2992
2993
		$jetpack = Jetpack::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...
2994
2995
		$active = Jetpack::get_active_modules();
2996
		$new    = array_filter( array_diff( $active, (array) $module ) );
2997
2998
		return self::update_active_modules( $new );
2999
	}
3000
3001
	public static function enable_module_configurable( $module ) {
3002
		$module = Jetpack::get_module_slug( $module );
3003
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3004
	}
3005
3006
	/**
3007
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3008
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3009
	 *
3010
	 * @param string $module Module slug
3011
	 * @return string $url module configuration URL
3012
	 */
3013
	public static function module_configuration_url( $module ) {
3014
		$module = Jetpack::get_module_slug( $module );
3015
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3016
		/**
3017
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3018
		 *
3019
		 * @since 6.9.0
3020
		 *
3021
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3022
		 */
3023
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3024
3025
		return $url;
3026
	}
3027
3028
/* Installation */
3029
	public static function bail_on_activation( $message, $deactivate = true ) {
3030
?>
3031
<!doctype html>
3032
<html>
3033
<head>
3034
<meta charset="<?php bloginfo( 'charset' ); ?>">
3035
<style>
3036
* {
3037
	text-align: center;
3038
	margin: 0;
3039
	padding: 0;
3040
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3041
}
3042
p {
3043
	margin-top: 1em;
3044
	font-size: 18px;
3045
}
3046
</style>
3047
<body>
3048
<p><?php echo esc_html( $message ); ?></p>
3049
</body>
3050
</html>
3051
<?php
3052
		if ( $deactivate ) {
3053
			$plugins = get_option( 'active_plugins' );
3054
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3055
			$update  = false;
3056
			foreach ( $plugins as $i => $plugin ) {
3057
				if ( $plugin === $jetpack ) {
3058
					$plugins[$i] = false;
3059
					$update = true;
3060
				}
3061
			}
3062
3063
			if ( $update ) {
3064
				update_option( 'active_plugins', array_filter( $plugins ) );
3065
			}
3066
		}
3067
		exit;
3068
	}
3069
3070
	/**
3071
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3072
	 * @static
3073
	 */
3074
	public static function plugin_activation( $network_wide ) {
3075
		Jetpack_Options::update_option( 'activated', 1 );
3076
3077
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3078
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3079
		}
3080
3081
		if ( $network_wide )
3082
			Jetpack::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...
3083
3084
		// For firing one-off events (notices) immediately after activation
3085
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3086
3087
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3088
3089
		Jetpack::plugin_initialize();
3090
	}
3091
3092
	public static function get_activation_source( $referer_url ) {
3093
3094
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3095
			return array( 'wp-cli', null );
3096
		}
3097
3098
		$referer = parse_url( $referer_url );
3099
3100
		$source_type = 'unknown';
3101
		$source_query = null;
3102
3103
		if ( ! is_array( $referer ) ) {
3104
			return array( $source_type, $source_query );
3105
		}
3106
3107
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3108
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3109
3110
		if ( isset( $referer['query'] ) ) {
3111
			parse_str( $referer['query'], $query_parts );
3112
		} else {
3113
			$query_parts = array();
3114
		}
3115
3116
		if ( $plugins_path === $referer['path'] ) {
3117
			$source_type = 'list';
3118
		} elseif ( $plugins_install_path === $referer['path'] ) {
3119
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3120
			switch( $tab ) {
3121
				case 'popular':
3122
					$source_type = 'popular';
3123
					break;
3124
				case 'recommended':
3125
					$source_type = 'recommended';
3126
					break;
3127
				case 'favorites':
3128
					$source_type = 'favorites';
3129
					break;
3130
				case 'search':
3131
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3132
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3133
					break;
3134
				default:
3135
					$source_type = 'featured';
3136
			}
3137
		}
3138
3139
		return array( $source_type, $source_query );
3140
	}
3141
3142
	/**
3143
	 * Runs before bumping version numbers up to a new version
3144
	 * @param  string $version    Version:timestamp
3145
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3146
	 * @return null              [description]
3147
	 */
3148
	public static function do_version_bump( $version, $old_version ) {
3149
		if ( ! $old_version ) { // For new sites
3150
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3151
		}
3152
	}
3153
3154
	/**
3155
	 * Sets the internal version number and activation state.
3156
	 * @static
3157
	 */
3158
	public static function plugin_initialize() {
3159
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3160
			Jetpack_Options::update_option( 'activated', 2 );
3161
		}
3162
3163 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3164
			$version = $old_version = JETPACK__VERSION . ':' . time();
3165
			/** This action is documented in class.jetpack.php */
3166
			do_action( 'updating_jetpack_version', $version, false );
3167
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3168
		}
3169
3170
		Jetpack::load_modules();
3171
3172
		Jetpack_Options::delete_option( 'do_activate' );
3173
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3174
	}
3175
3176
	/**
3177
	 * Removes all connection options
3178
	 * @static
3179
	 */
3180
	public static function plugin_deactivation( ) {
3181
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3182
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3183
			Jetpack_Network::init()->deactivate();
3184
		} else {
3185
			Jetpack::disconnect( false );
3186
			//Jetpack_Heartbeat::init()->deactivate();
3187
		}
3188
	}
3189
3190
	/**
3191
	 * Disconnects from the Jetpack servers.
3192
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3193
	 * @static
3194
	 */
3195
	public static function disconnect( $update_activated_state = true ) {
3196
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3197
		$connection = self::connection();
3198
		$connection->clean_nonces( true );
3199
3200
		// If the site is in an IDC because sync is not allowed,
3201
		// let's make sure to not disconnect the production site.
3202
		if ( ! self::validate_sync_error_idc_option() ) {
3203
			$tracking = new Tracking();
3204
			$tracking->record_user_event( 'disconnect_site', array() );
3205
			Jetpack::load_xml_rpc_client();
3206
			$xml = new Jetpack_IXR_Client();
3207
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3208
		}
3209
3210
		Jetpack_Options::delete_option(
3211
			array(
3212
				'blog_token',
3213
				'user_token',
3214
				'user_tokens',
3215
				'master_user',
3216
				'time_diff',
3217
				'fallback_no_verify_ssl_certs',
3218
			)
3219
		);
3220
3221
		Jetpack_IDC::clear_all_idc_options();
3222
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3223
3224
		if ( $update_activated_state ) {
3225
			Jetpack_Options::update_option( 'activated', 4 );
3226
		}
3227
3228
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3229
			// Check then record unique disconnection if site has never been disconnected previously
3230
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3231
				$jetpack_unique_connection['disconnected'] = 1;
3232
			} else {
3233
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3234
					//track unique disconnect
3235
					$jetpack = Jetpack::init();
3236
3237
					$jetpack->stat( 'connections', 'unique-disconnect' );
3238
					$jetpack->do_stats( 'server_side' );
3239
				}
3240
				// increment number of times disconnected
3241
				$jetpack_unique_connection['disconnected'] += 1;
3242
			}
3243
3244
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3245
		}
3246
3247
		// Delete cached connected user data
3248
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3249
		delete_transient( $transient_key );
3250
3251
		// Delete all the sync related data. Since it could be taking up space.
3252
		Sender::get_instance()->uninstall();
3253
3254
		// Disable the Heartbeat cron
3255
		Jetpack_Heartbeat::init()->deactivate();
3256
	}
3257
3258
	/**
3259
	 * Unlinks the current user from the linked WordPress.com user
3260
	 */
3261
	public static function unlink_user( $user_id = null ) {
3262
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3263
			return false;
3264
3265
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3266
3267
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3268
			return false;
3269
3270
		if ( ! isset( $tokens[ $user_id ] ) )
3271
			return false;
3272
3273
		Jetpack::load_xml_rpc_client();
3274
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3275
		$xml->query( 'jetpack.unlink_user', $user_id );
3276
3277
		unset( $tokens[ $user_id ] );
3278
3279
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3280
3281
		/**
3282
		 * Fires after the current user has been unlinked from WordPress.com.
3283
		 *
3284
		 * @since 4.1.0
3285
		 *
3286
		 * @param int $user_id The current user's ID.
3287
		 */
3288
		do_action( 'jetpack_unlinked_user', $user_id );
3289
3290
		return true;
3291
	}
3292
3293
	/**
3294
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3295
	 */
3296
	public static function try_registration() {
3297
		// The user has agreed to the TOS at some point by now.
3298
		Jetpack_Options::update_option( 'tos_agreed', true );
3299
3300
		// Let's get some testing in beta versions and such.
3301
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3302
			// Before attempting to connect, let's make sure that the domains are viable.
3303
			$domains_to_check = array_unique( array(
3304
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3305
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3306
			) );
3307
			foreach ( $domains_to_check as $domain ) {
3308
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3307 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...
3309
				if ( is_wp_error( $result ) ) {
3310
					return $result;
3311
				}
3312
			}
3313
		}
3314
3315
		$result = Jetpack::register();
3316
3317
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3318
		if ( ! $result || is_wp_error( $result ) ) {
3319
			return $result;
3320
		} else {
3321
			return true;
3322
		}
3323
	}
3324
3325
	/**
3326
	 * Tracking an internal event log. Try not to put too much chaff in here.
3327
	 *
3328
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3329
	 */
3330
	public static function log( $code, $data = null ) {
3331
		// only grab the latest 200 entries
3332
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3333
3334
		// Append our event to the log
3335
		$log_entry = array(
3336
			'time'    => time(),
3337
			'user_id' => get_current_user_id(),
3338
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3339
			'code'    => $code,
3340
		);
3341
		// Don't bother storing it unless we've got some.
3342
		if ( ! is_null( $data ) ) {
3343
			$log_entry['data'] = $data;
3344
		}
3345
		$log[] = $log_entry;
3346
3347
		// Try add_option first, to make sure it's not autoloaded.
3348
		// @todo: Add an add_option method to Jetpack_Options
3349
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3350
			Jetpack_Options::update_option( 'log', $log );
3351
		}
3352
3353
		/**
3354
		 * Fires when Jetpack logs an internal event.
3355
		 *
3356
		 * @since 3.0.0
3357
		 *
3358
		 * @param array $log_entry {
3359
		 *	Array of details about the log entry.
3360
		 *
3361
		 *	@param string time Time of the event.
3362
		 *	@param int user_id ID of the user who trigerred the event.
3363
		 *	@param int blog_id Jetpack Blog ID.
3364
		 *	@param string code Unique name for the event.
3365
		 *	@param string data Data about the event.
3366
		 * }
3367
		 */
3368
		do_action( 'jetpack_log_entry', $log_entry );
3369
	}
3370
3371
	/**
3372
	 * Get the internal event log.
3373
	 *
3374
	 * @param $event (string) - only return the specific log events
3375
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3376
	 *
3377
	 * @return array of log events || WP_Error for invalid params
3378
	 */
3379
	public static function get_log( $event = false, $num = false ) {
3380
		if ( $event && ! is_string( $event ) ) {
3381
			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...
3382
		}
3383
3384
		if ( $num && ! is_numeric( $num ) ) {
3385
			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...
3386
		}
3387
3388
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3389
3390
		// If nothing set - act as it did before, otherwise let's start customizing the output
3391
		if ( ! $num && ! $event ) {
3392
			return $entire_log;
3393
		} else {
3394
			$entire_log = array_reverse( $entire_log );
3395
		}
3396
3397
		$custom_log_output = array();
3398
3399
		if ( $event ) {
3400
			foreach ( $entire_log as $log_event ) {
3401
				if ( $event == $log_event[ 'code' ] ) {
3402
					$custom_log_output[] = $log_event;
3403
				}
3404
			}
3405
		} else {
3406
			$custom_log_output = $entire_log;
3407
		}
3408
3409
		if ( $num ) {
3410
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3411
		}
3412
3413
		return $custom_log_output;
3414
	}
3415
3416
	/**
3417
	 * Log modification of important settings.
3418
	 */
3419
	public static function log_settings_change( $option, $old_value, $value ) {
3420
		switch( $option ) {
3421
			case 'jetpack_sync_non_public_post_stati':
3422
				self::log( $option, $value );
3423
				break;
3424
		}
3425
	}
3426
3427
	/**
3428
	 * Return stat data for WPCOM sync
3429
	 */
3430
	public static function get_stat_data( $encode = true, $extended = true ) {
3431
		$data = Jetpack_Heartbeat::generate_stats_array();
3432
3433
		if ( $extended ) {
3434
			$additional_data = self::get_additional_stat_data();
3435
			$data = array_merge( $data, $additional_data );
3436
		}
3437
3438
		if ( $encode ) {
3439
			return json_encode( $data );
3440
		}
3441
3442
		return $data;
3443
	}
3444
3445
	/**
3446
	 * Get additional stat data to sync to WPCOM
3447
	 */
3448
	public static function get_additional_stat_data( $prefix = '' ) {
3449
		$return["{$prefix}themes"]         = Jetpack::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...
3450
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3451
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3452
		$return["{$prefix}site-count"]     = 0;
3453
3454
		if ( function_exists( 'get_blog_count' ) ) {
3455
			$return["{$prefix}site-count"] = get_blog_count();
3456
		}
3457
		return $return;
3458
	}
3459
3460
	private static function get_site_user_count() {
3461
		global $wpdb;
3462
3463
		if ( function_exists( 'wp_is_large_network' ) ) {
3464
			if ( wp_is_large_network( 'users' ) ) {
3465
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3466
			}
3467
		}
3468
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3469
			// It wasn't there, so regenerate the data and save the transient
3470
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3471
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3472
		}
3473
		return $user_count;
3474
	}
3475
3476
	/* Admin Pages */
3477
3478
	function admin_init() {
3479
		// If the plugin is not connected, display a connect message.
3480
		if (
3481
			// the plugin was auto-activated and needs its candy
3482
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3483
		||
3484
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3485
			! Jetpack_Options::get_option( 'activated' )
3486
		) {
3487
			Jetpack::plugin_initialize();
3488
		}
3489
3490
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3491
			Jetpack_Connection_Banner::init();
3492
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3493
			// Upgrade: 1.1 -> 1.1.1
3494
			// Check and see if host can verify the Jetpack servers' SSL certificate
3495
			$args = array();
3496
			$connection = self::connection();
3497
			Client::_wp_remote_request(
3498
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3499
				$args,
3500
				true
3501
			);
3502
		}
3503
3504
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3505
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3506
		}
3507
3508
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3509
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3510
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3511
3512
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3513
			// Artificially throw errors in certain whitelisted cases during plugin activation
3514
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3515
		}
3516
3517
		// Add custom column in wp-admin/users.php to show whether user is linked.
3518
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3519
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3520
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3521
	}
3522
3523
	function admin_body_class( $admin_body_class = '' ) {
3524
		$classes = explode( ' ', trim( $admin_body_class ) );
3525
3526
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3527
3528
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3529
		return " $admin_body_class ";
3530
	}
3531
3532
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3533
		return $admin_body_class . ' jetpack-pagestyles ';
3534
	}
3535
3536
	/**
3537
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3538
	 * This function artificially throws errors for such cases (whitelisted).
3539
	 *
3540
	 * @param string $plugin The activated plugin.
3541
	 */
3542
	function throw_error_on_activate_plugin( $plugin ) {
3543
		$active_modules = Jetpack::get_active_modules();
3544
3545
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3546
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3547
			$throw = false;
3548
3549
			// Try and make sure it really was the stats plugin
3550
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3551
				if ( 'stats.php' == basename( $plugin ) ) {
3552
					$throw = true;
3553
				}
3554
			} else {
3555
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3556
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3557
					$throw = true;
3558
				}
3559
			}
3560
3561
			if ( $throw ) {
3562
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3563
			}
3564
		}
3565
	}
3566
3567
	function intercept_plugin_error_scrape_init() {
3568
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3569
	}
3570
3571
	function intercept_plugin_error_scrape( $action, $result ) {
3572
		if ( ! $result ) {
3573
			return;
3574
		}
3575
3576
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3577
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3578
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3579
			}
3580
		}
3581
	}
3582
3583
	function add_remote_request_handlers() {
3584
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3585
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3586
	}
3587
3588
	function remote_request_handlers() {
3589
		$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...
3590
3591
		switch ( current_filter() ) {
3592
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3593
			$response = $this->upload_handler();
3594
			break;
3595
3596
		case 'wp_ajax_nopriv_jetpack_update_file' :
3597
			$response = $this->upload_handler( true );
3598
			break;
3599
		default :
3600
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3601
			break;
3602
		}
3603
3604
		if ( ! $response ) {
3605
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3606
		}
3607
3608
		if ( is_wp_error( $response ) ) {
3609
			$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<Jetpack_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...
3610
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<Jetpack_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...
3611
			$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<Jetpack_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...
3612
3613
			if ( ! is_int( $status_code ) ) {
3614
				$status_code = 400;
3615
			}
3616
3617
			status_header( $status_code );
3618
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3619
		}
3620
3621
		status_header( 200 );
3622
		if ( true === $response ) {
3623
			exit;
3624
		}
3625
3626
		die( json_encode( (object) $response ) );
3627
	}
3628
3629
	/**
3630
	 * Uploads a file gotten from the global $_FILES.
3631
	 * If `$update_media_item` is true and `post_id` is defined
3632
	 * the attachment file of the media item (gotten through of the post_id)
3633
	 * will be updated instead of add a new one.
3634
	 *
3635
	 * @param  boolean $update_media_item - update media attachment
3636
	 * @return array - An array describing the uploadind files process
3637
	 */
3638
	function upload_handler( $update_media_item = false ) {
3639
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3640
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3641
		}
3642
3643
		$user = wp_authenticate( '', '' );
3644
		if ( ! $user || is_wp_error( $user ) ) {
3645
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3646
		}
3647
3648
		wp_set_current_user( $user->ID );
3649
3650
		if ( ! current_user_can( 'upload_files' ) ) {
3651
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3652
		}
3653
3654
		if ( empty( $_FILES ) ) {
3655
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3656
		}
3657
3658
		foreach ( array_keys( $_FILES ) as $files_key ) {
3659
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3660
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3661
			}
3662
		}
3663
3664
		$media_keys = array_keys( $_FILES['media'] );
3665
3666
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
3667
		if ( ! $token || is_wp_error( $token ) ) {
3668
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3669
		}
3670
3671
		$uploaded_files = array();
3672
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3673
		unset( $GLOBALS['post'] );
3674
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3675
			$file = array();
3676
			foreach ( $media_keys as $media_key ) {
3677
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3678
			}
3679
3680
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3681
3682
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3683
			if ( $hmac_provided !== $hmac_file ) {
3684
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3685
				continue;
3686
			}
3687
3688
			$_FILES['.jetpack.upload.'] = $file;
3689
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3690
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3691
				$post_id = 0;
3692
			}
3693
3694
			if ( $update_media_item ) {
3695
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3696
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_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...
3697
				}
3698
3699
				$media_array = $_FILES['media'];
3700
3701
				$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...
3702
				$file_array['type'] = $media_array['type'][0];
3703
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3704
				$file_array['error'] = $media_array['error'][0];
3705
				$file_array['size'] = $media_array['size'][0];
3706
3707
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3708
3709
				if ( is_wp_error( $edited_media_item ) ) {
3710
					return $edited_media_item;
3711
				}
3712
3713
				$response = (object) array(
3714
					'id'   => (string) $post_id,
3715
					'file' => (string) $edited_media_item->post_title,
3716
					'url'  => (string) wp_get_attachment_url( $post_id ),
3717
					'type' => (string) $edited_media_item->post_mime_type,
3718
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3719
				);
3720
3721
				return (array) array( $response );
3722
			}
3723
3724
			$attachment_id = media_handle_upload(
3725
				'.jetpack.upload.',
3726
				$post_id,
3727
				array(),
3728
				array(
3729
					'action' => 'jetpack_upload_file',
3730
				)
3731
			);
3732
3733
			if ( ! $attachment_id ) {
3734
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3735
			} elseif ( is_wp_error( $attachment_id ) ) {
3736
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3737
			} else {
3738
				$attachment = get_post( $attachment_id );
3739
				$uploaded_files[$index] = (object) array(
3740
					'id'   => (string) $attachment_id,
3741
					'file' => $attachment->post_title,
3742
					'url'  => wp_get_attachment_url( $attachment_id ),
3743
					'type' => $attachment->post_mime_type,
3744
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3745
				);
3746
				// Zip files uploads are not supported unless they are done for installation purposed
3747
				// lets delete them in case something goes wrong in this whole process
3748
				if ( 'application/zip' === $attachment->post_mime_type ) {
3749
					// Schedule a cleanup for 2 hours from now in case of failed install.
3750
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3751
				}
3752
			}
3753
		}
3754
		if ( ! is_null( $global_post ) ) {
3755
			$GLOBALS['post'] = $global_post;
3756
		}
3757
3758
		return $uploaded_files;
3759
	}
3760
3761
	/**
3762
	 * Add help to the Jetpack page
3763
	 *
3764
	 * @since Jetpack (1.2.3)
3765
	 * @return false if not the Jetpack page
3766
	 */
3767
	function admin_help() {
3768
		$current_screen = get_current_screen();
3769
3770
		// Overview
3771
		$current_screen->add_help_tab(
3772
			array(
3773
				'id'		=> 'home',
3774
				'title'		=> __( 'Home', 'jetpack' ),
3775
				'content'	=>
3776
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3777
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3778
					'<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>',
3779
			)
3780
		);
3781
3782
		// Screen Content
3783
		if ( current_user_can( 'manage_options' ) ) {
3784
			$current_screen->add_help_tab(
3785
				array(
3786
					'id'		=> 'settings',
3787
					'title'		=> __( 'Settings', 'jetpack' ),
3788
					'content'	=>
3789
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3790
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3791
						'<ol>' .
3792
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3793
							'<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>' .
3794
						'</ol>' .
3795
						'<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>'
3796
				)
3797
			);
3798
		}
3799
3800
		// Help Sidebar
3801
		$current_screen->set_help_sidebar(
3802
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3803
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3804
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3805
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3806
		);
3807
	}
3808
3809
	function admin_menu_css() {
3810
		wp_enqueue_style( 'jetpack-icons' );
3811
	}
3812
3813
	function admin_menu_order() {
3814
		return true;
3815
	}
3816
3817 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3818
		$jp_menu_order = array();
3819
3820
		foreach ( $menu_order as $index => $item ) {
3821
			if ( $item != 'jetpack' ) {
3822
				$jp_menu_order[] = $item;
3823
			}
3824
3825
			if ( $index == 0 ) {
3826
				$jp_menu_order[] = 'jetpack';
3827
			}
3828
		}
3829
3830
		return $jp_menu_order;
3831
	}
3832
3833
	function admin_banner_styles() {
3834
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3835
3836
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3837
			wp_register_style(
3838
				'jetpack-dops-style',
3839
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3840
				array(),
3841
				JETPACK__VERSION
3842
			);
3843
		}
3844
3845
		wp_enqueue_style(
3846
			'jetpack',
3847
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3848
			array( 'jetpack-dops-style' ),
3849
			 JETPACK__VERSION . '-20121016'
3850
		);
3851
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3852
		wp_style_add_data( 'jetpack', 'suffix', $min );
3853
	}
3854
3855
	function plugin_action_links( $actions ) {
3856
3857
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3858
3859
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3860
			return array_merge(
3861
				$jetpack_home,
3862
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3863
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3864
				$actions
3865
				);
3866
			}
3867
3868
		return array_merge( $jetpack_home, $actions );
3869
	}
3870
3871
	/*
3872
	 * Registration flow:
3873
	 * 1 - ::admin_page_load() action=register
3874
	 * 2 - ::try_registration()
3875
	 * 3 - ::register()
3876
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3877
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3878
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3879
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3880
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3881
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3882
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3883
	 *       jetpack_id, jetpack_secret, jetpack_public
3884
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3885
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3886
	 * 5 - user logs in with WP.com account
3887
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3888
	 *		- Jetpack_Client_Server::authorize()
3889
	 *		- Jetpack_Client_Server::get_token()
3890
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3891
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3892
	 *			- which responds with access_token, token_type, scope
3893
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3894
	 *		- Jetpack::activate_default_modules()
3895
	 *     		- Deactivates deprecated plugins
3896
	 *     		- Activates all default modules
3897
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3898
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3899
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3900
	 *     Done!
3901
	 */
3902
3903
	/**
3904
	 * Handles the page load events for the Jetpack admin page
3905
	 */
3906
	function admin_page_load() {
3907
		$error = false;
3908
3909
		// Make sure we have the right body class to hook stylings for subpages off of.
3910
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3911
3912
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3913
			// Should only be used in intermediate redirects to preserve state across redirects
3914
			Jetpack::restate();
3915
		}
3916
3917
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3918
			// @todo: Add validation against a known whitelist
3919
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3920
			// User clicked in the iframe to link their accounts
3921
			if ( ! Jetpack::is_user_connected() ) {
3922
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3923
3924
				add_filter( 'allowed_redirect_hosts', array( self::connection(), 'allow_wpcom_environments' ) );
3925
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3926
				remove_filter( 'allowed_redirect_hosts', array( self::connection(), 'allow_wpcom_environments' ) );
3927
3928
				if ( isset( $_GET['notes_iframe'] ) )
3929
					$connect_url .= '&notes_iframe';
3930
				wp_redirect( $connect_url );
3931
				exit;
3932
			} else {
3933
				if ( ! isset( $_GET['calypso_env'] ) ) {
3934
					Jetpack::state( 'message', 'already_authorized' );
3935
					wp_safe_redirect( Jetpack::admin_url() );
3936
					exit;
3937
				} else {
3938
					$connect_url = $this->build_connect_url( true, false, $from );
3939
					$connect_url .= '&already_authorized=true';
3940
					wp_redirect( $connect_url );
3941
					exit;
3942
				}
3943
			}
3944
		}
3945
3946
3947
		if ( isset( $_GET['action'] ) ) {
3948
			switch ( $_GET['action'] ) {
3949
			case 'authorize':
3950
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3951
					Jetpack::state( 'message', 'already_authorized' );
3952
					wp_safe_redirect( Jetpack::admin_url() );
3953
					exit;
3954
				}
3955
				Jetpack::log( 'authorize' );
3956
				$client_server = new Jetpack_Client_Server;
3957
				$client_server->client_authorize();
3958
				exit;
3959
			case 'register' :
3960
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3961
					$error = 'cheatin';
3962
					break;
3963
				}
3964
				check_admin_referer( 'jetpack-register' );
3965
				Jetpack::log( 'register' );
3966
				Jetpack::maybe_set_version_option();
3967
				$registered = Jetpack::try_registration();
3968
				if ( is_wp_error( $registered ) ) {
3969
					$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...
3970
					Jetpack::state( 'error', $error );
3971
					Jetpack::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...
3972
3973
					/**
3974
					 * Jetpack registration Error.
3975
					 *
3976
					 * @since 7.5.0
3977
					 *
3978
					 * @param string|int $error The error code.
3979
					 * @param \WP_Error $registered The error object.
3980
					 */
3981
					do_action( 'jetpack_connection_register_fail', $error, $registered );
3982
					break;
3983
				}
3984
3985
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3986
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3987
3988
				/**
3989
				 * Jetpack registration Success.
3990
				 *
3991
				 * @since 7.5.0
3992
				 *
3993
				 * @param string $from 'from' GET parameter;
3994
				 */
3995
				do_action( 'jetpack_connection_register_success', $from );
3996
3997
				$url = $this->build_connect_url( true, $redirect, $from );
3998
3999
				if ( ! empty( $_GET['onboarding'] ) ) {
4000
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4001
				}
4002
4003
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4004
					$url = add_query_arg( 'auth_approved', 'true', $url );
4005
				}
4006
4007
				wp_redirect( $url );
4008
				exit;
4009
			case 'activate' :
4010
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4011
					$error = 'cheatin';
4012
					break;
4013
				}
4014
4015
				$module = stripslashes( $_GET['module'] );
4016
				check_admin_referer( "jetpack_activate-$module" );
4017
				Jetpack::log( 'activate', $module );
4018
				if ( ! Jetpack::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Jetpack::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...
4019
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4020
				}
4021
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4022
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4023
				exit;
4024
			case 'activate_default_modules' :
4025
				check_admin_referer( 'activate_default_modules' );
4026
				Jetpack::log( 'activate_default_modules' );
4027
				Jetpack::restate();
4028
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4029
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4030
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4031
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4032
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4033
				exit;
4034
			case 'disconnect' :
4035
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4036
					$error = 'cheatin';
4037
					break;
4038
				}
4039
4040
				check_admin_referer( 'jetpack-disconnect' );
4041
				Jetpack::log( 'disconnect' );
4042
				Jetpack::disconnect();
4043
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4044
				exit;
4045
			case 'reconnect' :
4046
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4047
					$error = 'cheatin';
4048
					break;
4049
				}
4050
4051
				check_admin_referer( 'jetpack-reconnect' );
4052
				Jetpack::log( 'reconnect' );
4053
				$this->disconnect();
4054
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4055
				exit;
4056 View Code Duplication
			case 'deactivate' :
4057
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4058
					$error = 'cheatin';
4059
					break;
4060
				}
4061
4062
				$modules = stripslashes( $_GET['module'] );
4063
				check_admin_referer( "jetpack_deactivate-$modules" );
4064
				foreach ( explode( ',', $modules ) as $module ) {
4065
					Jetpack::log( 'deactivate', $module );
4066
					Jetpack::deactivate_module( $module );
4067
					Jetpack::state( 'message', 'module_deactivated' );
4068
				}
4069
				Jetpack::state( 'module', $modules );
4070
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4071
				exit;
4072
			case 'unlink' :
4073
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4074
				check_admin_referer( 'jetpack-unlink' );
4075
				Jetpack::log( 'unlink' );
4076
				$this->unlink_user();
4077
				Jetpack::state( 'message', 'unlinked' );
4078
				if ( 'sub-unlink' == $redirect ) {
4079
					wp_safe_redirect( admin_url() );
4080
				} else {
4081
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4082
				}
4083
				exit;
4084
			case 'onboard' :
4085
				if ( ! current_user_can( 'manage_options' ) ) {
4086
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4087
				} else {
4088
					Jetpack::create_onboarding_token();
4089
					$url = $this->build_connect_url( true );
4090
4091
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4092
						$url = add_query_arg( 'onboarding', $token, $url );
4093
					}
4094
4095
					$calypso_env = $this->get_calypso_env();
4096
					if ( ! empty( $calypso_env ) ) {
4097
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4098
					}
4099
4100
					wp_redirect( $url );
4101
					exit;
4102
				}
4103
				exit;
4104
			default:
4105
				/**
4106
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4107
				 *
4108
				 * @since 2.6.0
4109
				 *
4110
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4111
				 */
4112
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4113
			}
4114
		}
4115
4116
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4117
			self::activate_new_modules( true );
4118
		}
4119
4120
		$message_code = Jetpack::state( 'message' );
4121
		if ( Jetpack::state( 'optin-manage' ) ) {
4122
			$activated_manage = $message_code;
4123
			$message_code = 'jetpack-manage';
4124
		}
4125
4126
		switch ( $message_code ) {
4127
		case 'jetpack-manage':
4128
			$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' ), 'https://wordpress.com/sites' ) . '</strong>';
4129
			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...
4130
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4131
			}
4132
			break;
4133
4134
		}
4135
4136
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4137
4138
		if ( ! empty( $deactivated_plugins ) ) {
4139
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4140
			$deactivated_titles  = array();
4141
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4142
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4143
					continue;
4144
				}
4145
4146
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4147
			}
4148
4149
			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...
4150
				if ( $this->message ) {
4151
					$this->message .= "<br /><br />\n";
4152
				}
4153
4154
				$this->message .= wp_sprintf(
4155
					_n(
4156
						'Jetpack contains the most recent version of the old %l plugin.',
4157
						'Jetpack contains the most recent versions of the old %l plugins.',
4158
						count( $deactivated_titles ),
4159
						'jetpack'
4160
					),
4161
					$deactivated_titles
4162
				);
4163
4164
				$this->message .= "<br />\n";
4165
4166
				$this->message .= _n(
4167
					'The old version has been deactivated and can be removed from your site.',
4168
					'The old versions have been deactivated and can be removed from your site.',
4169
					count( $deactivated_titles ),
4170
					'jetpack'
4171
				);
4172
			}
4173
		}
4174
4175
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4176
4177
		if ( $this->message || $this->error || $this->privacy_checks ) {
4178
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4179
		}
4180
4181
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4182
	}
4183
4184
	function admin_notices() {
4185
4186
		if ( $this->error ) {
4187
?>
4188
<div id="message" class="jetpack-message jetpack-err">
4189
	<div class="squeezer">
4190
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4191
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4192
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4193
<?php	endif; ?>
4194
	</div>
4195
</div>
4196
<?php
4197
		}
4198
4199
		if ( $this->message ) {
4200
?>
4201
<div id="message" class="jetpack-message">
4202
	<div class="squeezer">
4203
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4204
	</div>
4205
</div>
4206
<?php
4207
		}
4208
4209
		if ( $this->privacy_checks ) :
4210
			$module_names = $module_slugs = array();
4211
4212
			$privacy_checks = explode( ',', $this->privacy_checks );
4213
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4214
			foreach ( $privacy_checks as $module_slug ) {
4215
				$module = Jetpack::get_module( $module_slug );
4216
				if ( ! $module ) {
4217
					continue;
4218
				}
4219
4220
				$module_slugs[] = $module_slug;
4221
				$module_names[] = "<strong>{$module['name']}</strong>";
4222
			}
4223
4224
			$module_slugs = join( ',', $module_slugs );
4225
?>
4226
<div id="message" class="jetpack-message jetpack-err">
4227
	<div class="squeezer">
4228
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4229
		<p><?php
4230
			echo wp_kses(
4231
				wptexturize(
4232
					wp_sprintf(
4233
						_nx(
4234
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4235
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4236
							count( $privacy_checks ),
4237
							'%l = list of Jetpack module/feature names',
4238
							'jetpack'
4239
						),
4240
						$module_names
4241
					)
4242
				),
4243
				array( 'strong' => true )
4244
			);
4245
4246
			echo "\n<br />\n";
4247
4248
			echo wp_kses(
4249
				sprintf(
4250
					_nx(
4251
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4252
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4253
						count( $privacy_checks ),
4254
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4255
						'jetpack'
4256
					),
4257
					wp_nonce_url(
4258
						Jetpack::admin_url(
4259
							array(
4260
								'page'   => 'jetpack',
4261
								'action' => 'deactivate',
4262
								'module' => urlencode( $module_slugs ),
4263
							)
4264
						),
4265
						"jetpack_deactivate-$module_slugs"
4266
					),
4267
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4268
				),
4269
				array( 'a' => array( 'href' => true, 'title' => true ) )
4270
			);
4271
		?></p>
4272
	</div>
4273
</div>
4274
<?php endif;
4275
	}
4276
4277
	/**
4278
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4279
	 */
4280
	function stat( $group, $detail ) {
4281
		if ( ! isset( $this->stats[ $group ] ) )
4282
			$this->stats[ $group ] = array();
4283
		$this->stats[ $group ][] = $detail;
4284
	}
4285
4286
	/**
4287
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4288
	 */
4289
	function do_stats( $method = '' ) {
4290
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4291
			foreach ( $this->stats as $group => $stats ) {
4292
				if ( is_array( $stats ) && count( $stats ) ) {
4293
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4294
					if ( 'server_side' === $method ) {
4295
						self::do_server_side_stat( $args );
4296
					} else {
4297
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4298
					}
4299
				}
4300
				unset( $this->stats[ $group ] );
4301
			}
4302
		}
4303
	}
4304
4305
	/**
4306
	 * Runs stats code for a one-off, server-side.
4307
	 *
4308
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4309
	 *
4310
	 * @return bool If it worked.
4311
	 */
4312
	static function do_server_side_stat( $args ) {
4313
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4314
		if ( is_wp_error( $response ) )
4315
			return false;
4316
4317
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4318
			return false;
4319
4320
		return true;
4321
	}
4322
4323
	/**
4324
	 * Builds the stats url.
4325
	 *
4326
	 * @param $args array|string The arguments to append to the URL.
4327
	 *
4328
	 * @return string The URL to be pinged.
4329
	 */
4330
	static function build_stats_url( $args ) {
4331
		$defaults = array(
4332
			'v'    => 'wpcom2',
4333
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4334
		);
4335
		$args     = wp_parse_args( $args, $defaults );
4336
		/**
4337
		 * Filter the URL used as the Stats tracking pixel.
4338
		 *
4339
		 * @since 2.3.2
4340
		 *
4341
		 * @param string $url Base URL used as the Stats tracking pixel.
4342
		 */
4343
		$base_url = apply_filters(
4344
			'jetpack_stats_base_url',
4345
			'https://pixel.wp.com/g.gif'
4346
		);
4347
		$url      = add_query_arg( $args, $base_url );
4348
		return $url;
4349
	}
4350
4351
	/**
4352
	 * Get the role of the current user.
4353
	 *
4354
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4355
	 *
4356
	 * @access public
4357
	 * @static
4358
	 *
4359
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4360
	 */
4361
	public static function translate_current_user_to_role() {
4362
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4363
4364
		$roles = new Roles();
4365
		return $roles->translate_current_user_to_role();
4366
	}
4367
4368
	/**
4369
	 * Get the role of a particular user.
4370
	 *
4371
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4372
	 *
4373
	 * @access public
4374
	 * @static
4375
	 *
4376
	 * @param \WP_User $user User object.
4377
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4378
	 */
4379
	public static function translate_user_to_role( $user ) {
4380
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4381
4382
		$roles = new Roles();
4383
		return $roles->translate_user_to_role( $user );
4384
	}
4385
4386
	/**
4387
	 * Get the minimum capability for a role.
4388
	 *
4389
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4390
	 *
4391
	 * @access public
4392
	 * @static
4393
	 *
4394
	 * @param string $role Role name.
4395
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4396
	 */
4397
	public static function translate_role_to_cap( $role ) {
4398
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4399
4400
		$roles = new Roles();
4401
		return $roles->translate_role_to_cap( $role );
4402
	}
4403
4404
	static function sign_role( $role, $user_id = null ) {
4405
		if ( empty( $user_id ) ) {
4406
			$user_id = (int) get_current_user_id();
4407
		}
4408
4409
		if ( ! $user_id  ) {
4410
			return false;
4411
		}
4412
4413
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4414
		if ( ! $token || is_wp_error( $token ) ) {
4415
			return false;
4416
		}
4417
4418
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4419
	}
4420
4421
4422
	/**
4423
	 * Builds a URL to the Jetpack connection auth page
4424
	 *
4425
	 * @since 3.9.5
4426
	 *
4427
	 * @param bool $raw If true, URL will not be escaped.
4428
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4429
	 *                              If string, will be a custom redirect.
4430
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4431
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4432
	 *
4433
	 * @return string Connect URL
4434
	 */
4435
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4436
		$site_id = Jetpack_Options::get_option( 'id' );
4437
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4438
4439
		if ( $register || ! $blog_token || ! $site_id ) {
4440
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4441
4442
			if ( ! empty( $redirect ) ) {
4443
				$url = add_query_arg(
4444
					'redirect',
4445
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4446
					$url
4447
				);
4448
			}
4449
4450
			if( is_network_admin() ) {
4451
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4452
			}
4453
		} else {
4454
4455
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4456
			// because otherwise this logic can get us in to a loop.
4457
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4458
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4459
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4460
4461
				$response = Client::wpcom_json_api_request_as_blog(
4462
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4463
					'1.1'
4464
				);
4465
4466
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4467
4468
					// Generating a register URL instead to refresh the existing token
4469
					return $this->build_connect_url( $raw, $redirect, $from, true );
4470
				}
4471
			}
4472
4473
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4474
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4475
			}
4476
4477
			$roles       = new Roles();
4478
			$role        = $roles->translate_current_user_to_role();
4479
			$signed_role = self::sign_role( $role );
4480
4481
			$user = wp_get_current_user();
4482
4483
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4484
			$redirect = $redirect
4485
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4486
				: $jetpack_admin_page;
4487
4488
			if( isset( $_REQUEST['is_multisite'] ) ) {
4489
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4490
			}
4491
4492
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4493
4494
			/**
4495
			 * Filter the type of authorization.
4496
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4497
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4498
			 *
4499
			 * @since 4.3.3
4500
			 *
4501
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4502
			 */
4503
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4504
4505
4506
			$tracks = new Tracking();
4507
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4508
4509
			$args = urlencode_deep(
4510
				array(
4511
					'response_type' => 'code',
4512
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4513
					'redirect_uri'  => add_query_arg(
4514
						array(
4515
							'action'   => 'authorize',
4516
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4517
							'redirect' => urlencode( $redirect ),
4518
						),
4519
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4520
					),
4521
					'state'         => $user->ID,
4522
					'scope'         => $signed_role,
4523
					'user_email'    => $user->user_email,
4524
					'user_login'    => $user->user_login,
4525
					'is_active'     => Jetpack::is_active(),
4526
					'jp_version'    => JETPACK__VERSION,
4527
					'auth_type'     => $auth_type,
4528
					'secret'        => $secrets['secret_1'],
4529
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4530
					'blogname'      => get_option( 'blogname' ),
4531
					'site_url'      => site_url(),
4532
					'home_url'      => home_url(),
4533
					'site_icon'     => get_site_icon_url(),
4534
					'site_lang'     => get_locale(),
4535
					'_ui'           => $tracks_identity['_ui'],
4536
					'_ut'           => $tracks_identity['_ut'],
4537
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4538
				)
4539
			);
4540
4541
			self::apply_activation_source_to_args( $args );
4542
4543
			$connection = self::connection();
4544
			$url = add_query_arg( $args, $connection->api_url( 'authorize' ) );
4545
		}
4546
4547
		if ( $from ) {
4548
			$url = add_query_arg( 'from', $from, $url );
4549
		}
4550
4551
		// Ensure that class to get the affiliate code is loaded
4552
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4553
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4554
		}
4555
		// Get affiliate code and add it to the URL
4556
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4557
4558
		$calypso_env = $this->get_calypso_env();
4559
4560
		if ( ! empty( $calypso_env ) ) {
4561
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4562
		}
4563
4564
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4565
	}
4566
4567
	/**
4568
	 * Get our assumed site creation date.
4569
	 * Calculated based on the earlier date of either:
4570
	 * - Earliest admin user registration date.
4571
	 * - Earliest date of post of any post type.
4572
	 *
4573
	 * @since 7.2.0
4574
	 *
4575
	 * @return string Assumed site creation date and time.
4576
	 */
4577 View Code Duplication
	public static function get_assumed_site_creation_date() {
4578
		$earliest_registered_users = get_users( array(
4579
			'role'    => 'administrator',
4580
			'orderby' => 'user_registered',
4581
			'order'   => 'ASC',
4582
			'fields'  => array( 'user_registered' ),
4583
			'number'  => 1,
4584
		) );
4585
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4586
4587
		$earliest_posts = get_posts( array(
4588
			'posts_per_page' => 1,
4589
			'post_type'      => 'any',
4590
			'post_status'    => 'any',
4591
			'orderby'        => 'date',
4592
			'order'          => 'ASC',
4593
		) );
4594
4595
		// If there are no posts at all, we'll count only on user registration date.
4596
		if ( $earliest_posts ) {
4597
			$earliest_post_date = $earliest_posts[0]->post_date;
4598
		} else {
4599
			$earliest_post_date = PHP_INT_MAX;
4600
		}
4601
4602
		return min( $earliest_registration_date, $earliest_post_date );
4603
	}
4604
4605 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4606
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4607
4608
		if ( $activation_source_name ) {
4609
			$args['_as'] = urlencode( $activation_source_name );
4610
		}
4611
4612
		if ( $activation_source_keyword ) {
4613
			$args['_ak'] = urlencode( $activation_source_keyword );
4614
		}
4615
	}
4616
4617
	function build_reconnect_url( $raw = false ) {
4618
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4619
		return $raw ? $url : esc_url( $url );
4620
	}
4621
4622
	public static function admin_url( $args = null ) {
4623
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4624
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4625
		return $url;
4626
	}
4627
4628
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4629
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4630
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4631
	}
4632
4633
	function dismiss_jetpack_notice() {
4634
4635
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4636
			return;
4637
		}
4638
4639
		switch( $_GET['jetpack-notice'] ) {
4640
			case 'dismiss':
4641
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4642
4643
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4644
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4645
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4646
				}
4647
				break;
4648
			case 'jetpack-protect-multisite-opt-out':
4649
4650
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4651
					// Don't show the banner again
4652
4653
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4654
					// redirect back to the page that had the notice
4655
					if ( wp_get_referer() ) {
4656
						wp_safe_redirect( wp_get_referer() );
4657
					} else {
4658
						// Take me to Jetpack
4659
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4660
					}
4661
				}
4662
				break;
4663
		}
4664
	}
4665
4666
	public static function sort_modules( $a, $b ) {
4667
		if ( $a['sort'] == $b['sort'] )
4668
			return 0;
4669
4670
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4671
	}
4672
4673
	function ajax_recheck_ssl() {
4674
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4675
		$result = Jetpack::permit_ssl( true );
4676
		wp_send_json( array(
4677
			'enabled' => $result,
4678
			'message' => get_transient( 'jetpack_https_test_message' )
4679
		) );
4680
	}
4681
4682
/* Client API */
4683
4684
	/**
4685
	 * Returns the requested Jetpack API URL
4686
	 *
4687
	 * @deprecated since 7.7
4688
	 * @return string
4689
	 */
4690
	public static function api_url( $relative_url ) {
4691
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4692
		$connection = self::connection();
4693
		return $connection->api_url( $relative_url );
4694
	}
4695
4696
	/**
4697
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4698
	 */
4699
	public static function fix_url_for_bad_hosts( $url ) {
4700
		if ( 0 !== strpos( $url, 'https://' ) ) {
4701
			return $url;
4702
		}
4703
4704
		switch ( JETPACK_CLIENT__HTTPS ) {
4705
			case 'ALWAYS' :
4706
				return $url;
4707
			case 'NEVER' :
4708
				return set_url_scheme( $url, 'http' );
4709
			// default : case 'AUTO' :
4710
		}
4711
4712
		// we now return the unmodified SSL URL by default, as a security precaution
4713
		return $url;
4714
	}
4715
4716
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4717
		// Default to a blog token.
4718
		$token_type = 'blog';
4719
4720
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4721
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4722
			if ( ! empty( $_GET['onboarding'] ) ) {
4723
				$jpo = $_GET;
4724
			} else {
4725
				$jpo = json_decode( $request_data, true );
4726
			}
4727
4728
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4729
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4730
4731
			if (
4732
				isset( $jpo_user )
4733
				&& isset( $jpo_token )
4734
				&& is_email( $jpo_user )
4735
				&& ctype_alnum( $jpo_token )
4736
				&& isset( $_GET['rest_route'] )
4737
				&& self::validate_onboarding_token_action(
4738
					$jpo_token,
4739
					$_GET['rest_route']
4740
				)
4741
			) {
4742
				$jp_user = get_user_by( 'email', $jpo_user );
4743
				if ( is_a( $jp_user, 'WP_User' ) ) {
4744
					wp_set_current_user( $jp_user->ID );
4745
					$user_can = is_multisite()
4746
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4747
						: current_user_can( 'manage_options' );
4748
					if ( $user_can ) {
4749
						$token_type = 'user';
4750
						$token->external_user_id = $jp_user->ID;
4751
					}
4752
				}
4753
			}
4754
4755
			$token_data['type']    = $token_type;
4756
			$token_data['user_id'] = $token->external_user_id;
4757
		}
4758
4759
		return $token_data;
4760
	}
4761
4762
	/**
4763
	 * Create a random secret for validating onboarding payload
4764
	 *
4765
	 * @return string Secret token
4766
	 */
4767
	public static function create_onboarding_token() {
4768
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4769
			$token = wp_generate_password( 32, false );
4770
			Jetpack_Options::update_option( 'onboarding', $token );
4771
		}
4772
4773
		return $token;
4774
	}
4775
4776
	/**
4777
	 * Remove the onboarding token
4778
	 *
4779
	 * @return bool True on success, false on failure
4780
	 */
4781
	public static function invalidate_onboarding_token() {
4782
		return Jetpack_Options::delete_option( 'onboarding' );
4783
	}
4784
4785
	/**
4786
	 * Validate an onboarding token for a specific action
4787
	 *
4788
	 * @return boolean True if token/action pair is accepted, false if not
4789
	 */
4790
	public static function validate_onboarding_token_action( $token, $action ) {
4791
		// Compare tokens, bail if tokens do not match
4792
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4793
			return false;
4794
		}
4795
4796
		// List of valid actions we can take
4797
		$valid_actions = array(
4798
			'/jetpack/v4/settings',
4799
		);
4800
4801
		// Whitelist the action
4802
		if ( ! in_array( $action, $valid_actions ) ) {
4803
			return false;
4804
		}
4805
4806
		return true;
4807
	}
4808
4809
	/**
4810
	 * Checks to see if the URL is using SSL to connect with Jetpack
4811
	 *
4812
	 * @since 2.3.3
4813
	 * @return boolean
4814
	 */
4815
	public static function permit_ssl( $force_recheck = false ) {
4816
		// Do some fancy tests to see if ssl is being supported
4817
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4818
			$message = '';
4819
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4820
				$ssl = 0;
4821
			} else {
4822
				switch ( JETPACK_CLIENT__HTTPS ) {
4823
					case 'NEVER':
4824
						$ssl = 0;
4825
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4826
						break;
4827
					case 'ALWAYS':
4828
					case 'AUTO':
4829
					default:
4830
						$ssl = 1;
4831
						break;
4832
				}
4833
4834
				// If it's not 'NEVER', test to see
4835
				if ( $ssl ) {
4836
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4837
						$ssl = 0;
4838
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4839
					} else {
4840
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4841
						if ( is_wp_error( $response ) ) {
4842
							$ssl = 0;
4843
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4844
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4845
							$ssl = 0;
4846
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4847
						}
4848
					}
4849
				}
4850
			}
4851
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4852
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4853
		}
4854
4855
		return (bool) $ssl;
4856
	}
4857
4858
	/*
4859
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4860
	 */
4861
	public function alert_auto_ssl_fail() {
4862
		if ( ! current_user_can( 'manage_options' ) )
4863
			return;
4864
4865
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4866
		?>
4867
4868
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4869
			<div class="jp-banner__content">
4870
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4871
				<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>
4872
				<p>
4873
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4874
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4875
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4876
				</p>
4877
				<p>
4878
					<?php printf( __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
4879
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4880
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4881
				</p>
4882
			</div>
4883
		</div>
4884
		<style>
4885
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4886
		</style>
4887
		<script type="text/javascript">
4888
			jQuery( document ).ready( function( $ ) {
4889
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4890
					var $this = $( this );
4891
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4892
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4893
					e.preventDefault();
4894
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4895
					$.post( ajaxurl, data )
4896
					  .done( function( response ) {
4897
					  	if ( response.enabled ) {
4898
					  		$( '#jetpack-ssl-warning' ).hide();
4899
					  	} else {
4900
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4901
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4902
					  	}
4903
					  }.bind( $this ) );
4904
				} );
4905
			} );
4906
		</script>
4907
4908
		<?php
4909
	}
4910
4911
	/**
4912
	 * Returns the Jetpack XML-RPC API
4913
	 *
4914
	 * @return string
4915
	 */
4916
	public static function xmlrpc_api_url() {
4917
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4918
		return untrailingslashit( $base ) . '/xmlrpc.php';
4919
	}
4920
4921
	public static function connection() {
4922
		return self::init()->connection_manager;
4923
	}
4924
4925
	/**
4926
	 * Creates two secret tokens and the end of life timestamp for them.
4927
	 *
4928
	 * Note these tokens are unique per call, NOT static per site for connecting.
4929
	 *
4930
	 * @since 2.6
4931
	 * @return array
4932
	 */
4933
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4934
		if ( false === $user_id ) {
4935
			$user_id = get_current_user_id();
4936
		}
4937
4938
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4939
	}
4940
4941
	public static function get_secrets( $action, $user_id ) {
4942
		$secrets = self::connection()->get_secrets( $action, $user_id );
4943
4944
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4945
			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...
4946
		}
4947
4948
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4949
			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...
4950
		}
4951
4952
		return $secrets;
4953
	}
4954
4955
	/**
4956
	 * @deprecated 7.5 Use Connection_Manager instead.
4957
	 *
4958
	 * @param $action
4959
	 * @param $user_id
4960
	 */
4961
	public static function delete_secrets( $action, $user_id ) {
4962
		return self::connection()->delete_secrets( $action, $user_id );
4963
	}
4964
4965
	/**
4966
	 * Builds the timeout limit for queries talking with the wpcom servers.
4967
	 *
4968
	 * Based on local php max_execution_time in php.ini
4969
	 *
4970
	 * @since 2.6
4971
	 * @return int
4972
	 * @deprecated
4973
	 **/
4974
	public function get_remote_query_timeout_limit() {
4975
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4976
		return Jetpack::get_max_execution_time();
4977
	}
4978
4979
	/**
4980
	 * Builds the timeout limit for queries talking with the wpcom servers.
4981
	 *
4982
	 * Based on local php max_execution_time in php.ini
4983
	 *
4984
	 * @since 5.4
4985
	 * @return int
4986
	 **/
4987
	public static function get_max_execution_time() {
4988
		$timeout = (int) ini_get( 'max_execution_time' );
4989
4990
		// Ensure exec time set in php.ini
4991
		if ( ! $timeout ) {
4992
			$timeout = 30;
4993
		}
4994
		return $timeout;
4995
	}
4996
4997
	/**
4998
	 * Sets a minimum request timeout, and returns the current timeout
4999
	 *
5000
	 * @since 5.4
5001
	 **/
5002 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5003
		$timeout = self::get_max_execution_time();
5004
		if ( $timeout < $min_timeout ) {
5005
			$timeout = $min_timeout;
5006
			set_time_limit( $timeout );
5007
		}
5008
		return $timeout;
5009
	}
5010
5011
	/**
5012
	 * Takes the response from the Jetpack register new site endpoint and
5013
	 * verifies it worked properly.
5014
	 *
5015
	 * @since 2.6
5016
	 * @deprecated since 7.7.0
5017
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5018
	 **/
5019
	public function validate_remote_register_response() {
5020
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5021
	}
5022
5023
	/**
5024
	 * @return bool|WP_Error
5025
	 */
5026
	public static function register() {
5027
		$tracking = new Tracking();
5028
		$tracking->record_user_event( 'jpc_register_begin' );
5029
5030
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5031
5032
		$connection = self::connection();
5033
		$registration = $connection->register();
5034
5035
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5036
5037
		if ( ! $registration || is_wp_error( $registration ) ) {
5038
			return $registration;
5039
		}
5040
5041
		return true;
5042
	}
5043
5044
	/**
5045
	 * Filters the registration request body to include tracking properties.
5046
	 *
5047
	 * @param Array $properties
5048
	 * @return Array amended properties.
5049
	 */
5050
	public static function filter_register_request_body( $properties ) {
5051
		$tracking = new Tracking();
5052
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5053
5054
		return array_merge(
5055
			$properties,
5056
			array(
5057
				'_ui' => $tracks_identity['_ui'],
5058
				'_ut' => $tracks_identity['_ut'],
5059
			)
5060
		);
5061
	}
5062
5063
	/**
5064
	 * If the db version is showing something other that what we've got now, bump it to current.
5065
	 *
5066
	 * @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...
5067
	 */
5068
	public static function maybe_set_version_option() {
5069
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5070
		if ( JETPACK__VERSION != $version ) {
5071
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5072
5073
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5074
				/** This action is documented in class.jetpack.php */
5075
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5076
			}
5077
5078
			return true;
5079
		}
5080
		return false;
5081
	}
5082
5083
/* Client Server API */
5084
5085
	/**
5086
	 * Loads the Jetpack XML-RPC client
5087
	 */
5088
	public static function load_xml_rpc_client() {
5089
		require_once ABSPATH . WPINC . '/class-IXR.php';
5090
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5091
	}
5092
5093
	/**
5094
	 * Resets the saved authentication state in between testing requests.
5095
	 */
5096
	public function reset_saved_auth_state() {
5097
		$this->rest_authentication_status = null;
5098
		$this->connection_manager->reset_saved_auth_state();
5099
	}
5100
5101
	/**
5102
	 * Verifies the signature of the current request.
5103
	 *
5104
	 * @deprecated since 7.7.0
5105
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5106
	 *
5107
	 * @return false|array
5108
	 */
5109
	public function verify_xml_rpc_signature() {
5110
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5111
		return self::connection()->verify_xml_rpc_signature();
5112
	}
5113
5114
	/**
5115
	 * Verifies the signature of the current request.
5116
	 *
5117
	 * This function has side effects and should not be used. Instead,
5118
	 * use the memoized version `->verify_xml_rpc_signature()`.
5119
	 *
5120
	 * @deprecated since 7.7.0
5121
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5122
	 * @internal
5123
	 */
5124
	private function internal_verify_xml_rpc_signature() {
5125
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5126
	}
5127
5128
	/**
5129
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5130
	 *
5131
	 * @deprecated since 7.7.0
5132
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5133
	 *
5134
	 * @param \WP_User|mixed $user     User object if authenticated.
5135
	 * @param string         $username Username.
5136
	 * @param string         $password Password string.
5137
	 * @return \WP_User|mixed Authenticated user or error.
5138
	 */
5139
	public function authenticate_jetpack( $user, $username, $password ) {
5140
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5141
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5142
	}
5143
5144
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5145
	// Uses the existing XMLRPC request signing implementation.
5146
	function wp_rest_authenticate( $user ) {
5147
		if ( ! empty( $user ) ) {
5148
			// Another authentication method is in effect.
5149
			return $user;
5150
		}
5151
5152
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5153
			// Nothing to do for this authentication method.
5154
			return null;
5155
		}
5156
5157
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5158
			// Nothing to do for this authentication method.
5159
			return null;
5160
		}
5161
5162
		// Ensure that we always have the request body available.  At this
5163
		// point, the WP REST API code to determine the request body has not
5164
		// run yet.  That code may try to read from 'php://input' later, but
5165
		// this can only be done once per request in PHP versions prior to 5.6.
5166
		// So we will go ahead and perform this read now if needed, and save
5167
		// the request body where both the Jetpack signature verification code
5168
		// and the WP REST API code can see it.
5169
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5170
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5171
		}
5172
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5173
5174
		// Only support specific request parameters that have been tested and
5175
		// are known to work with signature verification.  A different method
5176
		// can be passed to the WP REST API via the '?_method=' parameter if
5177
		// needed.
5178
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5179
			$this->rest_authentication_status = new WP_Error(
5180
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5181
				__( 'This request method is not supported.', 'jetpack' ),
5182
				array( 'status' => 400 )
5183
			);
5184
			return null;
5185
		}
5186
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5187
			$this->rest_authentication_status = new WP_Error(
5188
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5189
				__( 'This request method does not support body parameters.', 'jetpack' ),
5190
				array( 'status' => 400 )
5191
			);
5192
			return null;
5193
		}
5194
5195
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5196
5197
		if (
5198
			$verified &&
5199
			isset( $verified['type'] ) &&
5200
			'user' === $verified['type'] &&
5201
			! empty( $verified['user_id'] )
5202
		) {
5203
			// Authentication successful.
5204
			$this->rest_authentication_status = true;
5205
			return $verified['user_id'];
5206
		}
5207
5208
		// Something else went wrong.  Probably a signature error.
5209
		$this->rest_authentication_status = new WP_Error(
5210
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5211
			__( 'The request is not signed correctly.', 'jetpack' ),
5212
			array( 'status' => 400 )
5213
		);
5214
		return null;
5215
	}
5216
5217
	/**
5218
	 * Report authentication status to the WP REST API.
5219
	 *
5220
	 * @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...
5221
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5222
	 */
5223
	public function wp_rest_authentication_errors( $value ) {
5224
		if ( $value !== null ) {
5225
			return $value;
5226
		}
5227
		return $this->rest_authentication_status;
5228
	}
5229
5230
	/**
5231
	 * Add our nonce to this request.
5232
	 *
5233
	 * @deprecated since 7.7.0
5234
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5235
	 *
5236
	 * @param int    $timestamp Timestamp of the request.
5237
	 * @param string $nonce     Nonce string.
5238
	 */
5239
	public function add_nonce( $timestamp, $nonce ) {
5240
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5241
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5242
	}
5243
5244
	/**
5245
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5246
	 * Capture it here so we can verify the signature later.
5247
	 *
5248
	 * @deprecated since 7.7.0
5249
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5250
	 *
5251
	 * @param array $methods XMLRPC methods.
5252
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5253
	 */
5254
	public function xmlrpc_methods( $methods ) {
5255
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5256
		return $this->connection_manager->xmlrpc_methods( $methods );
5257
	}
5258
5259
	/**
5260
	 * Register additional public XMLRPC methods.
5261
	 *
5262
	 * @deprecated since 7.7.0
5263
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5264
	 *
5265
	 * @param array $methods Public XMLRPC methods.
5266
	 * @return array Public XMLRPC methods, with the getOptions one.
5267
	 */
5268
	public function public_xmlrpc_methods( $methods ) {
5269
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5270
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5271
	}
5272
5273
	/**
5274
	 * Handles a getOptions XMLRPC method call.
5275
	 *
5276
	 * @deprecated since 7.7.0
5277
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5278
	 *
5279
	 * @param array $args method call arguments.
5280
	 * @return array an amended XMLRPC server options array.
5281
	 */
5282
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5283
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5284
		return $this->connection_manager->jetpack_getOptions( $args );
5285
	}
5286
5287
	/**
5288
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5289
	 *
5290
	 * @deprecated since 7.7.0
5291
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5292
	 *
5293
	 * @param array $options Standard Core options.
5294
	 * @return array Amended options.
5295
	 */
5296
	public function xmlrpc_options( $options ) {
5297
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5298
		return $this->connection_manager->xmlrpc_options( $options );
5299
	}
5300
5301
	/**
5302
	 * Cleans nonces that were saved when calling ::add_nonce.
5303
	 *
5304
	 * @deprecated since 7.7.0
5305
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5306
	 *
5307
	 * @param bool $all whether to clean even non-expired nonces.
5308
	 */
5309
	public static function clean_nonces( $all = false ) {
5310
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5311
		return self::connection()->clean_nonces( $all );
5312
	}
5313
5314
	/**
5315
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5316
	 * SET: state( $key, $value );
5317
	 * GET: $value = state( $key );
5318
	 *
5319
	 * @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...
5320
	 * @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...
5321
	 * @param bool $restate private
5322
	 */
5323
	public static function state( $key = null, $value = null, $restate = false ) {
5324
		static $state = array();
5325
		static $path, $domain;
5326
		if ( ! isset( $path ) ) {
5327
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5328
			$admin_url = Jetpack::admin_url();
5329
			$bits      = wp_parse_url( $admin_url );
5330
5331
			if ( is_array( $bits ) ) {
5332
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5333
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5334
			} else {
5335
				$path = $domain = null;
5336
			}
5337
		}
5338
5339
		// Extract state from cookies and delete cookies
5340
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5341
			$yum = $_COOKIE[ 'jetpackState' ];
5342
			unset( $_COOKIE[ 'jetpackState' ] );
5343
			foreach ( $yum as $k => $v ) {
5344
				if ( strlen( $v ) )
5345
					$state[ $k ] = $v;
5346
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5347
			}
5348
		}
5349
5350
		if ( $restate ) {
5351
			foreach ( $state as $k => $v ) {
5352
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5353
			}
5354
			return;
5355
		}
5356
5357
		// Get a state variable
5358
		if ( isset( $key ) && ! isset( $value ) ) {
5359
			if ( array_key_exists( $key, $state ) )
5360
				return $state[ $key ];
5361
			return null;
5362
		}
5363
5364
		// Set a state variable
5365
		if ( isset ( $key ) && isset( $value ) ) {
5366
			if( is_array( $value ) && isset( $value[0] ) ) {
5367
				$value = $value[0];
5368
			}
5369
			$state[ $key ] = $value;
5370
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5371
		}
5372
	}
5373
5374
	public static function restate() {
5375
		Jetpack::state( null, null, true );
5376
	}
5377
5378
	public static function check_privacy( $file ) {
5379
		static $is_site_publicly_accessible = null;
5380
5381
		if ( is_null( $is_site_publicly_accessible ) ) {
5382
			$is_site_publicly_accessible = false;
5383
5384
			Jetpack::load_xml_rpc_client();
5385
			$rpc = new Jetpack_IXR_Client();
5386
5387
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5388
			if ( $success ) {
5389
				$response = $rpc->getResponse();
5390
				if ( $response ) {
5391
					$is_site_publicly_accessible = true;
5392
				}
5393
			}
5394
5395
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5396
		}
5397
5398
		if ( $is_site_publicly_accessible ) {
5399
			return;
5400
		}
5401
5402
		$module_slug = self::get_module_slug( $file );
5403
5404
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5405
		if ( ! $privacy_checks ) {
5406
			$privacy_checks = $module_slug;
5407
		} else {
5408
			$privacy_checks .= ",$module_slug";
5409
		}
5410
5411
		Jetpack::state( 'privacy_checks', $privacy_checks );
5412
	}
5413
5414
	/**
5415
	 * Helper method for multicall XMLRPC.
5416
	 */
5417
	public static function xmlrpc_async_call() {
5418
		global $blog_id;
5419
		static $clients = array();
5420
5421
		$client_blog_id = is_multisite() ? $blog_id : 0;
5422
5423
		if ( ! isset( $clients[$client_blog_id] ) ) {
5424
			Jetpack::load_xml_rpc_client();
5425
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5426
			if ( function_exists( 'ignore_user_abort' ) ) {
5427
				ignore_user_abort( true );
5428
			}
5429
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5430
		}
5431
5432
		$args = func_get_args();
5433
5434
		if ( ! empty( $args[0] ) ) {
5435
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5436
		} elseif ( is_multisite() ) {
5437
			foreach ( $clients as $client_blog_id => $client ) {
5438
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5439
					continue;
5440
				}
5441
5442
				$switch_success = switch_to_blog( $client_blog_id, true );
5443
				if ( ! $switch_success ) {
5444
					continue;
5445
				}
5446
5447
				flush();
5448
				$client->query();
5449
5450
				restore_current_blog();
5451
			}
5452
		} else {
5453
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5454
				flush();
5455
				$clients[0]->query();
5456
			}
5457
		}
5458
	}
5459
5460
	public static function staticize_subdomain( $url ) {
5461
5462
		// Extract hostname from URL
5463
		$host = parse_url( $url, PHP_URL_HOST );
5464
5465
		// Explode hostname on '.'
5466
		$exploded_host = explode( '.', $host );
5467
5468
		// Retrieve the name and TLD
5469
		if ( count( $exploded_host ) > 1 ) {
5470
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5471
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5472
			// Rebuild domain excluding subdomains
5473
			$domain = $name . '.' . $tld;
5474
		} else {
5475
			$domain = $host;
5476
		}
5477
		// Array of Automattic domains
5478
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5479
5480
		// Return $url if not an Automattic domain
5481
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5482
			return $url;
5483
		}
5484
5485
		if ( is_ssl() ) {
5486
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5487
		}
5488
5489
		srand( crc32( basename( $url ) ) );
5490
		$static_counter = rand( 0, 2 );
5491
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5492
5493
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5494
	}
5495
5496
/* JSON API Authorization */
5497
5498
	/**
5499
	 * Handles the login action for Authorizing the JSON API.
5500
	 *
5501
	 * @deprecated since 7.7.0
5502
	 * @see Automattic\Jetpack\Connection\Manager::login_form_json_api_authorization()
5503
	 */
5504
	public function login_form_json_api_authorization() {
5505
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::login_form_json_api_authorization' );
5506
		self::connection()->login_form_json_api_authorization();
5507
	}
5508
5509
	/**
5510
	 * Make sure the login form is POSTed to the signed URL so we can reverify the request.
5511
	 *
5512
	 * @deprecated since 7.7.0
5513
	 * @see Automattic\Jetpack\Connection\Manager::post_login_form_to_signed_url()
5514
	 *
5515
	 * @param string      $url     The complete site URL including scheme and path.
5516
	 * @param string      $path    Path relative to the site URL. Blank string if no path is specified.
5517
	 * @param string|null $scheme  Scheme to give the site URL context. Accepts 'http', 'https', 'login'.
5518
	 * @return string Signed login form action URL.
5519
	 */
5520
	public function post_login_form_to_signed_url( $url, $path, $scheme ) {
5521
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::post_login_form_to_signed_url' );
5522
		return self::connection()->post_login_form_to_signed_url( $url, $path, $scheme );
5523
	}
5524
5525
	/**
5526
	 * Make sure the POSTed request is handled by the same action.
5527
	 *
5528
	 * @deprecated since 7.7.0
5529
	 * @see Automattic\Jetpack\Connection\Manager::preserve_action_in_login_form_for_json_api_authorization()
5530
	 */
5531
	public function preserve_action_in_login_form_for_json_api_authorization() {
5532
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::preserve_action_in_login_form_for_json_api_authorization' );
5533
		self::connection()->preserve_action_in_login_form_for_json_api_authorization();
5534
	}
5535
5536
	/**
5537
	 * If someone logs in to approve API access, store the Access Code in usermeta.
5538
	 *
5539
	 * @deprecated since 7.7.0
5540
	 * @see Automattic\Jetpack\Connection\Manager::store_json_api_authorization_token()
5541
	 *
5542
	 * @param string   $user_login Username.
5543
	 * @param \WP_User $user       \WP_User object of the logged-in user.
5544
	 */
5545
	public function store_json_api_authorization_token( $user_login, $user ) {
5546
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::store_json_api_authorization_token' );
5547
		self::connection()->store_json_api_authorization_token( $user_login, $user );
5548
	}
5549
5550
	/**
5551
	 * Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access.
5552
	 *
5553
	 * @deprecated since 7.7.0
5554
	 * @see Automattic\Jetpack\Connection\Manager::allow_wpcom_public_api_domain()
5555
	 *
5556
	 * @param array $domains An array of allowed hosts.
5557
	 * @return array Array of allowed hosts, with the WP.com API domain included.
5558
	 */
5559
	public function allow_wpcom_public_api_domain( $domains ) {
5560
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::allow_wpcom_public_api_domain' );
5561
		return self::connection()->allow_wpcom_public_api_domain( $domains );
5562
	}
5563
5564
	/**
5565
	 * Whether the redirect URL is encoded.
5566
	 *
5567
	 * @deprecated since 7.7.0
5568
	 * @see Automattic\Jetpack\Connection\Manager::is_redirect_encoded()
5569
	 *
5570
	 * @static
5571
	 *
5572
	 * @param string $redirect_url Redirect URL.
5573
	 * @return bool True if the URL is encoded, false otherwise.
5574
	 */
5575
	public static function is_redirect_encoded( $redirect_url ) {
5576
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_redirect_encoded' );
5577
		return self::connection()->is_redirect_encoded( $redirect_url );
5578
	}
5579
5580
	/**
5581
	 * Add all wordpress.com environments to the safe redirect whitelist.
5582
	 *
5583
	 * @deprecated since 7.7.0
5584
	 * @see Automattic\Jetpack\Connection\Manager::allow_wpcom_environments()
5585
	 *
5586
	 * @param array $domains An array of allowed hosts.
5587
	 * @return array Array of allowed hosts, with the WP.com API domain included.
5588
	 */
5589
	public function allow_wpcom_environments( $domains ) {
5590
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::allow_wpcom_environments' );
5591
		return self::connection()->allow_wpcom_environments( $domains );
5592
	}
5593
5594
	/**
5595
	 * Add the Access Code details to the public-api.wordpress.com redirect.
5596
	 *
5597
	 * @deprecated since 7.7.0
5598
	 * @see Automattic\Jetpack\Connection\Manager::add_token_to_login_redirect_json_api_authorization()
5599
	 *
5600
	 * @param string             $redirect_to          The redirect destination URL.
5601
	 * @param string             $original_redirect_to The requested redirect destination URL passed as a parameter.
5602
	 * @param \WP_User|\WP_Error $user                 \WP_User object if login was successful, \WP_Error object otherwise.
5603
	 * @return string Login redirect URL, with token parameters added to it.
5604
	 */
5605
	public function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5606
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_token_to_login_redirect_json_api_authorization' );
5607
		return self::connection()->add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user );
5608
	}
5609
5610
	/**
5611
	 * Verifies the request by checking the signature.
5612
	 *
5613
	 * @deprecated since 7.7.0
5614
	 * @see Automattic\Jetpack\Connection\Manager::verify_json_api_authorization_request()
5615
	 *
5616
	 * @param null|array $environment Authorization data.
5617
	 */
5618
	public function verify_json_api_authorization_request( $environment = null ) {
5619
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_json_api_authorization_request' );
5620
		self::connection()->verify_json_api_authorization_request( $environment );
5621
	}
5622
5623
	/**
5624
	 * Retrieve an updated login message for JSON API authorization.
5625
	 *
5626
	 * @deprecated since 7.7.0
5627
	 * @see Automattic\Jetpack\Connection\Manager::login_message_json_api_authorization()
5628
	 *
5629
	 * @param string $message Original message displayed to user at login.
5630
	 * @return string Updated Login message.
5631
	 */
5632
	public function login_message_json_api_authorization( $message ) {
5633
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::login_message_json_api_authorization' );
5634
		return self::connection()->login_message_json_api_authorization( $message );
0 ignored issues
show
Unused Code introduced by
The call to Manager::login_message_json_api_authorization() has too many arguments starting with $message.

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...
5635
	}
5636
5637
	/**
5638
	 * Get $content_width, but with a <s>twist</s> filter.
5639
	 */
5640
	public static function get_content_width() {
5641
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5642
			? $GLOBALS['content_width']
5643
			: false;
5644
		/**
5645
		 * Filter the Content Width value.
5646
		 *
5647
		 * @since 2.2.3
5648
		 *
5649
		 * @param string $content_width Content Width value.
5650
		 */
5651
		return apply_filters( 'jetpack_content_width', $content_width );
5652
	}
5653
5654
	/**
5655
	 * Pings the WordPress.com Mirror Site for the specified options.
5656
	 *
5657
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5658
	 *
5659
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5660
	 */
5661
	public function get_cloud_site_options( $option_names ) {
5662
		$option_names = array_filter( (array) $option_names, 'is_string' );
5663
5664
		Jetpack::load_xml_rpc_client();
5665
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5666
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5667
		if ( $xml->isError() ) {
5668
			return array(
5669
				'error_code' => $xml->getErrorCode(),
5670
				'error_msg'  => $xml->getErrorMessage(),
5671
			);
5672
		}
5673
		$cloud_site_options = $xml->getResponse();
5674
5675
		return $cloud_site_options;
5676
	}
5677
5678
	/**
5679
	 * Checks if the site is currently in an identity crisis.
5680
	 *
5681
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5682
	 */
5683
	public static function check_identity_crisis() {
5684
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5685
			return false;
5686
		}
5687
5688
		return Jetpack_Options::get_option( 'sync_error_idc' );
5689
	}
5690
5691
	/**
5692
	 * Checks whether the home and siteurl specifically are whitelisted
5693
	 * Written so that we don't have re-check $key and $value params every time
5694
	 * we want to check if this site is whitelisted, for example in footer.php
5695
	 *
5696
	 * @since  3.8.0
5697
	 * @return bool True = already whitelisted False = not whitelisted
5698
	 */
5699
	public static function is_staging_site() {
5700
		$is_staging = false;
5701
5702
		$known_staging = array(
5703
			'urls' => array(
5704
				'#\.staging\.wpengine\.com$#i', // WP Engine
5705
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5706
				'#\.stage\.site$#i'             // DreamPress
5707
			),
5708
			'constants' => array(
5709
				'IS_WPE_SNAPSHOT',      // WP Engine
5710
				'KINSTA_DEV_ENV',       // Kinsta.com
5711
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5712
				'JETPACK_STAGING_MODE', // Generic
5713
			)
5714
		);
5715
		/**
5716
		 * Filters the flags of known staging sites.
5717
		 *
5718
		 * @since 3.9.0
5719
		 *
5720
		 * @param array $known_staging {
5721
		 *     An array of arrays that each are used to check if the current site is staging.
5722
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5723
		 *     @type array $constants PHP constants of known staging/developement environments.
5724
		 *  }
5725
		 */
5726
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5727
5728
		if ( isset( $known_staging['urls'] ) ) {
5729
			foreach ( $known_staging['urls'] as $url ){
5730
				if ( preg_match( $url, site_url() ) ) {
5731
					$is_staging = true;
5732
					break;
5733
				}
5734
			}
5735
		}
5736
5737
		if ( isset( $known_staging['constants'] ) ) {
5738
			foreach ( $known_staging['constants'] as $constant ) {
5739
				if ( defined( $constant ) && constant( $constant ) ) {
5740
					$is_staging = true;
5741
				}
5742
			}
5743
		}
5744
5745
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5746
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5747
			$is_staging = true;
5748
		}
5749
5750
		/**
5751
		 * Filters is_staging_site check.
5752
		 *
5753
		 * @since 3.9.0
5754
		 *
5755
		 * @param bool $is_staging If the current site is a staging site.
5756
		 */
5757
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5758
	}
5759
5760
	/**
5761
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5762
	 *
5763
	 * @since 4.4.0
5764
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5765
	 *
5766
	 * @return bool
5767
	 */
5768
	public static function validate_sync_error_idc_option() {
5769
		$is_valid = false;
5770
5771
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5772
		if ( false === $idc_allowed ) {
5773
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5774
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5775
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5776
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5777
				$transient_duration = HOUR_IN_SECONDS;
5778
			} else {
5779
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5780
				$idc_allowed = '1';
5781
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5782
			}
5783
5784
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5785
		}
5786
5787
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5788
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5789
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5790
			$local_options = self::get_sync_error_idc_option();
5791
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5792
				$is_valid = true;
5793
			}
5794
		}
5795
5796
		/**
5797
		 * Filters whether the sync_error_idc option is valid.
5798
		 *
5799
		 * @since 4.4.0
5800
		 *
5801
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5802
		 */
5803
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5804
5805
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5806
			// Since the option exists, and did not validate, delete it
5807
			Jetpack_Options::delete_option( 'sync_error_idc' );
5808
		}
5809
5810
		return $is_valid;
5811
	}
5812
5813
	/**
5814
	 * Normalizes a url by doing three things:
5815
	 *  - Strips protocol
5816
	 *  - Strips www
5817
	 *  - Adds a trailing slash
5818
	 *
5819
	 * @since 4.4.0
5820
	 * @param string $url
5821
	 * @return WP_Error|string
5822
	 */
5823
	public static function normalize_url_protocol_agnostic( $url ) {
5824
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5825
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5826
			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...
5827
		}
5828
5829
		// Strip www and protocols
5830
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5831
		return $url;
5832
	}
5833
5834
	/**
5835
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5836
	 *
5837
	 * @since 4.4.0
5838
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5839
	 *
5840
	 * @param array $response
5841
	 * @return array Array of the local urls, wpcom urls, and error code
5842
	 */
5843
	public static function get_sync_error_idc_option( $response = array() ) {
5844
		// Since the local options will hit the database directly, store the values
5845
		// in a transient to allow for autoloading and caching on subsequent views.
5846
		$local_options = get_transient( 'jetpack_idc_local' );
5847
		if ( false === $local_options ) {
5848
			$local_options = array(
5849
				'home'    => Functions::home_url(),
5850
				'siteurl' => Functions::site_url(),
5851
			);
5852
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5853
		}
5854
5855
		$options = array_merge( $local_options, $response );
5856
5857
		$returned_values = array();
5858
		foreach( $options as $key => $option ) {
5859
			if ( 'error_code' === $key ) {
5860
				$returned_values[ $key ] = $option;
5861
				continue;
5862
			}
5863
5864
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5865
				continue;
5866
			}
5867
5868
			$returned_values[ $key ] = $normalized_url;
5869
		}
5870
5871
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5872
5873
		return $returned_values;
5874
	}
5875
5876
	/**
5877
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5878
	 * If set to true, the site will be put into staging mode.
5879
	 *
5880
	 * @since 4.3.2
5881
	 * @return bool
5882
	 */
5883
	public static function sync_idc_optin() {
5884
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5885
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5886
		} else {
5887
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5888
		}
5889
5890
		/**
5891
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5892
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5893
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5894
		 *
5895
		 * @since 4.3.2
5896
		 *
5897
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5898
		 */
5899
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5900
	}
5901
5902
	/**
5903
	 * Maybe Use a .min.css stylesheet, maybe not.
5904
	 *
5905
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5906
	 */
5907
	public static function maybe_min_asset( $url, $path, $plugin ) {
5908
		// Short out on things trying to find actual paths.
5909
		if ( ! $path || empty( $plugin ) ) {
5910
			return $url;
5911
		}
5912
5913
		$path = ltrim( $path, '/' );
5914
5915
		// Strip out the abspath.
5916
		$base = dirname( plugin_basename( $plugin ) );
5917
5918
		// Short out on non-Jetpack assets.
5919
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5920
			return $url;
5921
		}
5922
5923
		// File name parsing.
5924
		$file              = "{$base}/{$path}";
5925
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5926
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5927
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5928
		$extension         = array_shift( $file_name_parts_r );
5929
5930
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5931
			// Already pointing at the minified version.
5932
			if ( 'min' === $file_name_parts_r[0] ) {
5933
				return $url;
5934
			}
5935
5936
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5937
			if ( file_exists( $min_full_path ) ) {
5938
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5939
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5940
				if ( 'css' === $extension ) {
5941
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5942
					self::$min_assets[ $key ] = $path;
5943
				}
5944
			}
5945
		}
5946
5947
		return $url;
5948
	}
5949
5950
	/**
5951
	 * If the asset is minified, let's flag .min as the suffix.
5952
	 *
5953
	 * Attached to `style_loader_src` filter.
5954
	 *
5955
	 * @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...
5956
	 * @param string $handle The registered handle of the script in question.
5957
	 * @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...
5958
	 */
5959
	public static function set_suffix_on_min( $src, $handle ) {
5960
		if ( false === strpos( $src, '.min.css' ) ) {
5961
			return $src;
5962
		}
5963
5964
		if ( ! empty( self::$min_assets ) ) {
5965
			foreach ( self::$min_assets as $file => $path ) {
5966
				if ( false !== strpos( $src, $file ) ) {
5967
					wp_style_add_data( $handle, 'suffix', '.min' );
5968
					return $src;
5969
				}
5970
			}
5971
		}
5972
5973
		return $src;
5974
	}
5975
5976
	/**
5977
	 * Maybe inlines a stylesheet.
5978
	 *
5979
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5980
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5981
	 *
5982
	 * Attached to `style_loader_tag` filter.
5983
	 *
5984
	 * @param string $tag The tag that would link to the external asset.
5985
	 * @param string $handle The registered handle of the script in question.
5986
	 *
5987
	 * @return string
5988
	 */
5989
	public static function maybe_inline_style( $tag, $handle ) {
5990
		global $wp_styles;
5991
		$item = $wp_styles->registered[ $handle ];
5992
5993
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5994
			return $tag;
5995
		}
5996
5997
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5998
			$href = $matches[1];
5999
			// Strip off query string
6000
			if ( $pos = strpos( $href, '?' ) ) {
6001
				$href = substr( $href, 0, $pos );
6002
			}
6003
			// Strip off fragment
6004
			if ( $pos = strpos( $href, '#' ) ) {
6005
				$href = substr( $href, 0, $pos );
6006
			}
6007
		} else {
6008
			return $tag;
6009
		}
6010
6011
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6012
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6013
			return $tag;
6014
		}
6015
6016
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6017
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6018
			// And this isn't the pass that actually deals with the RTL version...
6019
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6020
				// Short out, as the RTL version will deal with it in a moment.
6021
				return $tag;
6022
			}
6023
		}
6024
6025
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6026
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6027
		if ( $css ) {
6028
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6029
			if ( empty( $item->extra['after'] ) ) {
6030
				wp_add_inline_style( $handle, $css );
6031
			} else {
6032
				array_unshift( $item->extra['after'], $css );
6033
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6034
			}
6035
		}
6036
6037
		return $tag;
6038
	}
6039
6040
	/**
6041
	 * Loads a view file from the views
6042
	 *
6043
	 * Data passed in with the $data parameter will be available in the
6044
	 * template file as $data['value']
6045
	 *
6046
	 * @param string $template - Template file to load
6047
	 * @param array $data - Any data to pass along to the template
6048
	 * @return boolean - If template file was found
6049
	 **/
6050
	public function load_view( $template, $data = array() ) {
6051
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6052
6053
		if( file_exists( $views_dir . $template ) ) {
6054
			require_once( $views_dir . $template );
6055
			return true;
6056
		}
6057
6058
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6059
		return false;
6060
	}
6061
6062
	/**
6063
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6064
	 */
6065
	public function deprecated_hooks() {
6066
		global $wp_filter;
6067
6068
		/*
6069
		 * Format:
6070
		 * deprecated_filter_name => replacement_name
6071
		 *
6072
		 * If there is no replacement, use null for replacement_name
6073
		 */
6074
		$deprecated_list = array(
6075
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6076
			'wpl_sharing_2014_1'                                     => null,
6077
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6078
			'jetpack_identity_crisis_options_to_check'               => null,
6079
			'update_option_jetpack_single_user_site'                 => null,
6080
			'audio_player_default_colors'                            => null,
6081
			'add_option_jetpack_featured_images_enabled'             => null,
6082
			'add_option_jetpack_update_details'                      => null,
6083
			'add_option_jetpack_updates'                             => null,
6084
			'add_option_jetpack_network_name'                        => null,
6085
			'add_option_jetpack_network_allow_new_registrations'     => null,
6086
			'add_option_jetpack_network_add_new_users'               => null,
6087
			'add_option_jetpack_network_site_upload_space'           => null,
6088
			'add_option_jetpack_network_upload_file_types'           => null,
6089
			'add_option_jetpack_network_enable_administration_menus' => null,
6090
			'add_option_jetpack_is_multi_site'                       => null,
6091
			'add_option_jetpack_is_main_network'                     => null,
6092
			'add_option_jetpack_main_network_site'                   => null,
6093
			'jetpack_sync_all_registered_options'                    => null,
6094
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6095
			'jetpack_is_post_mailable'                               => null,
6096
			'jetpack_seo_site_host'                                  => null,
6097
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6098
			'jetpack_holiday_snow_option_name'                       => null,
6099
			'jetpack_holiday_chance_of_snow'                         => null,
6100
			'jetpack_holiday_snow_js_url'                            => null,
6101
			'jetpack_is_holiday_snow_season'                         => null,
6102
			'jetpack_holiday_snow_option_updated'                    => null,
6103
			'jetpack_holiday_snowing'                                => null,
6104
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6105
			'jetpack_cache_plans'                                    => null,
6106
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6107
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6108
			'jetpack_enable_site_verification'                       => null,
6109
			'can_display_jetpack_manage_notice'                      => null,
6110
			// Removed in Jetpack 7.3.0
6111
			'atd_load_scripts'                                       => null,
6112
			'atd_http_post_timeout'                                  => null,
6113
			'atd_http_post_error'                                    => null,
6114
			'atd_service_domain'                                     => null,
6115
		);
6116
6117
		// This is a silly loop depth. Better way?
6118
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6119
			if ( has_action( $hook ) ) {
6120
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6121
					foreach( $values AS $hooked ) {
6122
						if ( is_callable( $hooked['function'] ) ) {
6123
							$function_name = 'an anonymous function';
6124
						} else {
6125
							$function_name = $hooked['function'];
6126
						}
6127
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6128
					}
6129
				}
6130
			}
6131
		}
6132
	}
6133
6134
	/**
6135
	 * Converts any url in a stylesheet, to the correct absolute url.
6136
	 *
6137
	 * Considerations:
6138
	 *  - Normal, relative URLs     `feh.png`
6139
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6140
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6141
	 *  - Absolute URLs             `http://domain.com/feh.png`
6142
	 *  - Domain root relative URLs `/feh.png`
6143
	 *
6144
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6145
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6146
	 *
6147
	 * @return mixed|string
6148
	 */
6149
	public static function absolutize_css_urls( $css, $css_file_url ) {
6150
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6151
		$css_dir = dirname( $css_file_url );
6152
		$p       = parse_url( $css_dir );
6153
		$domain  = sprintf(
6154
					'%1$s//%2$s%3$s%4$s',
6155
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6156
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6157
					$p['host'],
6158
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6159
				);
6160
6161
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6162
			$find = $replace = array();
6163
			foreach ( $matches as $match ) {
6164
				$url = trim( $match['path'], "'\" \t" );
6165
6166
				// If this is a data url, we don't want to mess with it.
6167
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6168
					continue;
6169
				}
6170
6171
				// If this is an absolute or protocol-agnostic url,
6172
				// we don't want to mess with it.
6173
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6174
					continue;
6175
				}
6176
6177
				switch ( substr( $url, 0, 1 ) ) {
6178
					case '/':
6179
						$absolute = $domain . $url;
6180
						break;
6181
					default:
6182
						$absolute = $css_dir . '/' . $url;
6183
				}
6184
6185
				$find[]    = $match[0];
6186
				$replace[] = sprintf( 'url("%s")', $absolute );
6187
			}
6188
			$css = str_replace( $find, $replace, $css );
6189
		}
6190
6191
		return $css;
6192
	}
6193
6194
	/**
6195
	 * This methods removes all of the registered css files on the front end
6196
	 * from Jetpack in favor of using a single file. In effect "imploding"
6197
	 * all the files into one file.
6198
	 *
6199
	 * Pros:
6200
	 * - Uses only ONE css asset connection instead of 15
6201
	 * - Saves a minimum of 56k
6202
	 * - Reduces server load
6203
	 * - Reduces time to first painted byte
6204
	 *
6205
	 * Cons:
6206
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6207
	 *		should not cause any issues with themes.
6208
	 * - Plugins/themes dequeuing styles no longer do anything. See
6209
	 *		jetpack_implode_frontend_css filter for a workaround
6210
	 *
6211
	 * For some situations developers may wish to disable css imploding and
6212
	 * instead operate in legacy mode where each file loads seperately and
6213
	 * can be edited individually or dequeued. This can be accomplished with
6214
	 * the following line:
6215
	 *
6216
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6217
	 *
6218
	 * @since 3.2
6219
	 **/
6220
	public function implode_frontend_css( $travis_test = false ) {
6221
		$do_implode = true;
6222
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6223
			$do_implode = false;
6224
		}
6225
6226
		// Do not implode CSS when the page loads via the AMP plugin.
6227
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6228
			$do_implode = false;
6229
		}
6230
6231
		/**
6232
		 * Allow CSS to be concatenated into a single jetpack.css file.
6233
		 *
6234
		 * @since 3.2.0
6235
		 *
6236
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6237
		 */
6238
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6239
6240
		// Do not use the imploded file when default behavior was altered through the filter
6241
		if ( ! $do_implode ) {
6242
			return;
6243
		}
6244
6245
		// We do not want to use the imploded file in dev mode, or if not connected
6246
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6247
			if ( ! $travis_test ) {
6248
				return;
6249
			}
6250
		}
6251
6252
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6253
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6254
			return;
6255
		}
6256
6257
		/*
6258
		 * Now we assume Jetpack is connected and able to serve the single
6259
		 * file.
6260
		 *
6261
		 * In the future there will be a check here to serve the file locally
6262
		 * or potentially from the Jetpack CDN
6263
		 *
6264
		 * For now:
6265
		 * - Enqueue a single imploded css file
6266
		 * - Zero out the style_loader_tag for the bundled ones
6267
		 * - Be happy, drink scotch
6268
		 */
6269
6270
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6271
6272
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6273
6274
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6275
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6276
	}
6277
6278
	function concat_remove_style_loader_tag( $tag, $handle ) {
6279
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6280
			$tag = '';
6281
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6282
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6283
			}
6284
		}
6285
6286
		return $tag;
6287
	}
6288
6289
	/*
6290
	 * Check the heartbeat data
6291
	 *
6292
	 * Organizes the heartbeat data by severity.  For example, if the site
6293
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6294
	 *
6295
	 * Data will be added to "caution" array, if it either:
6296
	 *  - Out of date Jetpack version
6297
	 *  - Out of date WP version
6298
	 *  - Out of date PHP version
6299
	 *
6300
	 * $return array $filtered_data
6301
	 */
6302
	public static function jetpack_check_heartbeat_data() {
6303
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6304
6305
		$good    = array();
6306
		$caution = array();
6307
		$bad     = array();
6308
6309
		foreach ( $raw_data as $stat => $value ) {
6310
6311
			// Check jetpack version
6312
			if ( 'version' == $stat ) {
6313
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6314
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6315
					continue;
6316
				}
6317
			}
6318
6319
			// Check WP version
6320
			if ( 'wp-version' == $stat ) {
6321
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6322
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6323
					continue;
6324
				}
6325
			}
6326
6327
			// Check PHP version
6328
			if ( 'php-version' == $stat ) {
6329
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6330
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6331
					continue;
6332
				}
6333
			}
6334
6335
			// Check ID crisis
6336
			if ( 'identitycrisis' == $stat ) {
6337
				if ( 'yes' == $value ) {
6338
					$bad[ $stat ] = $value;
6339
					continue;
6340
				}
6341
			}
6342
6343
			// The rest are good :)
6344
			$good[ $stat ] = $value;
6345
		}
6346
6347
		$filtered_data = array(
6348
			'good'    => $good,
6349
			'caution' => $caution,
6350
			'bad'     => $bad
6351
		);
6352
6353
		return $filtered_data;
6354
	}
6355
6356
6357
	/*
6358
	 * This method is used to organize all options that can be reset
6359
	 * without disconnecting Jetpack.
6360
	 *
6361
	 * It is used in class.jetpack-cli.php to reset options
6362
	 *
6363
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6364
	 *
6365
	 * @return array of options to delete.
6366
	 */
6367
	public static function get_jetpack_options_for_reset() {
6368
		return Jetpack_Options::get_options_for_reset();
6369
	}
6370
6371
	/*
6372
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6373
	 * so we can bring them directly to their site in calypso.
6374
	 *
6375
	 * @param string | url
6376
	 * @return string | url without the guff
6377
	 */
6378
	public static function build_raw_urls( $url ) {
6379
		$strip_http = '/.*?:\/\//i';
6380
		$url = preg_replace( $strip_http, '', $url  );
6381
		$url = str_replace( '/', '::', $url );
6382
		return $url;
6383
	}
6384
6385
	/**
6386
	 * Stores and prints out domains to prefetch for page speed optimization.
6387
	 *
6388
	 * @param mixed $new_urls
6389
	 */
6390
	public static function dns_prefetch( $new_urls = null ) {
6391
		static $prefetch_urls = array();
6392
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6393
			echo "\r\n";
6394
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6395
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6396
			}
6397
		} elseif ( ! empty( $new_urls ) ) {
6398
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6399
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6400
			}
6401
			foreach ( (array) $new_urls as $this_new_url ) {
6402
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6403
			}
6404
			$prefetch_urls = array_unique( $prefetch_urls );
6405
		}
6406
	}
6407
6408
	public function wp_dashboard_setup() {
6409
		if ( self::is_active() ) {
6410
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6411
		}
6412
6413
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6414
			$jetpack_logo = new Jetpack_Logo();
6415
			$widget_title = sprintf(
6416
				wp_kses(
6417
					/* translators: Placeholder is a Jetpack logo. */
6418
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6419
					array( 'span' => array() )
6420
				),
6421
				$jetpack_logo->get_jp_emblem( true )
6422
			);
6423
6424
			wp_add_dashboard_widget(
6425
				'jetpack_summary_widget',
6426
				$widget_title,
6427
				array( __CLASS__, 'dashboard_widget' )
6428
			);
6429
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6430
6431
			// If we're inactive and not in development mode, sort our box to the top.
6432
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6433
				global $wp_meta_boxes;
6434
6435
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6436
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6437
6438
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6439
			}
6440
		}
6441
	}
6442
6443
	/**
6444
	 * @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...
6445
	 * @return mixed
6446
	 */
6447
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6448
		if ( ! is_array( $sorted ) ) {
6449
			return $sorted;
6450
		}
6451
6452
		foreach ( $sorted as $box_context => $ids ) {
6453
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6454
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6455
				continue;
6456
			}
6457
6458
			$ids_array = explode( ',', $ids );
6459
			$key = array_search( 'dashboard_stats', $ids_array );
6460
6461
			if ( false !== $key ) {
6462
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6463
				$ids_array[ $key ] = 'jetpack_summary_widget';
6464
				$sorted[ $box_context ] = implode( ',', $ids_array );
6465
				// We've found it, stop searching, and just return.
6466
				break;
6467
			}
6468
		}
6469
6470
		return $sorted;
6471
	}
6472
6473
	public static function dashboard_widget() {
6474
		/**
6475
		 * Fires when the dashboard is loaded.
6476
		 *
6477
		 * @since 3.4.0
6478
		 */
6479
		do_action( 'jetpack_dashboard_widget' );
6480
	}
6481
6482
	public static function dashboard_widget_footer() {
6483
		?>
6484
		<footer>
6485
6486
		<div class="protect">
6487
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6488
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6489
				<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>
6490
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6491
				<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( array( 'action' => 'activate', 'module' => 'protect' ) ), 'jetpack_activate-protect' ) ); ?>" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6492
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6493
				</a>
6494
			<?php else : ?>
6495
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6496
			<?php endif; ?>
6497
		</div>
6498
6499
		<div class="akismet">
6500
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6501
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6502
				<p><?php echo esc_html_x( 'Spam comments blocked by Akismet.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6503
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6504
				<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'activate', 'plugin' => 'akismet/akismet.php' ), admin_url( 'plugins.php' ) ), 'activate-plugin_akismet/akismet.php' ) ); ?>" class="button button-jetpack">
6505
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6506
				</a>
6507
			<?php else : ?>
6508
				<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( 'Akismet can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
6509
			<?php endif; ?>
6510
		</div>
6511
6512
		</footer>
6513
		<?php
6514
	}
6515
6516
	/*
6517
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6518
	 */
6519
	function jetpack_icon_user_connected( $columns ) {
6520
		$columns['user_jetpack'] = '';
6521
		return $columns;
6522
	}
6523
6524
	/*
6525
	 * Show Jetpack icon if the user is linked.
6526
	 */
6527
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6528
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6529
			$jetpack_logo = new Jetpack_Logo();
6530
			$emblem_html = sprintf(
6531
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6532
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6533
				$jetpack_logo->get_jp_emblem()
6534
			);
6535
			return $emblem_html;
6536
		}
6537
6538
		return $val;
6539
	}
6540
6541
	/*
6542
	 * Style the Jetpack user column
6543
	 */
6544
	function jetpack_user_col_style() {
6545
		global $current_screen;
6546
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6547
			<style>
6548
				.fixed .column-user_jetpack {
6549
					width: 21px;
6550
				}
6551
				.jp-emblem-user-admin svg {
6552
					width: 20px;
6553
					height: 20px;
6554
				}
6555
				.jp-emblem-user-admin path {
6556
					fill: #00BE28;
6557
				}
6558
			</style>
6559
		<?php }
6560
	}
6561
6562
	/**
6563
	 * Checks if Akismet is active and working.
6564
	 *
6565
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6566
	 * that implied usage of methods present since more recent version.
6567
	 * See https://github.com/Automattic/jetpack/pull/9585
6568
	 *
6569
	 * @since  5.1.0
6570
	 *
6571
	 * @return bool True = Akismet available. False = Aksimet not available.
6572
	 */
6573
	public static function is_akismet_active() {
6574
		static $status = null;
6575
6576
		if ( ! is_null( $status ) ) {
6577
			return $status;
6578
		}
6579
6580
		// Check if a modern version of Akismet is active.
6581
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6582
			$status = false;
6583
			return $status;
6584
		}
6585
6586
		// Make sure there is a key known to Akismet at all before verifying key.
6587
		$akismet_key = Akismet::get_api_key();
6588
		if ( ! $akismet_key ) {
6589
			$status = false;
6590
			return $status;
6591
		}
6592
6593
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6594
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6595
6596
		// 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.
6597
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6598
		// We cache the result of the Akismet key verification for ten minutes.
6599
		if ( ! $akismet_key_state || $recheck ) {
6600
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6601
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6602
		}
6603
6604
		$status = 'valid' === $akismet_key_state;
6605
6606
		return $status;
6607
	}
6608
6609
	/**
6610
	 * @deprecated
6611
	 *
6612
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6613
	 */
6614
	public static function is_function_in_backtrace() {
6615
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6616
	}
6617
6618
	/**
6619
	 * Given a minified path, and a non-minified path, will return
6620
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6621
	 *
6622
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6623
	 * root Jetpack directory.
6624
	 *
6625
	 * @since 5.6.0
6626
	 *
6627
	 * @param string $min_path
6628
	 * @param string $non_min_path
6629
	 * @return string The URL to the file
6630
	 */
6631
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6632
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6633
	}
6634
6635
	/**
6636
	 * Checks for whether Jetpack Backup & Scan is enabled.
6637
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6638
	 * @return bool|int|mixed
6639
	 */
6640
	public static function is_rewind_enabled() {
6641
		if ( ! Jetpack::is_active() ) {
6642
			return false;
6643
		}
6644
6645
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6646
		if ( false === $rewind_enabled ) {
6647
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6648
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6649
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6650
				&& ! empty( $rewind_data['state'] )
6651
				&& 'active' === $rewind_data['state'] )
6652
				? 1
6653
				: 0;
6654
6655
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6656
		}
6657
		return $rewind_enabled;
6658
	}
6659
6660
	/**
6661
	 * Return Calypso environment value; used for developing Jetpack and pairing
6662
	 * it with different Calypso enrionments, such as localhost.
6663
	 *
6664
	 * @since 7.4.0
6665
	 *
6666
	 * @return string Calypso environment
6667
	 */
6668
	public static function get_calypso_env() {
6669
		if ( isset( $_GET['calypso_env'] ) ) {
6670
			return sanitize_key( $_GET['calypso_env'] );
6671
		}
6672
6673
		if ( getenv( 'CALYPSO_ENV' ) ) {
6674
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6675
		}
6676
6677
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6678
			return sanitize_key( CALYPSO_ENV );
6679
		}
6680
6681
		return '';
6682
	}
6683
6684
	/**
6685
	 * Checks whether or not TOS has been agreed upon.
6686
	 * Will return true if a user has clicked to register, or is already connected.
6687
	 */
6688
	public static function jetpack_tos_agreed() {
6689
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6690
	}
6691
6692
	/**
6693
	 * Handles activating default modules as well general cleanup for the new connection.
6694
	 *
6695
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6696
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6697
	 * @param boolean $send_state_messages          Whether to send state messages.
6698
	 * @return void
6699
	 */
6700
	public static function handle_post_authorization_actions(
6701
		$activate_sso = false,
6702
		$redirect_on_activation_error = false,
6703
		$send_state_messages = true
6704
	) {
6705
		$other_modules = $activate_sso
6706
			? array( 'sso' )
6707
			: array();
6708
6709
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6710
			Jetpack::delete_active_modules();
6711
6712
			Jetpack::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...
6713
		} else {
6714
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6715
		}
6716
6717
		// Since this is a fresh connection, be sure to clear out IDC options
6718
		Jetpack_IDC::clear_all_idc_options();
6719
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6720
6721
		// Start nonce cleaner
6722
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6723
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6724
6725
		if ( $send_state_messages ) {
6726
			Jetpack::state( 'message', 'authorized' );
6727
		}
6728
	}
6729
6730
	/**
6731
	 * Returns a boolean for whether backups UI should be displayed or not.
6732
	 *
6733
	 * @return bool Should backups UI be displayed?
6734
	 */
6735
	public static function show_backups_ui() {
6736
		/**
6737
		 * Whether UI for backups should be displayed.
6738
		 *
6739
		 * @since 6.5.0
6740
		 *
6741
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6742
		 */
6743
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6744
	}
6745
6746
	/*
6747
	 * Deprecated manage functions
6748
	 */
6749
	function prepare_manage_jetpack_notice() {
6750
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6751
	}
6752
	function manage_activate_screen() {
6753
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6754
	}
6755
	function admin_jetpack_manage_notice() {
6756
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6757
	}
6758
	function opt_out_jetpack_manage_url() {
6759
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6760
	}
6761
	function opt_in_jetpack_manage_url() {
6762
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6763
	}
6764
	function opt_in_jetpack_manage_notice() {
6765
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6766
	}
6767
	function can_display_jetpack_manage_notice() {
6768
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6769
	}
6770
6771
	/**
6772
	 * Clean leftoveruser meta.
6773
	 *
6774
	 * Delete Jetpack-related user meta when it is no longer needed.
6775
	 *
6776
	 * @since 7.3.0
6777
	 *
6778
	 * @param int $user_id User ID being updated.
6779
	 */
6780
	public static function user_meta_cleanup( $user_id ) {
6781
		$meta_keys = array(
6782
			// AtD removed from Jetpack 7.3
6783
			'AtD_options',
6784
			'AtD_check_when',
6785
			'AtD_guess_lang',
6786
			'AtD_ignored_phrases',
6787
		);
6788
6789
		foreach ( $meta_keys as $meta_key ) {
6790
			if ( get_user_meta( $user_id, $meta_key ) ) {
6791
				delete_user_meta( $user_id, $meta_key );
6792
			}
6793
		}
6794
	}
6795
6796
	function is_active_and_not_development_mode( $maybe ) {
6797
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6798
			return false;
6799
		}
6800
		return true;
6801
	}
6802
}
6803