Completed
Push — jetpack-sync-modules ( c75ff9...47dabd )
by
unknown
88:36 queued 80:13
created

class.jetpack.php (81 issues)

Upgrade to new PHP Analysis Engine

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

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

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

Loading history...
463
	 */
464
	static function update_active_modules( $modules ) {
465
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
466
		$active_modules       = Jetpack::get_active_modules();
467
		$new_active_modules   = array_diff( $modules, $current_modules );
468
		$new_inactive_modules = array_diff( $active_modules, $modules );
469
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
470
		$reindexed_modules    = array_values( $new_current_modules );
471
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
472
473
		foreach ( $new_active_modules as $module ) {
474
			/**
475
			 * Fires when a specific module is activated.
476
			 *
477
			 * @since 1.9.0
478
			 *
479
			 * @param string $module Module slug.
480
			 * @param boolean $success whether the module was activated. @since 4.2
481
			 */
482
			do_action( 'jetpack_activate_module', $module, $success );
483
			/**
484
			 * Fires when a module is activated.
485
			 * The dynamic part of the filter, $module, is the module slug.
486
			 *
487
			 * @since 1.9.0
488
			 *
489
			 * @param string $module Module slug.
490
			 */
491
			do_action( "jetpack_activate_module_$module", $module );
492
		}
493
494
		foreach ( $new_inactive_modules as $module ) {
495
			/**
496
			 * Fired after a module has been deactivated.
497
			 *
498
			 * @since 4.2.0
499
			 *
500
			 * @param string $module Module slug.
501
			 * @param boolean $success whether the module was deactivated.
502
			 */
503
			do_action( 'jetpack_deactivate_module', $module, $success );
504
			/**
505
			 * Fires when a module is deactivated.
506
			 * The dynamic part of the filter, $module, is the module slug.
507
			 *
508
			 * @since 1.9.0
509
			 *
510
			 * @param string $module Module slug.
511
			 */
512
			do_action( "jetpack_deactivate_module_$module", $module );
513
		}
514
515
		return $success;
516
	}
517
518
	static function delete_active_modules() {
519
		self::update_active_modules( array() );
520
	}
521
522
	/**
523
	 * Constructor.  Initializes WordPress hooks
524
	 */
525
	private function __construct() {
526
		/*
527
		 * Check for and alert any deprecated hooks
528
		 */
529
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
530
531
		/*
532
		 * Enable enhanced handling of previewing sites in Calypso
533
		 */
534
		if ( Jetpack::is_active() ) {
535
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
536
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
537
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
538
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
539
		}
540
541
		if ( self::jetpack_tos_agreed() ) {
542
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
543
			add_action( 'init', array( $tracking, 'init' ) );
544
		}
545
546
		/*
547
		 * Load things that should only be in Network Admin.
548
		 *
549
		 * For now blow away everything else until a more full
550
		 * understanding of what is needed at the network level is
551
		 * available
552
		 */
553
		if ( is_multisite() ) {
554
			Jetpack_Network::init();
555
		}
556
557
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
558
			return function() {
559
				return wp_generate_password( 32, false );
560
			};
561
		} );
562
563
		$this->connection_manager = new Connection_Manager( );
564
565
		/**
566
		 * Prepare Gutenberg Editor functionality
567
		 */
568
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
569
		Jetpack_Gutenberg::init();
570
		Jetpack_Gutenberg::load_independent_blocks();
571
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
572
573
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
574
575
		// Unlink user before deleting the user from .com
576
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
577
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
578
579
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
580
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
581
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
582
				define( 'XMLRPC_REQUEST', true );
583
			}
584
585
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
586
587
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
588
		}
589
590
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
591
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
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...
592
593
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
594
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
595
596
			$this->require_jetpack_authentication();
597
598
			if ( Jetpack::is_active() ) {
599
				// Hack to preserve $HTTP_RAW_POST_DATA
600
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
601
602 View Code Duplication
				if ( $this->verify_xml_rpc_signature() ) {
603
					// The actual API methods.
604
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
605
				} else {
606
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
607
					// active Jetpack connection, so that additional users can link their account.
608
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
609
				}
610 View Code Duplication
			} else {
611
				new XMLRPC_Connector( $this->connection_manager );
612
613
				// The bootstrap API methods.
614
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
615
616
				if ( $this->verify_xml_rpc_signature() ) {
617
					// the jetpack Provision method is available for blog-token-signed requests
618
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
619
				}
620
			}
621
622
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
623
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
624
		} elseif (
625
			is_admin() &&
626
			isset( $_POST['action'] ) && (
627
				'jetpack_upload_file' == $_POST['action'] ||
628
				'jetpack_update_file' == $_POST['action']
629
			)
630
		) {
631
			$this->require_jetpack_authentication();
632
			$this->add_remote_request_handlers();
633
		} else {
634
			if ( Jetpack::is_active() ) {
635
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
636
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
637
			} else {
638
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
639
			}
640
		}
641
642
		if ( Jetpack::is_active() ) {
643
			Jetpack_Heartbeat::init();
644
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
645
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
646
				Jetpack_Search_Performance_Logger::init();
647
			}
648
		}
649
650
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
651
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
652
653
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
654
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
655
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
656
		}
657
658
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
659
660
		add_action( 'admin_init', array( $this, 'admin_init' ) );
661
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
662
663
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
664
665
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
666
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
667
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
668
669
		// returns HTTPS support status
670
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
671
672
		// JITM AJAX callback function
673
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
674
675
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
676
677
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
678
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
679
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
680
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
681
682
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
683
684
		/**
685
		 * These actions run checks to load additional files.
686
		 * They check for external files or plugins, so they need to run as late as possible.
687
		 */
688
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
689
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
690
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
691
692
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
693
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
694
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
695
696
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
697
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
698
699
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
700
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
701
702
		// A filter to control all just in time messages
703
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
704
705
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
706
707
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
708
		// We should make sure to only do this for front end links.
709
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
710
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
711
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
712
713
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
714
			//so they point moderation links on emails to Calypso
715
			jetpack_require_lib( 'functions.wp-notify' );
716
		}
717
718
		// Update the Jetpack plan from API on heartbeats
719
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
720
721
		/**
722
		 * This is the hack to concatenate all css files into one.
723
		 * For description and reasoning see the implode_frontend_css method
724
		 *
725
		 * Super late priority so we catch all the registered styles
726
		 */
727
		if( !is_admin() ) {
728
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
729
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
730
		}
731
732
733
		/**
734
		 * These are sync actions that we need to keep track of for jitms
735
		 */
736
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
737
738
		// Actually push the stats on shutdown.
739
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
740
			add_action( 'shutdown', array( $this, 'push_stats' ) );
741
		}
742
743
	}
744
745
	function initialize_rest_api_registration_connector() {
746
		new REST_Connector( $this->connection_manager );
747
	}
748
749
	/**
750
	 * This is ported over from the manage module, which has been deprecated and baked in here.
751
	 *
752
	 * @param $domains
753
	 */
754
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
755
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
756
	}
757
758
	/**
759
	 * Return $domains, with 'wordpress.com' appended.
760
	 * This is ported over from the manage module, which has been deprecated and baked in here.
761
	 *
762
	 * @param $domains
763
	 * @return array
764
	 */
765
	function allow_wpcom_domain( $domains ) {
766
		if ( empty( $domains ) ) {
767
			$domains = array();
768
		}
769
		$domains[] = 'wordpress.com';
770
		return array_unique( $domains );
771
	}
772
773
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
774
		$post = get_post( $post_id );
775
776
		if ( empty( $post ) ) {
777
			return $default_url;
778
		}
779
780
		$post_type = $post->post_type;
781
782
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
783
		// https://en.support.wordpress.com/custom-post-types/
784
		$allowed_post_types = array(
785
			'post' => 'post',
786
			'page' => 'page',
787
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
788
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
789
		);
790
791
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
792
			return $default_url;
793
		}
794
795
		$path_prefix = $allowed_post_types[ $post_type ];
796
797
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
798
799
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
800
	}
801
802
	function point_edit_comment_links_to_calypso( $url ) {
803
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
804
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
The variable $query_args does not exist. Did you forget to declare it?

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

Loading history...
805
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
806
			Jetpack::build_raw_urls( get_home_url() ),
807
			$query_args['amp;c']
808
		) );
809
	}
810
811
	function jetpack_track_last_sync_callback( $params ) {
812
		/**
813
		 * Filter to turn off jitm caching
814
		 *
815
		 * @since 5.4.0
816
		 *
817
		 * @param bool false Whether to cache just in time messages
818
		 */
819
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
820
			return $params;
821
		}
822
823
		if ( is_array( $params ) && isset( $params[0] ) ) {
824
			$option = $params[0];
825
			if ( 'active_plugins' === $option ) {
826
				// use the cache if we can, but not terribly important if it gets evicted
827
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
828
			}
829
		}
830
831
		return $params;
832
	}
833
834
	function jetpack_connection_banner_callback() {
835
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
836
837
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
838
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
839
			wp_send_json_success();
840
		}
841
842
		wp_die();
843
	}
844
845
	/**
846
	 * Removes all XML-RPC methods that are not `jetpack.*`.
847
	 * Only used in our alternate XML-RPC endpoint, where we want to
848
	 * ensure that Core and other plugins' methods are not exposed.
849
	 *
850
	 * @param array $methods
851
	 * @return array filtered $methods
852
	 */
853
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
854
		$jetpack_methods = array();
855
856
		foreach ( $methods as $method => $callback ) {
857
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
858
				$jetpack_methods[ $method ] = $callback;
859
			}
860
		}
861
862
		return $jetpack_methods;
863
	}
864
865
	/**
866
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
867
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
868
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
869
	 * which is accessible via a different URI. Most of the below is copied directly
870
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
871
	 */
872
	function alternate_xmlrpc() {
873
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
874
		global $HTTP_RAW_POST_DATA;
875
876
		// Some browser-embedded clients send cookies. We don't want them.
877
		$_COOKIE = array();
878
879
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
880
		// but we can do it ourself.
881
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
882
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
883
		}
884
885
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
886
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
887
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
888
		}
889
890
		// phpcs:enable
891
892
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
893
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
894
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
895
896
		/**
897
		 * Filters the class used for handling XML-RPC requests.
898
		 *
899
		 * @since 3.1.0
900
		 *
901
		 * @param string $class The name of the XML-RPC server class.
902
		 */
903
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
904
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
905
906
		// Fire off the request
907
		nocache_headers();
908
		$wp_xmlrpc_server->serve_request();
909
910
		exit;
911
	}
912
913
	/**
914
	 * The callback for the JITM ajax requests.
915
	 */
916
	function jetpack_jitm_ajax_callback() {
917
		// Check for nonce
918
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
919
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
920
		}
921
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
922
			$module_slug = $_REQUEST['jitmModule'];
923
			Jetpack::log( 'activate', $module_slug );
924
			Jetpack::activate_module( $module_slug, false, false );
925
			Jetpack::state( 'message', 'no_message' );
926
927
			//A Jetpack module is being activated through a JITM, track it
928
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
929
			$this->do_stats( 'server_side' );
930
931
			wp_send_json_success();
932
		}
933
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
934
			// get the hide_jitm options array
935
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
936
			$module_slug = $_REQUEST['jitmModule'];
937
938
			if( ! $jetpack_hide_jitm ) {
939
				$jetpack_hide_jitm = array(
940
					$module_slug => 'hide'
941
				);
942
			} else {
943
				$jetpack_hide_jitm[$module_slug] = 'hide';
944
			}
945
946
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
947
948
			//jitm is being dismissed forever, track it
949
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
950
			$this->do_stats( 'server_side' );
951
952
			wp_send_json_success();
953
		}
954 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
955
			$module_slug = $_REQUEST['jitmModule'];
956
957
			// User went to WordPress.com, track this
958
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
959
			$this->do_stats( 'server_side' );
960
961
			wp_send_json_success();
962
		}
963 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
964
			$track = $_REQUEST['jitmModule'];
965
966
			// User is viewing JITM, track it.
967
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
968
			$this->do_stats( 'server_side' );
969
970
			wp_send_json_success();
971
		}
972
	}
973
974
	/**
975
	 * If there are any stats that need to be pushed, but haven't been, push them now.
976
	 */
977
	function push_stats() {
978
		if ( ! empty( $this->stats ) ) {
979
			$this->do_stats( 'server_side' );
980
		}
981
	}
982
983
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
984
		switch( $cap ) {
985
			case 'jetpack_connect' :
986
			case 'jetpack_reconnect' :
987
				if ( Jetpack::is_development_mode() ) {
988
					$caps = array( 'do_not_allow' );
989
					break;
990
				}
991
				/**
992
				 * Pass through. If it's not development mode, these should match disconnect.
993
				 * Let users disconnect if it's development mode, just in case things glitch.
994
				 */
995
			case 'jetpack_disconnect' :
996
				/**
997
				 * In multisite, can individual site admins manage their own connection?
998
				 *
999
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1000
				 */
1001
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1002
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1003
						/**
1004
						 * We need to update the option name -- it's terribly unclear which
1005
						 * direction the override goes.
1006
						 *
1007
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1008
						 */
1009
						$caps = array( 'do_not_allow' );
1010
						break;
1011
					}
1012
				}
1013
1014
				$caps = array( 'manage_options' );
1015
				break;
1016
			case 'jetpack_manage_modules' :
1017
			case 'jetpack_activate_modules' :
1018
			case 'jetpack_deactivate_modules' :
1019
				$caps = array( 'manage_options' );
1020
				break;
1021
			case 'jetpack_configure_modules' :
1022
				$caps = array( 'manage_options' );
1023
				break;
1024
			case 'jetpack_manage_autoupdates' :
1025
				$caps = array(
1026
					'manage_options',
1027
					'update_plugins',
1028
				);
1029
				break;
1030
			case 'jetpack_network_admin_page':
1031
			case 'jetpack_network_settings_page':
1032
				$caps = array( 'manage_network_plugins' );
1033
				break;
1034
			case 'jetpack_network_sites_page':
1035
				$caps = array( 'manage_sites' );
1036
				break;
1037
			case 'jetpack_admin_page' :
1038
				if ( Jetpack::is_development_mode() ) {
1039
					$caps = array( 'manage_options' );
1040
					break;
1041
				} else {
1042
					$caps = array( 'read' );
1043
				}
1044
				break;
1045
			case 'jetpack_connect_user' :
1046
				if ( Jetpack::is_development_mode() ) {
1047
					$caps = array( 'do_not_allow' );
1048
					break;
1049
				}
1050
				$caps = array( 'read' );
1051
				break;
1052
		}
1053
		return $caps;
1054
	}
1055
1056
	function require_jetpack_authentication() {
1057
		// Don't let anyone authenticate
1058
		$_COOKIE = array();
1059
		remove_all_filters( 'authenticate' );
1060
		remove_all_actions( 'wp_login_failed' );
1061
1062
		if ( Jetpack::is_active() ) {
1063
			// Allow Jetpack authentication
1064
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1065
		}
1066
	}
1067
1068
	/**
1069
	 * Load language files
1070
	 * @action plugins_loaded
1071
	 */
1072
	public static function plugin_textdomain() {
1073
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1074
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1075
	}
1076
1077
	/**
1078
	 * Register assets for use in various modules and the Jetpack admin page.
1079
	 *
1080
	 * @uses wp_script_is, wp_register_script, plugins_url
1081
	 * @action wp_loaded
1082
	 * @return null
1083
	 */
1084
	public function register_assets() {
1085
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1086
			wp_register_script(
1087
				'spin',
1088
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1089
				false,
1090
				'1.3'
1091
			);
1092
		}
1093
1094
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1095
			wp_register_script(
1096
				'jquery.spin',
1097
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1098
				array( 'jquery', 'spin' ),
1099
				'1.3'
1100
			);
1101
		}
1102
1103 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1104
			wp_register_script(
1105
				'jetpack-gallery-settings',
1106
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1107
				array( 'media-views' ),
1108
				'20121225'
1109
			);
1110
		}
1111
1112
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1113
			wp_register_script(
1114
				'jetpack-twitter-timeline',
1115
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1116
				array( 'jquery' ),
1117
				'4.0.0',
1118
				true
1119
			);
1120
		}
1121
1122
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1123
			wp_register_script(
1124
				'jetpack-facebook-embed',
1125
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1126
				array( 'jquery' ),
1127
				null,
1128
				true
1129
			);
1130
1131
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1132
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1133
			if ( ! is_numeric( $fb_app_id ) ) {
1134
				$fb_app_id = '';
1135
			}
1136
			wp_localize_script(
1137
				'jetpack-facebook-embed',
1138
				'jpfbembed',
1139
				array(
1140
					'appid' => $fb_app_id,
1141
					'locale' => $this->get_locale(),
1142
				)
1143
			);
1144
		}
1145
1146
		/**
1147
		 * As jetpack_register_genericons is by default fired off a hook,
1148
		 * the hook may have already fired by this point.
1149
		 * So, let's just trigger it manually.
1150
		 */
1151
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1152
		jetpack_register_genericons();
1153
1154
		/**
1155
		 * Register the social logos
1156
		 */
1157
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1158
		jetpack_register_social_logos();
1159
1160 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1161
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1162
	}
1163
1164
	/**
1165
	 * Guess locale from language code.
1166
	 *
1167
	 * @param string $lang Language code.
1168
	 * @return string|bool
1169
	 */
1170 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1171
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1172
			return 'en_US';
1173
		}
1174
1175
		if ( ! class_exists( 'GP_Locales' ) ) {
1176
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1177
				return false;
1178
			}
1179
1180
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1181
		}
1182
1183
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1184
			// WP.com: get_locale() returns 'it'
1185
			$locale = GP_Locales::by_slug( $lang );
1186
		} else {
1187
			// Jetpack: get_locale() returns 'it_IT';
1188
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1189
		}
1190
1191
		if ( ! $locale ) {
1192
			return false;
1193
		}
1194
1195
		if ( empty( $locale->facebook_locale ) ) {
1196
			if ( empty( $locale->wp_locale ) ) {
1197
				return false;
1198
			} else {
1199
				// Facebook SDK is smart enough to fall back to en_US if a
1200
				// locale isn't supported. Since supported Facebook locales
1201
				// can fall out of sync, we'll attempt to use the known
1202
				// wp_locale value and rely on said fallback.
1203
				return $locale->wp_locale;
1204
			}
1205
		}
1206
1207
		return $locale->facebook_locale;
1208
	}
1209
1210
	/**
1211
	 * Get the locale.
1212
	 *
1213
	 * @return string|bool
1214
	 */
1215
	function get_locale() {
1216
		$locale = $this->guess_locale_from_lang( get_locale() );
1217
1218
		if ( ! $locale ) {
1219
			$locale = 'en_US';
1220
		}
1221
1222
		return $locale;
1223
	}
1224
1225
	/**
1226
	 * Device Pixels support
1227
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1228
	 */
1229
	function devicepx() {
1230
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1231
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1232
		}
1233
	}
1234
1235
	/**
1236
	 * Return the network_site_url so that .com knows what network this site is a part of.
1237
	 * @param  bool $option
1238
	 * @return string
1239
	 */
1240
	public function jetpack_main_network_site_option( $option ) {
1241
		return network_site_url();
1242
	}
1243
	/**
1244
	 * Network Name.
1245
	 */
1246
	static function network_name( $option = null ) {
1247
		global $current_site;
1248
		return $current_site->site_name;
1249
	}
1250
	/**
1251
	 * Does the network allow new user and site registrations.
1252
	 * @return string
1253
	 */
1254
	static function network_allow_new_registrations( $option = null ) {
1255
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1256
	}
1257
	/**
1258
	 * Does the network allow admins to add new users.
1259
	 * @return boolian
1260
	 */
1261
	static function network_add_new_users( $option = null ) {
1262
		return (bool) get_site_option( 'add_new_users' );
1263
	}
1264
	/**
1265
	 * File upload psace left per site in MB.
1266
	 *  -1 means NO LIMIT.
1267
	 * @return number
1268
	 */
1269
	static function network_site_upload_space( $option = null ) {
1270
		// value in MB
1271
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1272
	}
1273
1274
	/**
1275
	 * Network allowed file types.
1276
	 * @return string
1277
	 */
1278
	static function network_upload_file_types( $option = null ) {
1279
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1280
	}
1281
1282
	/**
1283
	 * Maximum file upload size set by the network.
1284
	 * @return number
1285
	 */
1286
	static function network_max_upload_file_size( $option = null ) {
1287
		// value in KB
1288
		return get_site_option( 'fileupload_maxk', 300 );
1289
	}
1290
1291
	/**
1292
	 * Lets us know if a site allows admins to manage the network.
1293
	 * @return array
1294
	 */
1295
	static function network_enable_administration_menus( $option = null ) {
1296
		return get_site_option( 'menu_items' );
1297
	}
1298
1299
	/**
1300
	 * If a user has been promoted to or demoted from admin, we need to clear the
1301
	 * jetpack_other_linked_admins transient.
1302
	 *
1303
	 * @since 4.3.2
1304
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1305
	 *
1306
	 * @param int    $user_id   The user ID whose role changed.
1307
	 * @param string $role      The new role.
1308
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Should the type for parameter $old_roles not be array|null?

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2264
2265
		if ( $redirect ) {
2266
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2267
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2268
				$page = $_GET['page'];
2269
			}
2270
2271
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2272
			exit;
2273
		}
2274
	}
2275
2276
	/**
2277
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2278
	 * Make sure to tuck away module "library" files in a sub-directory.
2279
	 */
2280
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2281
		static $modules = null;
2282
2283
		if ( ! isset( $modules ) ) {
2284
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2285
			// Use the cache if we're on the front-end and it's available...
2286
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2287
				$modules = $available_modules_option[ JETPACK__VERSION ];
2288
			} else {
2289
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2290
2291
				$modules = array();
2292
2293
				foreach ( $files as $file ) {
2294
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2295
						continue;
2296
					}
2297
2298
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2299
				}
2300
2301
				Jetpack_Options::update_option( 'available_modules', array(
2302
					JETPACK__VERSION => $modules,
2303
				) );
2304
			}
2305
		}
2306
2307
		/**
2308
		 * Filters the array of modules available to be activated.
2309
		 *
2310
		 * @since 2.4.0
2311
		 *
2312
		 * @param array $modules Array of available modules.
2313
		 * @param string $min_version Minimum version number required to use modules.
2314
		 * @param string $max_version Maximum version number required to use modules.
2315
		 */
2316
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2317
2318
		if ( ! $min_version && ! $max_version ) {
2319
			return array_keys( $mods );
2320
		}
2321
2322
		$r = array();
2323
		foreach ( $mods as $slug => $introduced ) {
2324
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2325
				continue;
2326
			}
2327
2328
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2329
				continue;
2330
			}
2331
2332
			$r[] = $slug;
2333
		}
2334
2335
		return $r;
2336
	}
2337
2338
	/**
2339
	 * Default modules loaded on activation.
2340
	 */
2341
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2342
		$return = array();
2343
2344
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2345
			$module_data = Jetpack::get_module( $module );
2346
2347
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2348
				case 'yes' :
2349
					$return[] = $module;
2350
					break;
2351
				case 'public' :
2352
					if ( Jetpack_Options::get_option( 'public' ) ) {
2353
						$return[] = $module;
2354
					}
2355
					break;
2356
				case 'no' :
2357
				default :
2358
					break;
2359
			}
2360
		}
2361
		/**
2362
		 * Filters the array of default modules.
2363
		 *
2364
		 * @since 2.5.0
2365
		 *
2366
		 * @param array $return Array of default modules.
2367
		 * @param string $min_version Minimum version number required to use modules.
2368
		 * @param string $max_version Maximum version number required to use modules.
2369
		 */
2370
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2371
	}
2372
2373
	/**
2374
	 * Checks activated modules during auto-activation to determine
2375
	 * if any of those modules are being deprecated.  If so, close
2376
	 * them out, and add any replacement modules.
2377
	 *
2378
	 * Runs at priority 99 by default.
2379
	 *
2380
	 * This is run late, so that it can still activate a module if
2381
	 * the new module is a replacement for another that the user
2382
	 * currently has active, even if something at the normal priority
2383
	 * would kibosh everything.
2384
	 *
2385
	 * @since 2.6
2386
	 * @uses jetpack_get_default_modules filter
2387
	 * @param array $modules
2388
	 * @return array
2389
	 */
2390
	function handle_deprecated_modules( $modules ) {
2391
		$deprecated_modules = array(
2392
			'debug'            => null,  // Closed out and moved to the debugger library.
2393
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2394
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2395
		);
2396
2397
		// Don't activate SSO if they never completed activating WPCC.
2398
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2399
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2400
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2401
				$deprecated_modules['wpcc'] = null;
2402
			}
2403
		}
2404
2405
		foreach ( $deprecated_modules as $module => $replacement ) {
2406
			if ( Jetpack::is_module_active( $module ) ) {
2407
				self::deactivate_module( $module );
2408
				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...
2409
					$modules[] = $replacement;
2410
				}
2411
			}
2412
		}
2413
2414
		return array_unique( $modules );
2415
	}
2416
2417
	/**
2418
	 * Checks activated plugins during auto-activation to determine
2419
	 * if any of those plugins are in the list with a corresponding module
2420
	 * that is not compatible with the plugin. The module will not be allowed
2421
	 * to auto-activate.
2422
	 *
2423
	 * @since 2.6
2424
	 * @uses jetpack_get_default_modules filter
2425
	 * @param array $modules
2426
	 * @return array
2427
	 */
2428
	function filter_default_modules( $modules ) {
2429
2430
		$active_plugins = self::get_active_plugins();
2431
2432
		if ( ! empty( $active_plugins ) ) {
2433
2434
			// For each module we'd like to auto-activate...
2435
			foreach ( $modules as $key => $module ) {
2436
				// If there are potential conflicts for it...
2437
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2438
					// For each potential conflict...
2439
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2440
						// If that conflicting plugin is active...
2441
						if ( in_array( $plugin, $active_plugins ) ) {
2442
							// Remove that item from being auto-activated.
2443
							unset( $modules[ $key ] );
2444
						}
2445
					}
2446
				}
2447
			}
2448
		}
2449
2450
		return $modules;
2451
	}
2452
2453
	/**
2454
	 * Extract a module's slug from its full path.
2455
	 */
2456
	public static function get_module_slug( $file ) {
2457
		return str_replace( '.php', '', basename( $file ) );
2458
	}
2459
2460
	/**
2461
	 * Generate a module's path from its slug.
2462
	 */
2463
	public static function get_module_path( $slug ) {
2464
		/**
2465
		 * Filters the path of a modules.
2466
		 *
2467
		 * @since 7.4.0
2468
		 *
2469
		 * @param array $return The absolute path to a module's root php file
2470
		 * @param string $slug The module slug
2471
		 */
2472
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2473
	}
2474
2475
	/**
2476
	 * Load module data from module file. Headers differ from WordPress
2477
	 * plugin headers to avoid them being identified as standalone
2478
	 * plugins on the WordPress plugins page.
2479
	 */
2480
	public static function get_module( $module ) {
2481
		$headers = array(
2482
			'name'                      => 'Module Name',
2483
			'description'               => 'Module Description',
2484
			'sort'                      => 'Sort Order',
2485
			'recommendation_order'      => 'Recommendation Order',
2486
			'introduced'                => 'First Introduced',
2487
			'changed'                   => 'Major Changes In',
2488
			'deactivate'                => 'Deactivate',
2489
			'free'                      => 'Free',
2490
			'requires_connection'       => 'Requires Connection',
2491
			'auto_activate'             => 'Auto Activate',
2492
			'module_tags'               => 'Module Tags',
2493
			'feature'                   => 'Feature',
2494
			'additional_search_queries' => 'Additional Search Queries',
2495
			'plan_classes'              => 'Plans',
2496
		);
2497
2498
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2499
2500
		$mod = Jetpack::get_file_data( $file, $headers );
2501
		if ( empty( $mod['name'] ) ) {
2502
			return false;
2503
		}
2504
2505
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2506
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2507
		$mod['deactivate']              = empty( $mod['deactivate'] );
2508
		$mod['free']                    = empty( $mod['free'] );
2509
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2510
2511
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2512
			$mod['auto_activate'] = 'No';
2513
		} else {
2514
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2515
		}
2516
2517
		if ( $mod['module_tags'] ) {
2518
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2519
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2520
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2521
		} else {
2522
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2523
		}
2524
2525 View Code Duplication
		if ( $mod['plan_classes'] ) {
2526
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2527
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2528
		} else {
2529
			$mod['plan_classes'] = array( 'free' );
2530
		}
2531
2532 View Code Duplication
		if ( $mod['feature'] ) {
2533
			$mod['feature'] = explode( ',', $mod['feature'] );
2534
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2535
		} else {
2536
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2537
		}
2538
2539
		/**
2540
		 * Filters the feature array on a module.
2541
		 *
2542
		 * This filter allows you to control where each module is filtered: Recommended,
2543
		 * and the default "Other" listing.
2544
		 *
2545
		 * @since 3.5.0
2546
		 *
2547
		 * @param array   $mod['feature'] The areas to feature this module:
2548
		 *     'Recommended' shows on the main Jetpack admin screen.
2549
		 *     'Other' should be the default if no other value is in the array.
2550
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2551
		 * @param array   $mod All the currently assembled module data.
2552
		 */
2553
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2554
2555
		/**
2556
		 * Filter the returned data about a module.
2557
		 *
2558
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2559
		 * so please be careful.
2560
		 *
2561
		 * @since 3.6.0
2562
		 *
2563
		 * @param array   $mod    The details of the requested module.
2564
		 * @param string  $module The slug of the module, e.g. sharedaddy
2565
		 * @param string  $file   The path to the module source file.
2566
		 */
2567
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2568
	}
2569
2570
	/**
2571
	 * Like core's get_file_data implementation, but caches the result.
2572
	 */
2573
	public static function get_file_data( $file, $headers ) {
2574
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2575
		$file_name = basename( $file );
2576
2577
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2578
2579
		$file_data_option = get_transient( $cache_key );
2580
2581
		if ( false === $file_data_option ) {
2582
			$file_data_option = array();
2583
		}
2584
2585
		$key           = md5( $file_name . serialize( $headers ) );
2586
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2587
2588
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2589
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2590
			return $file_data_option[ $key ];
2591
		}
2592
2593
		$data = get_file_data( $file, $headers );
2594
2595
		$file_data_option[ $key ] = $data;
2596
2597
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2598
2599
		return $data;
2600
	}
2601
2602
2603
	/**
2604
	 * Return translated module tag.
2605
	 *
2606
	 * @param string $tag Tag as it appears in each module heading.
2607
	 *
2608
	 * @return mixed
2609
	 */
2610
	public static function translate_module_tag( $tag ) {
2611
		return jetpack_get_module_i18n_tag( $tag );
2612
	}
2613
2614
	/**
2615
	 * Get i18n strings as a JSON-encoded string
2616
	 *
2617
	 * @return string The locale as JSON
2618
	 */
2619
	public static function get_i18n_data_json() {
2620
2621
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2622
		// JSON files with the file they should be included for. This is an md5
2623
		// of '_inc/build/admin.js'.
2624
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2625
2626
		$i18n_json =
2627
				   JETPACK__PLUGIN_DIR
2628
				   . 'languages/json/jetpack-'
2629
				   . get_user_locale()
2630
				   . '-'
2631
				   . $path_md5
2632
				   . '.json';
2633
2634
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2635
			$locale_data = @file_get_contents( $i18n_json );
2636
			if ( $locale_data ) {
2637
				return $locale_data;
2638
			}
2639
		}
2640
2641
		// Return valid empty Jed locale
2642
		return '{ "locale_data": { "messages": { "": {} } } }';
2643
	}
2644
2645
	/**
2646
	 * Add locale data setup to wp-i18n
2647
	 *
2648
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2649
	 *
2650
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2651
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2652
	 *
2653
	 * This method provides a safe way to request the setup multiple times but add the script at
2654
	 * most once.
2655
	 *
2656
	 * @since 6.7.0
2657
	 *
2658
	 * @return void
2659
	 */
2660
	public static function setup_wp_i18n_locale_data() {
2661
		static $script_added = false;
2662
		if ( ! $script_added ) {
2663
			$script_added = true;
2664
			wp_add_inline_script(
2665
				'wp-i18n',
2666
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2667
			);
2668
		}
2669
	}
2670
2671
	/**
2672
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2673
	 *
2674
	 * @since 3.9.2
2675
	 *
2676
	 * @param array $modules
2677
	 *
2678
	 * @return string|void
2679
	 */
2680
	public static function get_translated_modules( $modules ) {
2681
		foreach ( $modules as $index => $module ) {
2682
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2683
			if ( isset( $module['name'] ) ) {
2684
				$modules[ $index ]['name'] = $i18n_module['name'];
2685
			}
2686
			if ( isset( $module['description'] ) ) {
2687
				$modules[ $index ]['description'] = $i18n_module['description'];
2688
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2689
			}
2690
		}
2691
		return $modules;
2692
	}
2693
2694
	/**
2695
	 * Get a list of activated modules as an array of module slugs.
2696
	 */
2697
	public static function get_active_modules() {
2698
		$active = Jetpack_Options::get_option( 'active_modules' );
2699
2700
		if ( ! is_array( $active ) ) {
2701
			$active = array();
2702
		}
2703
2704
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2705
			$active[] = 'vaultpress';
2706
		} else {
2707
			$active = array_diff( $active, array( 'vaultpress' ) );
2708
		}
2709
2710
		//If protect is active on the main site of a multisite, it should be active on all sites.
2711
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2712
			$active[] = 'protect';
2713
		}
2714
2715
		/**
2716
		 * Allow filtering of the active modules.
2717
		 *
2718
		 * Gives theme and plugin developers the power to alter the modules that
2719
		 * are activated on the fly.
2720
		 *
2721
		 * @since 5.8.0
2722
		 *
2723
		 * @param array $active Array of active module slugs.
2724
		 */
2725
		$active = apply_filters( 'jetpack_active_modules', $active );
2726
2727
		return array_unique( $active );
2728
	}
2729
2730
	/**
2731
	 * Check whether or not a Jetpack module is active.
2732
	 *
2733
	 * @param string $module The slug of a Jetpack module.
2734
	 * @return bool
2735
	 *
2736
	 * @static
2737
	 */
2738
	public static function is_module_active( $module ) {
2739
		return in_array( $module, self::get_active_modules() );
2740
	}
2741
2742
	public static function is_module( $module ) {
2743
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2744
	}
2745
2746
	/**
2747
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2748
	 *
2749
	 * @param bool $catch True to start catching, False to stop.
2750
	 *
2751
	 * @static
2752
	 */
2753
	public static function catch_errors( $catch ) {
2754
		static $display_errors, $error_reporting;
2755
2756
		if ( $catch ) {
2757
			$display_errors  = @ini_set( 'display_errors', 1 );
2758
			$error_reporting = @error_reporting( E_ALL );
2759
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2760
		} else {
2761
			@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...
2762
			@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...
2763
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2764
		}
2765
	}
2766
2767
	/**
2768
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2769
	 */
2770
	public static function catch_errors_on_shutdown() {
2771
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2772
	}
2773
2774
	/**
2775
	 * Rewrite any string to make paths easier to read.
2776
	 *
2777
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2778
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2779
	 *
2780
	 * @param $string
2781
	 * @return mixed
2782
	 */
2783
	public static function alias_directories( $string ) {
2784
		// ABSPATH has a trailing slash.
2785
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2786
		// WP_CONTENT_DIR does not have a trailing slash.
2787
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2788
2789
		return $string;
2790
	}
2791
2792
	public static function activate_default_modules(
2793
		$min_version = false,
2794
		$max_version = false,
2795
		$other_modules = array(),
2796
		$redirect = true,
2797
		$send_state_messages = true
2798
	) {
2799
		$jetpack = Jetpack::init();
2800
2801
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2802
		$modules = array_merge( $other_modules, $modules );
2803
2804
		// Look for standalone plugins and disable if active.
2805
2806
		$to_deactivate = array();
2807
		foreach ( $modules as $module ) {
2808
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2809
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2810
			}
2811
		}
2812
2813
		$deactivated = array();
2814
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2815
			list( $probable_file, $probable_title ) = $deactivate_me;
2816
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2817
				$deactivated[] = $module;
2818
			}
2819
		}
2820
2821
		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...
2822
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2823
2824
			$url = add_query_arg(
2825
				array(
2826
					'action'   => 'activate_default_modules',
2827
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2828
				),
2829
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2830
			);
2831
			wp_safe_redirect( $url );
2832
			exit;
2833
		}
2834
2835
		/**
2836
		 * Fires before default modules are activated.
2837
		 *
2838
		 * @since 1.9.0
2839
		 *
2840
		 * @param string $min_version Minimum version number required to use modules.
2841
		 * @param string $max_version Maximum version number required to use modules.
2842
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2843
		 */
2844
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2845
2846
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2847
		if ( $send_state_messages ) {
2848
			Jetpack::restate();
2849
			Jetpack::catch_errors( true );
2850
		}
2851
2852
		$active = Jetpack::get_active_modules();
2853
2854
		foreach ( $modules as $module ) {
2855
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2856
				$active[] = $module;
2857
				self::update_active_modules( $active );
2858
				continue;
2859
			}
2860
2861
			if ( $send_state_messages && in_array( $module, $active ) ) {
2862
				$module_info = Jetpack::get_module( $module );
2863 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2864
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2865
					if ( $active_state = Jetpack::state( $state ) ) {
2866
						$active_state = explode( ',', $active_state );
2867
					} else {
2868
						$active_state = array();
2869
					}
2870
					$active_state[] = $module;
2871
					Jetpack::state( $state, implode( ',', $active_state ) );
2872
				}
2873
				continue;
2874
			}
2875
2876
			$file = Jetpack::get_module_path( $module );
2877
			if ( ! file_exists( $file ) ) {
2878
				continue;
2879
			}
2880
2881
			// we'll override this later if the plugin can be included without fatal error
2882
			if ( $redirect ) {
2883
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2884
			}
2885
2886
			if ( $send_state_messages ) {
2887
				Jetpack::state( 'error', 'module_activation_failed' );
2888
				Jetpack::state( 'module', $module );
2889
			}
2890
2891
			ob_start();
2892
			require_once $file;
2893
2894
			$active[] = $module;
2895
2896 View Code Duplication
			if ( $send_state_messages ) {
2897
2898
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2899
				if ( $active_state = Jetpack::state( $state ) ) {
2900
					$active_state = explode( ',', $active_state );
2901
				} else {
2902
					$active_state = array();
2903
				}
2904
				$active_state[] = $module;
2905
				Jetpack::state( $state, implode( ',', $active_state ) );
2906
			}
2907
2908
			Jetpack::update_active_modules( $active );
2909
2910
			ob_end_clean();
2911
		}
2912
2913
		if ( $send_state_messages ) {
2914
			Jetpack::state( 'error', false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2916
		}
2917
2918
		Jetpack::catch_errors( false );
2919
		/**
2920
		 * Fires when default modules are activated.
2921
		 *
2922
		 * @since 1.9.0
2923
		 *
2924
		 * @param string $min_version Minimum version number required to use modules.
2925
		 * @param string $max_version Maximum version number required to use modules.
2926
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2927
		 */
2928
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2929
	}
2930
2931
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2932
		/**
2933
		 * Fires before a module is activated.
2934
		 *
2935
		 * @since 2.6.0
2936
		 *
2937
		 * @param string $module Module slug.
2938
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2939
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2940
		 */
2941
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2942
2943
		$jetpack = Jetpack::init();
2944
2945
		if ( ! strlen( $module ) )
2946
			return false;
2947
2948
		if ( ! Jetpack::is_module( $module ) )
2949
			return false;
2950
2951
		// If it's already active, then don't do it again
2952
		$active = Jetpack::get_active_modules();
2953
		foreach ( $active as $act ) {
2954
			if ( $act == $module )
2955
				return true;
2956
		}
2957
2958
		$module_data = Jetpack::get_module( $module );
2959
2960
		if ( ! Jetpack::is_active() ) {
2961
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2962
				return false;
2963
2964
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2965
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2966
				return false;
2967
		}
2968
2969
		// Check and see if the old plugin is active
2970
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2971
			// Deactivate the old plugin
2972
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2973
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2974
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2975
				Jetpack::state( 'deactivated_plugins', $module );
2976
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2977
				exit;
2978
			}
2979
		}
2980
2981
		// Protect won't work with mis-configured IPs
2982
		if ( 'protect' === $module ) {
2983
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2984
			if ( ! jetpack_protect_get_ip() ) {
2985
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2986
				return false;
2987
			}
2988
		}
2989
2990
		if ( ! Jetpack_Plan::supports( $module ) ) {
2991
			return false;
2992
		}
2993
2994
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2995
		Jetpack::state( 'module', $module );
2996
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2997
2998
		Jetpack::catch_errors( true );
2999
		ob_start();
3000
		require Jetpack::get_module_path( $module );
3001
		/** This action is documented in class.jetpack.php */
3002
		do_action( 'jetpack_activate_module', $module );
3003
		$active[] = $module;
3004
		Jetpack::update_active_modules( $active );
3005
3006
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3007
		ob_end_clean();
3008
		Jetpack::catch_errors( false );
3009
3010
		if ( $redirect ) {
3011
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3012
		}
3013
		if ( $exit ) {
3014
			exit;
3015
		}
3016
		return true;
3017
	}
3018
3019
	function activate_module_actions( $module ) {
3020
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3021
	}
3022
3023
	public static function deactivate_module( $module ) {
3024
		/**
3025
		 * Fires when a module is deactivated.
3026
		 *
3027
		 * @since 1.9.0
3028
		 *
3029
		 * @param string $module Module slug.
3030
		 */
3031
		do_action( 'jetpack_pre_deactivate_module', $module );
3032
3033
		$jetpack = Jetpack::init();
0 ignored issues
show
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3034
3035
		$active = Jetpack::get_active_modules();
3036
		$new    = array_filter( array_diff( $active, (array) $module ) );
3037
3038
		return self::update_active_modules( $new );
3039
	}
3040
3041
	public static function enable_module_configurable( $module ) {
3042
		$module = Jetpack::get_module_slug( $module );
3043
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3044
	}
3045
3046
	/**
3047
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3048
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3049
	 *
3050
	 * @param string $module Module slug
3051
	 * @return string $url module configuration URL
3052
	 */
3053
	public static function module_configuration_url( $module ) {
3054
		$module = Jetpack::get_module_slug( $module );
3055
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3056
		/**
3057
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3058
		 *
3059
		 * @since 6.9.0
3060
		 *
3061
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3062
		 */
3063
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3064
3065
		return $url;
3066
	}
3067
3068
/* Installation */
3069
	public static function bail_on_activation( $message, $deactivate = true ) {
3070
?>
3071
<!doctype html>
3072
<html>
3073
<head>
3074
<meta charset="<?php bloginfo( 'charset' ); ?>">
3075
<style>
3076
* {
3077
	text-align: center;
3078
	margin: 0;
3079
	padding: 0;
3080
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3081
}
3082
p {
3083
	margin-top: 1em;
3084
	font-size: 18px;
3085
}
3086
</style>
3087
<body>
3088
<p><?php echo esc_html( $message ); ?></p>
3089
</body>
3090
</html>
3091
<?php
3092
		if ( $deactivate ) {
3093
			$plugins = get_option( 'active_plugins' );
3094
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3095
			$update  = false;
3096
			foreach ( $plugins as $i => $plugin ) {
3097
				if ( $plugin === $jetpack ) {
3098
					$plugins[$i] = false;
3099
					$update = true;
3100
				}
3101
			}
3102
3103
			if ( $update ) {
3104
				update_option( 'active_plugins', array_filter( $plugins ) );
3105
			}
3106
		}
3107
		exit;
3108
	}
3109
3110
	/**
3111
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3112
	 * @static
3113
	 */
3114
	public static function plugin_activation( $network_wide ) {
3115
		Jetpack_Options::update_option( 'activated', 1 );
3116
3117
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3118
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3119
		}
3120
3121
		if ( $network_wide )
3122
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3123
3124
		// For firing one-off events (notices) immediately after activation
3125
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3126
3127
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3128
3129
		Jetpack::plugin_initialize();
3130
	}
3131
3132
	public static function get_activation_source( $referer_url ) {
3133
3134
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3135
			return array( 'wp-cli', null );
3136
		}
3137
3138
		$referer = parse_url( $referer_url );
3139
3140
		$source_type = 'unknown';
3141
		$source_query = null;
3142
3143
		if ( ! is_array( $referer ) ) {
3144
			return array( $source_type, $source_query );
3145
		}
3146
3147
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3148
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3149
3150
		if ( isset( $referer['query'] ) ) {
3151
			parse_str( $referer['query'], $query_parts );
3152
		} else {
3153
			$query_parts = array();
3154
		}
3155
3156
		if ( $plugins_path === $referer['path'] ) {
3157
			$source_type = 'list';
3158
		} elseif ( $plugins_install_path === $referer['path'] ) {
3159
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3160
			switch( $tab ) {
3161
				case 'popular':
3162
					$source_type = 'popular';
3163
					break;
3164
				case 'recommended':
3165
					$source_type = 'recommended';
3166
					break;
3167
				case 'favorites':
3168
					$source_type = 'favorites';
3169
					break;
3170
				case 'search':
3171
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3172
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3173
					break;
3174
				default:
3175
					$source_type = 'featured';
3176
			}
3177
		}
3178
3179
		return array( $source_type, $source_query );
3180
	}
3181
3182
	/**
3183
	 * Runs before bumping version numbers up to a new version
3184
	 * @param  string $version    Version:timestamp
3185
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3186
	 * @return null              [description]
3187
	 */
3188
	public static function do_version_bump( $version, $old_version ) {
3189
		if ( ! $old_version ) { // For new sites
3190
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3191
		}
3192
	}
3193
3194
	/**
3195
	 * Sets the internal version number and activation state.
3196
	 * @static
3197
	 */
3198
	public static function plugin_initialize() {
3199
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3200
			Jetpack_Options::update_option( 'activated', 2 );
3201
		}
3202
3203 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3204
			$version = $old_version = JETPACK__VERSION . ':' . time();
3205
			/** This action is documented in class.jetpack.php */
3206
			do_action( 'updating_jetpack_version', $version, false );
3207
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3208
		}
3209
3210
		Jetpack::load_modules();
3211
3212
		Jetpack_Options::delete_option( 'do_activate' );
3213
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3214
	}
3215
3216
	/**
3217
	 * Removes all connection options
3218
	 * @static
3219
	 */
3220
	public static function plugin_deactivation( ) {
3221
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3222
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3223
			Jetpack_Network::init()->deactivate();
3224
		} else {
3225
			Jetpack::disconnect( false );
3226
			//Jetpack_Heartbeat::init()->deactivate();
3227
		}
3228
	}
3229
3230
	/**
3231
	 * Disconnects from the Jetpack servers.
3232
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3233
	 * @static
3234
	 */
3235
	public static function disconnect( $update_activated_state = true ) {
3236
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3237
		Jetpack::clean_nonces( true );
3238
3239
		// If the site is in an IDC because sync is not allowed,
3240
		// let's make sure to not disconnect the production site.
3241
		if ( ! self::validate_sync_error_idc_option() ) {
3242
			$tracking = new Tracking();
3243
			$tracking->record_user_event( 'disconnect_site', array() );
3244
			Jetpack::load_xml_rpc_client();
3245
			$xml = new Jetpack_IXR_Client();
3246
			$xml->query( 'jetpack.deregister' );
3247
		}
3248
3249
		Jetpack_Options::delete_option(
3250
			array(
3251
				'blog_token',
3252
				'user_token',
3253
				'user_tokens',
3254
				'master_user',
3255
				'time_diff',
3256
				'fallback_no_verify_ssl_certs',
3257
			)
3258
		);
3259
3260
		Jetpack_IDC::clear_all_idc_options();
3261
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3262
3263
		if ( $update_activated_state ) {
3264
			Jetpack_Options::update_option( 'activated', 4 );
3265
		}
3266
3267
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3268
			// Check then record unique disconnection if site has never been disconnected previously
3269
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3270
				$jetpack_unique_connection['disconnected'] = 1;
3271
			} else {
3272
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3273
					//track unique disconnect
3274
					$jetpack = Jetpack::init();
3275
3276
					$jetpack->stat( 'connections', 'unique-disconnect' );
3277
					$jetpack->do_stats( 'server_side' );
3278
				}
3279
				// increment number of times disconnected
3280
				$jetpack_unique_connection['disconnected'] += 1;
3281
			}
3282
3283
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3284
		}
3285
3286
		// Delete cached connected user data
3287
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3288
		delete_transient( $transient_key );
3289
3290
		// Delete all the sync related data. Since it could be taking up space.
3291
		Sender::get_instance()->uninstall();
3292
3293
		// Disable the Heartbeat cron
3294
		Jetpack_Heartbeat::init()->deactivate();
3295
	}
3296
3297
	/**
3298
	 * Unlinks the current user from the linked WordPress.com user
3299
	 */
3300
	public static function unlink_user( $user_id = null ) {
3301
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3302
			return false;
3303
3304
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3305
3306
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3307
			return false;
3308
3309
		if ( ! isset( $tokens[ $user_id ] ) )
3310
			return false;
3311
3312
		Jetpack::load_xml_rpc_client();
3313
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3314
		$xml->query( 'jetpack.unlink_user', $user_id );
3315
3316
		unset( $tokens[ $user_id ] );
3317
3318
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3319
3320
		/**
3321
		 * Fires after the current user has been unlinked from WordPress.com.
3322
		 *
3323
		 * @since 4.1.0
3324
		 *
3325
		 * @param int $user_id The current user's ID.
3326
		 */
3327
		do_action( 'jetpack_unlinked_user', $user_id );
3328
3329
		return true;
3330
	}
3331
3332
	/**
3333
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3334
	 */
3335
	public static function try_registration() {
3336
		// The user has agreed to the TOS at some point by now.
3337
		Jetpack_Options::update_option( 'tos_agreed', true );
3338
3339
		// Let's get some testing in beta versions and such.
3340
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3341
			// Before attempting to connect, let's make sure that the domains are viable.
3342
			$domains_to_check = array_unique( array(
3343
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3344
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3345
			) );
3346
			foreach ( $domains_to_check as $domain ) {
3347
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3346 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...
3348
				if ( is_wp_error( $result ) ) {
3349
					return $result;
3350
				}
3351
			}
3352
		}
3353
3354
		$result = Jetpack::register();
3355
3356
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3357
		if ( ! $result || is_wp_error( $result ) ) {
3358
			return $result;
3359
		} else {
3360
			return true;
3361
		}
3362
	}
3363
3364
	/**
3365
	 * Tracking an internal event log. Try not to put too much chaff in here.
3366
	 *
3367
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3368
	 */
3369
	public static function log( $code, $data = null ) {
3370
		// only grab the latest 200 entries
3371
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3372
3373
		// Append our event to the log
3374
		$log_entry = array(
3375
			'time'    => time(),
3376
			'user_id' => get_current_user_id(),
3377
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3378
			'code'    => $code,
3379
		);
3380
		// Don't bother storing it unless we've got some.
3381
		if ( ! is_null( $data ) ) {
3382
			$log_entry['data'] = $data;
3383
		}
3384
		$log[] = $log_entry;
3385
3386
		// Try add_option first, to make sure it's not autoloaded.
3387
		// @todo: Add an add_option method to Jetpack_Options
3388
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3389
			Jetpack_Options::update_option( 'log', $log );
3390
		}
3391
3392
		/**
3393
		 * Fires when Jetpack logs an internal event.
3394
		 *
3395
		 * @since 3.0.0
3396
		 *
3397
		 * @param array $log_entry {
3398
		 *	Array of details about the log entry.
3399
		 *
3400
		 *	@param string time Time of the event.
3401
		 *	@param int user_id ID of the user who trigerred the event.
3402
		 *	@param int blog_id Jetpack Blog ID.
3403
		 *	@param string code Unique name for the event.
3404
		 *	@param string data Data about the event.
3405
		 * }
3406
		 */
3407
		do_action( 'jetpack_log_entry', $log_entry );
3408
	}
3409
3410
	/**
3411
	 * Get the internal event log.
3412
	 *
3413
	 * @param $event (string) - only return the specific log events
3414
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3415
	 *
3416
	 * @return array of log events || WP_Error for invalid params
3417
	 */
3418
	public static function get_log( $event = false, $num = false ) {
3419
		if ( $event && ! is_string( $event ) ) {
3420
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

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

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

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

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

Loading history...
3425
		}
3426
3427
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3428
3429
		// If nothing set - act as it did before, otherwise let's start customizing the output
3430
		if ( ! $num && ! $event ) {
3431
			return $entire_log;
3432
		} else {
3433
			$entire_log = array_reverse( $entire_log );
3434
		}
3435
3436
		$custom_log_output = array();
3437
3438
		if ( $event ) {
3439
			foreach ( $entire_log as $log_event ) {
3440
				if ( $event == $log_event[ 'code' ] ) {
3441
					$custom_log_output[] = $log_event;
3442
				}
3443
			}
3444
		} else {
3445
			$custom_log_output = $entire_log;
3446
		}
3447
3448
		if ( $num ) {
3449
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3450
		}
3451
3452
		return $custom_log_output;
3453
	}
3454
3455
	/**
3456
	 * Log modification of important settings.
3457
	 */
3458
	public static function log_settings_change( $option, $old_value, $value ) {
3459
		switch( $option ) {
3460
			case 'jetpack_sync_non_public_post_stati':
3461
				self::log( $option, $value );
3462
				break;
3463
		}
3464
	}
3465
3466
	/**
3467
	 * Return stat data for WPCOM sync
3468
	 */
3469
	public static function get_stat_data( $encode = true, $extended = true ) {
3470
		$data = Jetpack_Heartbeat::generate_stats_array();
3471
3472
		if ( $extended ) {
3473
			$additional_data = self::get_additional_stat_data();
3474
			$data = array_merge( $data, $additional_data );
3475
		}
3476
3477
		if ( $encode ) {
3478
			return json_encode( $data );
3479
		}
3480
3481
		return $data;
3482
	}
3483
3484
	/**
3485
	 * Get additional stat data to sync to WPCOM
3486
	 */
3487
	public static function get_additional_stat_data( $prefix = '' ) {
3488
		$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...
3489
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3490
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3491
		$return["{$prefix}site-count"]     = 0;
3492
3493
		if ( function_exists( 'get_blog_count' ) ) {
3494
			$return["{$prefix}site-count"] = get_blog_count();
3495
		}
3496
		return $return;
3497
	}
3498
3499
	private static function get_site_user_count() {
3500
		global $wpdb;
3501
3502
		if ( function_exists( 'wp_is_large_network' ) ) {
3503
			if ( wp_is_large_network( 'users' ) ) {
3504
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3505
			}
3506
		}
3507 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3508
			// It wasn't there, so regenerate the data and save the transient
3509
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3510
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3511
		}
3512
		return $user_count;
3513
	}
3514
3515
	/* Admin Pages */
3516
3517
	function admin_init() {
3518
		// If the plugin is not connected, display a connect message.
3519
		if (
3520
			// the plugin was auto-activated and needs its candy
3521
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3522
		||
3523
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3524
			! Jetpack_Options::get_option( 'activated' )
3525
		) {
3526
			Jetpack::plugin_initialize();
3527
		}
3528
3529
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3530
			Jetpack_Connection_Banner::init();
3531
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3532
			// Upgrade: 1.1 -> 1.1.1
3533
			// Check and see if host can verify the Jetpack servers' SSL certificate
3534
			$args = array();
3535
			Client::_wp_remote_request(
3536
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3537
				$args,
3538
				true
3539
			);
3540
		}
3541
3542
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3543
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3544
		}
3545
3546
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3547
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3548
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3549
3550
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3551
			// Artificially throw errors in certain whitelisted cases during plugin activation
3552
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3553
		}
3554
3555
		// Add custom column in wp-admin/users.php to show whether user is linked.
3556
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3557
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3558
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3559
	}
3560
3561
	function admin_body_class( $admin_body_class = '' ) {
3562
		$classes = explode( ' ', trim( $admin_body_class ) );
3563
3564
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3565
3566
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3567
		return " $admin_body_class ";
3568
	}
3569
3570
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3571
		return $admin_body_class . ' jetpack-pagestyles ';
3572
	}
3573
3574
	/**
3575
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3576
	 * This function artificially throws errors for such cases (whitelisted).
3577
	 *
3578
	 * @param string $plugin The activated plugin.
3579
	 */
3580
	function throw_error_on_activate_plugin( $plugin ) {
3581
		$active_modules = Jetpack::get_active_modules();
3582
3583
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3584
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3585
			$throw = false;
3586
3587
			// Try and make sure it really was the stats plugin
3588
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3589
				if ( 'stats.php' == basename( $plugin ) ) {
3590
					$throw = true;
3591
				}
3592
			} else {
3593
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3594
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3595
					$throw = true;
3596
				}
3597
			}
3598
3599
			if ( $throw ) {
3600
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3601
			}
3602
		}
3603
	}
3604
3605
	function intercept_plugin_error_scrape_init() {
3606
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3607
	}
3608
3609
	function intercept_plugin_error_scrape( $action, $result ) {
3610
		if ( ! $result ) {
3611
			return;
3612
		}
3613
3614
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3615
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3616
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3617
			}
3618
		}
3619
	}
3620
3621
	function add_remote_request_handlers() {
3622
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3623
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3624
	}
3625
3626
	function remote_request_handlers() {
3627
		$action = current_filter();
0 ignored issues
show
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3628
3629
		switch ( current_filter() ) {
3630
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3631
			$response = $this->upload_handler();
3632
			break;
3633
3634
		case 'wp_ajax_nopriv_jetpack_update_file' :
3635
			$response = $this->upload_handler( true );
3636
			break;
3637
		default :
3638
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
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...
3639
			break;
3640
		}
3641
3642
		if ( ! $response ) {
3643
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
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...
3644
		}
3645
3646
		if ( is_wp_error( $response ) ) {
3647
			$status_code       = $response->get_error_data();
0 ignored issues
show
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...
3648
			$error             = $response->get_error_code();
0 ignored issues
show
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...
3649
			$error_description = $response->get_error_message();
0 ignored issues
show
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...
3650
3651
			if ( ! is_int( $status_code ) ) {
3652
				$status_code = 400;
3653
			}
3654
3655
			status_header( $status_code );
3656
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3657
		}
3658
3659
		status_header( 200 );
3660
		if ( true === $response ) {
3661
			exit;
3662
		}
3663
3664
		die( json_encode( (object) $response ) );
3665
	}
3666
3667
	/**
3668
	 * Uploads a file gotten from the global $_FILES.
3669
	 * If `$update_media_item` is true and `post_id` is defined
3670
	 * the attachment file of the media item (gotten through of the post_id)
3671
	 * will be updated instead of add a new one.
3672
	 *
3673
	 * @param  boolean $update_media_item - update media attachment
3674
	 * @return array - An array describing the uploadind files process
3675
	 */
3676
	function upload_handler( $update_media_item = false ) {
3677
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3678
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
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...
3679
		}
3680
3681
		$user = wp_authenticate( '', '' );
3682
		if ( ! $user || is_wp_error( $user ) ) {
3683
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
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...
3684
		}
3685
3686
		wp_set_current_user( $user->ID );
3687
3688
		if ( ! current_user_can( 'upload_files' ) ) {
3689
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
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...
3690
		}
3691
3692
		if ( empty( $_FILES ) ) {
3693
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
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...
3694
		}
3695
3696
		foreach ( array_keys( $_FILES ) as $files_key ) {
3697
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3698
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
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...
3699
			}
3700
		}
3701
3702
		$media_keys = array_keys( $_FILES['media'] );
3703
3704
		$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...
3705
		if ( ! $token || is_wp_error( $token ) ) {
3706
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
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...
3707
		}
3708
3709
		$uploaded_files = array();
3710
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3711
		unset( $GLOBALS['post'] );
3712
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3713
			$file = array();
3714
			foreach ( $media_keys as $media_key ) {
3715
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3716
			}
3717
3718
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3719
3720
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3721
			if ( $hmac_provided !== $hmac_file ) {
3722
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3723
				continue;
3724
			}
3725
3726
			$_FILES['.jetpack.upload.'] = $file;
3727
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3728
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3729
				$post_id = 0;
3730
			}
3731
3732
			if ( $update_media_item ) {
3733
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3734
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
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...
3735
				}
3736
3737
				$media_array = $_FILES['media'];
3738
3739
				$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...
3740
				$file_array['type'] = $media_array['type'][0];
3741
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3742
				$file_array['error'] = $media_array['error'][0];
3743
				$file_array['size'] = $media_array['size'][0];
3744
3745
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3746
3747
				if ( is_wp_error( $edited_media_item ) ) {
3748
					return $edited_media_item;
3749
				}
3750
3751
				$response = (object) array(
3752
					'id'   => (string) $post_id,
3753
					'file' => (string) $edited_media_item->post_title,
3754
					'url'  => (string) wp_get_attachment_url( $post_id ),
3755
					'type' => (string) $edited_media_item->post_mime_type,
3756
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3757
				);
3758
3759
				return (array) array( $response );
3760
			}
3761
3762
			$attachment_id = media_handle_upload(
3763
				'.jetpack.upload.',
3764
				$post_id,
3765
				array(),
3766
				array(
3767
					'action' => 'jetpack_upload_file',
3768
				)
3769
			);
3770
3771
			if ( ! $attachment_id ) {
3772
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3773
			} elseif ( is_wp_error( $attachment_id ) ) {
3774
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3775
			} else {
3776
				$attachment = get_post( $attachment_id );
3777
				$uploaded_files[$index] = (object) array(
3778
					'id'   => (string) $attachment_id,
3779
					'file' => $attachment->post_title,
3780
					'url'  => wp_get_attachment_url( $attachment_id ),
3781
					'type' => $attachment->post_mime_type,
3782
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3783
				);
3784
				// Zip files uploads are not supported unless they are done for installation purposed
3785
				// lets delete them in case something goes wrong in this whole process
3786
				if ( 'application/zip' === $attachment->post_mime_type ) {
3787
					// Schedule a cleanup for 2 hours from now in case of failed install.
3788
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3789
				}
3790
			}
3791
		}
3792
		if ( ! is_null( $global_post ) ) {
3793
			$GLOBALS['post'] = $global_post;
3794
		}
3795
3796
		return $uploaded_files;
3797
	}
3798
3799
	/**
3800
	 * Add help to the Jetpack page
3801
	 *
3802
	 * @since Jetpack (1.2.3)
3803
	 * @return false if not the Jetpack page
3804
	 */
3805
	function admin_help() {
3806
		$current_screen = get_current_screen();
3807
3808
		// Overview
3809
		$current_screen->add_help_tab(
3810
			array(
3811
				'id'		=> 'home',
3812
				'title'		=> __( 'Home', 'jetpack' ),
3813
				'content'	=>
3814
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3815
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3816
					'<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>',
3817
			)
3818
		);
3819
3820
		// Screen Content
3821
		if ( current_user_can( 'manage_options' ) ) {
3822
			$current_screen->add_help_tab(
3823
				array(
3824
					'id'		=> 'settings',
3825
					'title'		=> __( 'Settings', 'jetpack' ),
3826
					'content'	=>
3827
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3828
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3829
						'<ol>' .
3830
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3831
							'<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>' .
3832
						'</ol>' .
3833
						'<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>'
3834
				)
3835
			);
3836
		}
3837
3838
		// Help Sidebar
3839
		$current_screen->set_help_sidebar(
3840
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3841
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3842
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3843
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3844
		);
3845
	}
3846
3847
	function admin_menu_css() {
3848
		wp_enqueue_style( 'jetpack-icons' );
3849
	}
3850
3851
	function admin_menu_order() {
3852
		return true;
3853
	}
3854
3855 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3856
		$jp_menu_order = array();
3857
3858
		foreach ( $menu_order as $index => $item ) {
3859
			if ( $item != 'jetpack' ) {
3860
				$jp_menu_order[] = $item;
3861
			}
3862
3863
			if ( $index == 0 ) {
3864
				$jp_menu_order[] = 'jetpack';
3865
			}
3866
		}
3867
3868
		return $jp_menu_order;
3869
	}
3870
3871
	function admin_banner_styles() {
3872
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3873
3874
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3875
			wp_register_style(
3876
				'jetpack-dops-style',
3877
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3878
				array(),
3879
				JETPACK__VERSION
3880
			);
3881
		}
3882
3883
		wp_enqueue_style(
3884
			'jetpack',
3885
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3886
			array( 'jetpack-dops-style' ),
3887
			 JETPACK__VERSION . '-20121016'
3888
		);
3889
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3890
		wp_style_add_data( 'jetpack', 'suffix', $min );
3891
	}
3892
3893
	function plugin_action_links( $actions ) {
3894
3895
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3896
3897
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3898
			return array_merge(
3899
				$jetpack_home,
3900
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3901
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3902
				$actions
3903
				);
3904
			}
3905
3906
		return array_merge( $jetpack_home, $actions );
3907
	}
3908
3909
	/*
3910
	 * Registration flow:
3911
	 * 1 - ::admin_page_load() action=register
3912
	 * 2 - ::try_registration()
3913
	 * 3 - ::register()
3914
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3915
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3916
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3917
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3918
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3919
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3920
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3921
	 *       jetpack_id, jetpack_secret, jetpack_public
3922
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3923
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3924
	 * 5 - user logs in with WP.com account
3925
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3926
	 *		- Jetpack_Client_Server::authorize()
3927
	 *		- Jetpack_Client_Server::get_token()
3928
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3929
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3930
	 *			- which responds with access_token, token_type, scope
3931
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3932
	 *		- Jetpack::activate_default_modules()
3933
	 *     		- Deactivates deprecated plugins
3934
	 *     		- Activates all default modules
3935
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3936
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3937
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3938
	 *     Done!
3939
	 */
3940
3941
	/**
3942
	 * Handles the page load events for the Jetpack admin page
3943
	 */
3944
	function admin_page_load() {
3945
		$error = false;
3946
3947
		// Make sure we have the right body class to hook stylings for subpages off of.
3948
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3949
3950
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3951
			// Should only be used in intermediate redirects to preserve state across redirects
3952
			Jetpack::restate();
3953
		}
3954
3955
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3956
			// @todo: Add validation against a known whitelist
3957
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3958
			// User clicked in the iframe to link their accounts
3959
			if ( ! Jetpack::is_user_connected() ) {
3960
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3961
3962
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3963
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3964
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3965
3966
				if ( isset( $_GET['notes_iframe'] ) )
3967
					$connect_url .= '&notes_iframe';
3968
				wp_redirect( $connect_url );
3969
				exit;
3970
			} else {
3971
				if ( ! isset( $_GET['calypso_env'] ) ) {
3972
					Jetpack::state( 'message', 'already_authorized' );
3973
					wp_safe_redirect( Jetpack::admin_url() );
3974
					exit;
3975
				} else {
3976
					$connect_url = $this->build_connect_url( true, false, $from );
3977
					$connect_url .= '&already_authorized=true';
3978
					wp_redirect( $connect_url );
3979
					exit;
3980
				}
3981
			}
3982
		}
3983
3984
3985
		if ( isset( $_GET['action'] ) ) {
3986
			switch ( $_GET['action'] ) {
3987
			case 'authorize':
3988
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3989
					Jetpack::state( 'message', 'already_authorized' );
3990
					wp_safe_redirect( Jetpack::admin_url() );
3991
					exit;
3992
				}
3993
				Jetpack::log( 'authorize' );
3994
				$client_server = new Jetpack_Client_Server;
3995
				$client_server->client_authorize();
3996
				exit;
3997
			case 'register' :
3998
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3999
					$error = 'cheatin';
4000
					break;
4001
				}
4002
				check_admin_referer( 'jetpack-register' );
4003
				Jetpack::log( 'register' );
4004
				Jetpack::maybe_set_version_option();
4005
				$registered = Jetpack::try_registration();
4006
				if ( is_wp_error( $registered ) ) {
4007
					$error = $registered->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

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

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

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

Loading history...
4010
4011
					/**
4012
					 * Jetpack registration Error.
4013
					 *
4014
					 * @since 7.5.0
4015
					 *
4016
					 * @param string|int $error The error code.
4017
					 * @param \WP_Error $registered The error object.
4018
					 */
4019
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4020
					break;
4021
				}
4022
4023
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4024
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4025
4026
				/**
4027
				 * Jetpack registration Success.
4028
				 *
4029
				 * @since 7.5.0
4030
				 *
4031
				 * @param string $from 'from' GET parameter;
4032
				 */
4033
				do_action( 'jetpack_connection_register_success', $from );
4034
4035
				$url = $this->build_connect_url( true, $redirect, $from );
4036
4037
				if ( ! empty( $_GET['onboarding'] ) ) {
4038
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4039
				}
4040
4041
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4042
					$url = add_query_arg( 'auth_approved', 'true', $url );
4043
				}
4044
4045
				wp_redirect( $url );
4046
				exit;
4047
			case 'activate' :
4048
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4049
					$error = 'cheatin';
4050
					break;
4051
				}
4052
4053
				$module = stripslashes( $_GET['module'] );
4054
				check_admin_referer( "jetpack_activate-$module" );
4055
				Jetpack::log( 'activate', $module );
4056
				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...
4057
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4058
				}
4059
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4060
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4061
				exit;
4062
			case 'activate_default_modules' :
4063
				check_admin_referer( 'activate_default_modules' );
4064
				Jetpack::log( 'activate_default_modules' );
4065
				Jetpack::restate();
4066
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4067
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4068
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4069
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4070
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4071
				exit;
4072
			case 'disconnect' :
4073
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4074
					$error = 'cheatin';
4075
					break;
4076
				}
4077
4078
				check_admin_referer( 'jetpack-disconnect' );
4079
				Jetpack::log( 'disconnect' );
4080
				Jetpack::disconnect();
4081
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4082
				exit;
4083
			case 'reconnect' :
4084
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4085
					$error = 'cheatin';
4086
					break;
4087
				}
4088
4089
				check_admin_referer( 'jetpack-reconnect' );
4090
				Jetpack::log( 'reconnect' );
4091
				$this->disconnect();
4092
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4093
				exit;
4094 View Code Duplication
			case 'deactivate' :
4095
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4096
					$error = 'cheatin';
4097
					break;
4098
				}
4099
4100
				$modules = stripslashes( $_GET['module'] );
4101
				check_admin_referer( "jetpack_deactivate-$modules" );
4102
				foreach ( explode( ',', $modules ) as $module ) {
4103
					Jetpack::log( 'deactivate', $module );
4104
					Jetpack::deactivate_module( $module );
4105
					Jetpack::state( 'message', 'module_deactivated' );
4106
				}
4107
				Jetpack::state( 'module', $modules );
4108
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4109
				exit;
4110
			case 'unlink' :
4111
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4112
				check_admin_referer( 'jetpack-unlink' );
4113
				Jetpack::log( 'unlink' );
4114
				$this->unlink_user();
4115
				Jetpack::state( 'message', 'unlinked' );
4116
				if ( 'sub-unlink' == $redirect ) {
4117
					wp_safe_redirect( admin_url() );
4118
				} else {
4119
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4120
				}
4121
				exit;
4122
			case 'onboard' :
4123
				if ( ! current_user_can( 'manage_options' ) ) {
4124
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4125
				} else {
4126
					Jetpack::create_onboarding_token();
4127
					$url = $this->build_connect_url( true );
4128
4129
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4130
						$url = add_query_arg( 'onboarding', $token, $url );
4131
					}
4132
4133
					$calypso_env = $this->get_calypso_env();
4134
					if ( ! empty( $calypso_env ) ) {
4135
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4136
					}
4137
4138
					wp_redirect( $url );
4139
					exit;
4140
				}
4141
				exit;
4142
			default:
4143
				/**
4144
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4145
				 *
4146
				 * @since 2.6.0
4147
				 *
4148
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4149
				 */
4150
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4151
			}
4152
		}
4153
4154
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4155
			self::activate_new_modules( true );
4156
		}
4157
4158
		$message_code = Jetpack::state( 'message' );
4159
		if ( Jetpack::state( 'optin-manage' ) ) {
4160
			$activated_manage = $message_code;
4161
			$message_code = 'jetpack-manage';
4162
		}
4163
4164
		switch ( $message_code ) {
4165
		case 'jetpack-manage':
4166
			$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>';
4167
			if ( $activated_manage ) {
0 ignored issues
show
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4168
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4169
			}
4170
			break;
4171
4172
		}
4173
4174
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4175
4176
		if ( ! empty( $deactivated_plugins ) ) {
4177
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4178
			$deactivated_titles  = array();
4179
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4180
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4181
					continue;
4182
				}
4183
4184
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4185
			}
4186
4187
			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...
4188
				if ( $this->message ) {
4189
					$this->message .= "<br /><br />\n";
4190
				}
4191
4192
				$this->message .= wp_sprintf(
4193
					_n(
4194
						'Jetpack contains the most recent version of the old %l plugin.',
4195
						'Jetpack contains the most recent versions of the old %l plugins.',
4196
						count( $deactivated_titles ),
4197
						'jetpack'
4198
					),
4199
					$deactivated_titles
4200
				);
4201
4202
				$this->message .= "<br />\n";
4203
4204
				$this->message .= _n(
4205
					'The old version has been deactivated and can be removed from your site.',
4206
					'The old versions have been deactivated and can be removed from your site.',
4207
					count( $deactivated_titles ),
4208
					'jetpack'
4209
				);
4210
			}
4211
		}
4212
4213
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4214
4215
		if ( $this->message || $this->error || $this->privacy_checks ) {
4216
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4217
		}
4218
4219
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4220
	}
4221
4222
	function admin_notices() {
4223
4224
		if ( $this->error ) {
4225
?>
4226
<div id="message" class="jetpack-message jetpack-err">
4227
	<div class="squeezer">
4228
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4229
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4230
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4231
<?php	endif; ?>
4232
	</div>
4233
</div>
4234
<?php
4235
		}
4236
4237
		if ( $this->message ) {
4238
?>
4239
<div id="message" class="jetpack-message">
4240
	<div class="squeezer">
4241
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4242
	</div>
4243
</div>
4244
<?php
4245
		}
4246
4247
		if ( $this->privacy_checks ) :
4248
			$module_names = $module_slugs = array();
4249
4250
			$privacy_checks = explode( ',', $this->privacy_checks );
4251
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4252
			foreach ( $privacy_checks as $module_slug ) {
4253
				$module = Jetpack::get_module( $module_slug );
4254
				if ( ! $module ) {
4255
					continue;
4256
				}
4257
4258
				$module_slugs[] = $module_slug;
4259
				$module_names[] = "<strong>{$module['name']}</strong>";
4260
			}
4261
4262
			$module_slugs = join( ',', $module_slugs );
4263
?>
4264
<div id="message" class="jetpack-message jetpack-err">
4265
	<div class="squeezer">
4266
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4267
		<p><?php
4268
			echo wp_kses(
4269
				wptexturize(
4270
					wp_sprintf(
4271
						_nx(
4272
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4273
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4274
							count( $privacy_checks ),
4275
							'%l = list of Jetpack module/feature names',
4276
							'jetpack'
4277
						),
4278
						$module_names
4279
					)
4280
				),
4281
				array( 'strong' => true )
4282
			);
4283
4284
			echo "\n<br />\n";
4285
4286
			echo wp_kses(
4287
				sprintf(
4288
					_nx(
4289
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4290
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4291
						count( $privacy_checks ),
4292
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4293
						'jetpack'
4294
					),
4295
					wp_nonce_url(
4296
						Jetpack::admin_url(
4297
							array(
4298
								'page'   => 'jetpack',
4299
								'action' => 'deactivate',
4300
								'module' => urlencode( $module_slugs ),
4301
							)
4302
						),
4303
						"jetpack_deactivate-$module_slugs"
4304
					),
4305
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4306
				),
4307
				array( 'a' => array( 'href' => true, 'title' => true ) )
4308
			);
4309
		?></p>
4310
	</div>
4311
</div>
4312
<?php endif;
4313
	}
4314
4315
	/**
4316
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4317
	 */
4318
	function stat( $group, $detail ) {
4319
		if ( ! isset( $this->stats[ $group ] ) )
4320
			$this->stats[ $group ] = array();
4321
		$this->stats[ $group ][] = $detail;
4322
	}
4323
4324
	/**
4325
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4326
	 */
4327
	function do_stats( $method = '' ) {
4328
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4329
			foreach ( $this->stats as $group => $stats ) {
4330
				if ( is_array( $stats ) && count( $stats ) ) {
4331
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4332
					if ( 'server_side' === $method ) {
4333
						self::do_server_side_stat( $args );
4334
					} else {
4335
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4336
					}
4337
				}
4338
				unset( $this->stats[ $group ] );
4339
			}
4340
		}
4341
	}
4342
4343
	/**
4344
	 * Runs stats code for a one-off, server-side.
4345
	 *
4346
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4347
	 *
4348
	 * @return bool If it worked.
4349
	 */
4350
	static function do_server_side_stat( $args ) {
4351
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4352
		if ( is_wp_error( $response ) )
4353
			return false;
4354
4355
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4356
			return false;
4357
4358
		return true;
4359
	}
4360
4361
	/**
4362
	 * Builds the stats url.
4363
	 *
4364
	 * @param $args array|string The arguments to append to the URL.
4365
	 *
4366
	 * @return string The URL to be pinged.
4367
	 */
4368
	static function build_stats_url( $args ) {
4369
		$defaults = array(
4370
			'v'    => 'wpcom2',
4371
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4372
		);
4373
		$args     = wp_parse_args( $args, $defaults );
4374
		/**
4375
		 * Filter the URL used as the Stats tracking pixel.
4376
		 *
4377
		 * @since 2.3.2
4378
		 *
4379
		 * @param string $url Base URL used as the Stats tracking pixel.
4380
		 */
4381
		$base_url = apply_filters(
4382
			'jetpack_stats_base_url',
4383
			'https://pixel.wp.com/g.gif'
4384
		);
4385
		$url      = add_query_arg( $args, $base_url );
4386
		return $url;
4387
	}
4388
4389
	static function translate_current_user_to_role() {
4390
		foreach ( self::$capability_translations as $role => $cap ) {
4391
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4392
				return $role;
4393
			}
4394
		}
4395
4396
		return false;
4397
	}
4398
4399
	static function translate_user_to_role( $user ) {
4400
		foreach ( self::$capability_translations as $role => $cap ) {
4401
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4402
				return $role;
4403
			}
4404
		}
4405
4406
		return false;
4407
    }
4408
4409
	static function translate_role_to_cap( $role ) {
4410
		if ( ! isset( self::$capability_translations[$role] ) ) {
4411
			return false;
4412
		}
4413
4414
		return self::$capability_translations[$role];
4415
	}
4416
4417
	static function sign_role( $role, $user_id = null ) {
4418
		if ( empty( $user_id ) ) {
4419
			$user_id = (int) get_current_user_id();
4420
		}
4421
4422
		if ( ! $user_id  ) {
4423
			return false;
4424
		}
4425
4426
		$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...
4427
		if ( ! $token || is_wp_error( $token ) ) {
4428
			return false;
4429
		}
4430
4431
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4432
	}
4433
4434
4435
	/**
4436
	 * Builds a URL to the Jetpack connection auth page
4437
	 *
4438
	 * @since 3.9.5
4439
	 *
4440
	 * @param bool $raw If true, URL will not be escaped.
4441
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4442
	 *                              If string, will be a custom redirect.
4443
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4444
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4445
	 *
4446
	 * @return string Connect URL
4447
	 */
4448
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4449
		$site_id = Jetpack_Options::get_option( 'id' );
4450
		$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...
4451
4452
		if ( $register || ! $blog_token || ! $site_id ) {
4453
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4454
4455
			if ( ! empty( $redirect ) ) {
4456
				$url = add_query_arg(
4457
					'redirect',
4458
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4459
					$url
4460
				);
4461
			}
4462
4463
			if( is_network_admin() ) {
4464
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4465
			}
4466
		} else {
4467
4468
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4469
			// because otherwise this logic can get us in to a loop.
4470
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4471
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4472
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4473
4474
				$response = Client::wpcom_json_api_request_as_blog(
4475
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4476
					'1.1'
4477
				);
4478
4479
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4480
4481
					// Generating a register URL instead to refresh the existing token
4482
					return $this->build_connect_url( $raw, $redirect, $from, true );
4483
				}
4484
			}
4485
4486
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4487
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4488
			}
4489
4490
			$role = self::translate_current_user_to_role();
4491
			$signed_role = self::sign_role( $role );
4492
4493
			$user = wp_get_current_user();
4494
4495
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4496
			$redirect = $redirect
4497
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4498
				: $jetpack_admin_page;
4499
4500
			if( isset( $_REQUEST['is_multisite'] ) ) {
4501
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4502
			}
4503
4504
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4505
4506
			/**
4507
			 * Filter the type of authorization.
4508
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4509
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4510
			 *
4511
			 * @since 4.3.3
4512
			 *
4513
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4514
			 */
4515
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4516
4517
4518
			$tracks = new Tracking();
4519
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4520
4521
			$args = urlencode_deep(
4522
				array(
4523
					'response_type' => 'code',
4524
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4525
					'redirect_uri'  => add_query_arg(
4526
						array(
4527
							'action'   => 'authorize',
4528
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4529
							'redirect' => urlencode( $redirect ),
4530
						),
4531
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4532
					),
4533
					'state'         => $user->ID,
4534
					'scope'         => $signed_role,
4535
					'user_email'    => $user->user_email,
4536
					'user_login'    => $user->user_login,
4537
					'is_active'     => Jetpack::is_active(),
4538
					'jp_version'    => JETPACK__VERSION,
4539
					'auth_type'     => $auth_type,
4540
					'secret'        => $secrets['secret_1'],
4541
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4542
					'blogname'      => get_option( 'blogname' ),
4543
					'site_url'      => site_url(),
4544
					'home_url'      => home_url(),
4545
					'site_icon'     => get_site_icon_url(),
4546
					'site_lang'     => get_locale(),
4547
					'_ui'           => $tracks_identity['_ui'],
4548
					'_ut'           => $tracks_identity['_ut'],
4549
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4550
				)
4551
			);
4552
4553
			self::apply_activation_source_to_args( $args );
4554
4555
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4556
		}
4557
4558
		if ( $from ) {
4559
			$url = add_query_arg( 'from', $from, $url );
4560
		}
4561
4562
		// Ensure that class to get the affiliate code is loaded
4563
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4564
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4565
		}
4566
		// Get affiliate code and add it to the URL
4567
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4568
4569
		$calypso_env = $this->get_calypso_env();
4570
4571
		if ( ! empty( $calypso_env ) ) {
4572
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4573
		}
4574
4575
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4576
	}
4577
4578
	/**
4579
	 * Get our assumed site creation date.
4580
	 * Calculated based on the earlier date of either:
4581
	 * - Earliest admin user registration date.
4582
	 * - Earliest date of post of any post type.
4583
	 *
4584
	 * @since 7.2.0
4585
	 *
4586
	 * @return string Assumed site creation date and time.
4587
	 */
4588
	public static function get_assumed_site_creation_date() {
4589
		$earliest_registered_users = get_users( array(
4590
			'role'    => 'administrator',
4591
			'orderby' => 'user_registered',
4592
			'order'   => 'ASC',
4593
			'fields'  => array( 'user_registered' ),
4594
			'number'  => 1,
4595
		) );
4596
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4597
4598
		$earliest_posts = get_posts( array(
4599
			'posts_per_page' => 1,
4600
			'post_type'      => 'any',
4601
			'post_status'    => 'any',
4602
			'orderby'        => 'date',
4603
			'order'          => 'ASC',
4604
		) );
4605
4606
		// If there are no posts at all, we'll count only on user registration date.
4607
		if ( $earliest_posts ) {
4608
			$earliest_post_date = $earliest_posts[0]->post_date;
4609
		} else {
4610
			$earliest_post_date = PHP_INT_MAX;
4611
		}
4612
4613
		return min( $earliest_registration_date, $earliest_post_date );
4614
	}
4615
4616
	public static function apply_activation_source_to_args( &$args ) {
4617
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4618
4619
		if ( $activation_source_name ) {
4620
			$args['_as'] = urlencode( $activation_source_name );
4621
		}
4622
4623
		if ( $activation_source_keyword ) {
4624
			$args['_ak'] = urlencode( $activation_source_keyword );
4625
		}
4626
	}
4627
4628
	function build_reconnect_url( $raw = false ) {
4629
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4630
		return $raw ? $url : esc_url( $url );
4631
	}
4632
4633
	public static function admin_url( $args = null ) {
4634
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4635
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4636
		return $url;
4637
	}
4638
4639
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4640
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4641
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4642
	}
4643
4644
	function dismiss_jetpack_notice() {
4645
4646
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4647
			return;
4648
		}
4649
4650
		switch( $_GET['jetpack-notice'] ) {
4651
			case 'dismiss':
4652
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4653
4654
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4655
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4656
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4657
				}
4658
				break;
4659
			case 'jetpack-protect-multisite-opt-out':
4660
4661
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4662
					// Don't show the banner again
4663
4664
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4665
					// redirect back to the page that had the notice
4666
					if ( wp_get_referer() ) {
4667
						wp_safe_redirect( wp_get_referer() );
4668
					} else {
4669
						// Take me to Jetpack
4670
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4671
					}
4672
				}
4673
				break;
4674
		}
4675
	}
4676
4677
	public static function sort_modules( $a, $b ) {
4678
		if ( $a['sort'] == $b['sort'] )
4679
			return 0;
4680
4681
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4682
	}
4683
4684
	function ajax_recheck_ssl() {
4685
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4686
		$result = Jetpack::permit_ssl( true );
4687
		wp_send_json( array(
4688
			'enabled' => $result,
4689
			'message' => get_transient( 'jetpack_https_test_message' )
4690
		) );
4691
	}
4692
4693
/* Client API */
4694
4695
	/**
4696
	 * Returns the requested Jetpack API URL
4697
	 *
4698
	 * @return string
4699
	 */
4700
	public static function api_url( $relative_url ) {
4701
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4702
	}
4703
4704
	/**
4705
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4706
	 */
4707
	public static function fix_url_for_bad_hosts( $url ) {
4708
		if ( 0 !== strpos( $url, 'https://' ) ) {
4709
			return $url;
4710
		}
4711
4712
		switch ( JETPACK_CLIENT__HTTPS ) {
4713
			case 'ALWAYS' :
4714
				return $url;
4715
			case 'NEVER' :
4716
				return set_url_scheme( $url, 'http' );
4717
			// default : case 'AUTO' :
4718
		}
4719
4720
		// we now return the unmodified SSL URL by default, as a security precaution
4721
		return $url;
4722
	}
4723
4724
	/**
4725
	 * Create a random secret for validating onboarding payload
4726
	 *
4727
	 * @return string Secret token
4728
	 */
4729
	public static function create_onboarding_token() {
4730
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4731
			$token = wp_generate_password( 32, false );
4732
			Jetpack_Options::update_option( 'onboarding', $token );
4733
		}
4734
4735
		return $token;
4736
	}
4737
4738
	/**
4739
	 * Remove the onboarding token
4740
	 *
4741
	 * @return bool True on success, false on failure
4742
	 */
4743
	public static function invalidate_onboarding_token() {
4744
		return Jetpack_Options::delete_option( 'onboarding' );
4745
	}
4746
4747
	/**
4748
	 * Validate an onboarding token for a specific action
4749
	 *
4750
	 * @return boolean True if token/action pair is accepted, false if not
4751
	 */
4752
	public static function validate_onboarding_token_action( $token, $action ) {
4753
		// Compare tokens, bail if tokens do not match
4754
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4755
			return false;
4756
		}
4757
4758
		// List of valid actions we can take
4759
		$valid_actions = array(
4760
			'/jetpack/v4/settings',
4761
		);
4762
4763
		// Whitelist the action
4764
		if ( ! in_array( $action, $valid_actions ) ) {
4765
			return false;
4766
		}
4767
4768
		return true;
4769
	}
4770
4771
	/**
4772
	 * Checks to see if the URL is using SSL to connect with Jetpack
4773
	 *
4774
	 * @since 2.3.3
4775
	 * @return boolean
4776
	 */
4777
	public static function permit_ssl( $force_recheck = false ) {
4778
		// Do some fancy tests to see if ssl is being supported
4779
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4780
			$message = '';
4781
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4782
				$ssl = 0;
4783
			} else {
4784
				switch ( JETPACK_CLIENT__HTTPS ) {
4785
					case 'NEVER':
4786
						$ssl = 0;
4787
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4788
						break;
4789
					case 'ALWAYS':
4790
					case 'AUTO':
4791
					default:
4792
						$ssl = 1;
4793
						break;
4794
				}
4795
4796
				// If it's not 'NEVER', test to see
4797
				if ( $ssl ) {
4798
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4799
						$ssl = 0;
4800
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4801
					} else {
4802
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4803
						if ( is_wp_error( $response ) ) {
4804
							$ssl = 0;
4805
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4806
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4807
							$ssl = 0;
4808
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4809
						}
4810
					}
4811
				}
4812
			}
4813
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4814
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4815
		}
4816
4817
		return (bool) $ssl;
4818
	}
4819
4820
	/*
4821
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4822
	 */
4823
	public function alert_auto_ssl_fail() {
4824
		if ( ! current_user_can( 'manage_options' ) )
4825
			return;
4826
4827
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4828
		?>
4829
4830
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4831
			<div class="jp-banner__content">
4832
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4833
				<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>
4834
				<p>
4835
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4836
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4837
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4838
				</p>
4839
				<p>
4840
					<?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' ),
4841
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4842
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4843
				</p>
4844
			</div>
4845
		</div>
4846
		<style>
4847
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4848
		</style>
4849
		<script type="text/javascript">
4850
			jQuery( document ).ready( function( $ ) {
4851
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4852
					var $this = $( this );
4853
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4854
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4855
					e.preventDefault();
4856
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4857
					$.post( ajaxurl, data )
4858
					  .done( function( response ) {
4859
					  	if ( response.enabled ) {
4860
					  		$( '#jetpack-ssl-warning' ).hide();
4861
					  	} else {
4862
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4863
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4864
					  	}
4865
					  }.bind( $this ) );
4866
				} );
4867
			} );
4868
		</script>
4869
4870
		<?php
4871
	}
4872
4873
	/**
4874
	 * Returns the Jetpack XML-RPC API
4875
	 *
4876
	 * @return string
4877
	 */
4878
	public static function xmlrpc_api_url() {
4879
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4880
		return untrailingslashit( $base ) . '/xmlrpc.php';
4881
	}
4882
4883
	public static function connection() {
4884
		return self::init()->connection_manager;
4885
	}
4886
4887
	/**
4888
	 * Creates two secret tokens and the end of life timestamp for them.
4889
	 *
4890
	 * Note these tokens are unique per call, NOT static per site for connecting.
4891
	 *
4892
	 * @since 2.6
4893
	 * @return array
4894
	 */
4895
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4896
		if ( false === $user_id ) {
4897
			$user_id = get_current_user_id();
4898
		}
4899
4900
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4901
	}
4902
4903
	public static function get_secrets( $action, $user_id ) {
4904
		$secrets = self::connection()->get_secrets( $action, $user_id );
4905
4906
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4907
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

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

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

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

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

Loading history...
4912
		}
4913
4914
		return $secrets;
4915
	}
4916
4917
	/**
4918
	 * @deprecated 7.5 Use Connection_Manager instead.
4919
	 *
4920
	 * @param $action
4921
	 * @param $user_id
4922
	 */
4923
	public static function delete_secrets( $action, $user_id ) {
4924
		return self::connection()->delete_secrets( $action, $user_id );
4925
	}
4926
4927
	/**
4928
	 * Builds the timeout limit for queries talking with the wpcom servers.
4929
	 *
4930
	 * Based on local php max_execution_time in php.ini
4931
	 *
4932
	 * @since 2.6
4933
	 * @return int
4934
	 * @deprecated
4935
	 **/
4936
	public function get_remote_query_timeout_limit() {
4937
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4938
		return Jetpack::get_max_execution_time();
4939
	}
4940
4941
	/**
4942
	 * Builds the timeout limit for queries talking with the wpcom servers.
4943
	 *
4944
	 * Based on local php max_execution_time in php.ini
4945
	 *
4946
	 * @since 5.4
4947
	 * @return int
4948
	 **/
4949
	public static function get_max_execution_time() {
4950
		$timeout = (int) ini_get( 'max_execution_time' );
4951
4952
		// Ensure exec time set in php.ini
4953
		if ( ! $timeout ) {
4954
			$timeout = 30;
4955
		}
4956
		return $timeout;
4957
	}
4958
4959
	/**
4960
	 * Sets a minimum request timeout, and returns the current timeout
4961
	 *
4962
	 * @since 5.4
4963
	 **/
4964
	public static function set_min_time_limit( $min_timeout ) {
4965
		$timeout = self::get_max_execution_time();
4966
		if ( $timeout < $min_timeout ) {
4967
			$timeout = $min_timeout;
4968
			set_time_limit( $timeout );
4969
		}
4970
		return $timeout;
4971
	}
4972
4973
4974
	/**
4975
	 * Takes the response from the Jetpack register new site endpoint and
4976
	 * verifies it worked properly.
4977
	 *
4978
	 * @since 2.6
4979
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4980
	 **/
4981
	public function validate_remote_register_response( $response ) {
4982
	  if ( is_wp_error( $response ) ) {
4983
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'register_http_request_failed'.

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...
4984
		}
4985
4986
		$code   = wp_remote_retrieve_response_code( $response );
4987
		$entity = wp_remote_retrieve_body( $response );
4988
		if ( $entity )
4989
			$registration_response = json_decode( $entity );
4990
		else
4991
			$registration_response = false;
4992
4993
		$code_type = intval( $code / 100 );
4994
		if ( 5 == $code_type ) {
4995
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_5??'.

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...
4996
		} elseif ( 408 == $code ) {
4997
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_408'.

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...
4998
		} elseif ( ! empty( $registration_response->error ) ) {
4999
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5000
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5001
			} else {
5002
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5003
			}
5004
5005
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with (string) $registration_response->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...
5006
		} elseif ( 200 != $code ) {
5007
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_bad_response'.

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...
5008
		}
5009
5010
		// Jetpack ID error block
5011
		if ( empty( $registration_response->jetpack_id ) ) {
5012
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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...
5013
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5014
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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...
5015
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5016
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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...
5017
		}
5018
5019
	    return $registration_response;
5020
	}
5021
	/**
5022
	 * @return bool|WP_Error
5023
	 */
5024
	public static function register() {
5025
		$tracking = new Tracking();
5026
		$tracking->record_user_event( 'jpc_register_begin' );
5027
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5028
		$secrets = Jetpack::generate_secrets( 'register' );
5029
5030 View Code Duplication
		if (
5031
			empty( $secrets['secret_1'] ) ||
5032
			empty( $secrets['secret_2'] ) ||
5033
			empty( $secrets['exp'] )
5034
		) {
5035
			return new Jetpack_Error( 'missing_secrets' );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_secrets'.

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...
5036
		}
5037
5038
		// better to try (and fail) to set a higher timeout than this system
5039
		// supports than to have register fail for more users than it should
5040
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5041
5042
		$gmt_offset = get_option( 'gmt_offset' );
5043
		if ( ! $gmt_offset ) {
5044
			$gmt_offset = 0;
5045
		}
5046
5047
		$stats_options = get_option( 'stats_options' );
5048
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5049
5050
		$tracks = new Tracking();
5051
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5052
5053
		$args = array(
5054
			'method'  => 'POST',
5055
			'body'    => array(
5056
				'siteurl'         => site_url(),
5057
				'home'            => home_url(),
5058
				'gmt_offset'      => $gmt_offset,
5059
				'timezone_string' => (string) get_option( 'timezone_string' ),
5060
				'site_name'       => (string) get_option( 'blogname' ),
5061
				'secret_1'        => $secrets['secret_1'],
5062
				'secret_2'        => $secrets['secret_2'],
5063
				'site_lang'       => get_locale(),
5064
				'timeout'         => $timeout,
5065
				'stats_id'        => $stats_id,
5066
				'state'           => get_current_user_id(),
5067
				'_ui'             => $tracks_identity['_ui'],
5068
				'_ut'             => $tracks_identity['_ut'],
5069
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5070
				'jetpack_version' => JETPACK__VERSION,
5071
				'ABSPATH'         => defined( 'ABSPATH' ) ? ABSPATH : '',
5072
			),
5073
			'headers' => array(
5074
				'Accept' => 'application/json',
5075
			),
5076
			'timeout' => $timeout,
5077
		);
5078
5079
		self::apply_activation_source_to_args( $args['body'] );
5080
5081
		$response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5082
5083
		// Make sure the response is valid and does not contain any Jetpack errors
5084
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5085
		if ( is_wp_error( $registration_details ) ) {
5086
			return $registration_details;
5087
		} elseif ( ! $registration_details ) {
5088
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
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...
5089
		}
5090
5091 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5092
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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...
5093
		}
5094
5095
		if ( isset( $registration_details->jetpack_public ) ) {
5096
			$jetpack_public = (int) $registration_details->jetpack_public;
5097
		} else {
5098
			$jetpack_public = false;
5099
		}
5100
5101
		Jetpack_Options::update_options(
5102
			array(
5103
				'id'         => (int)    $registration_details->jetpack_id,
5104
				'blog_token' => (string) $registration_details->jetpack_secret,
5105
				'public'     => $jetpack_public,
5106
			)
5107
		);
5108
5109
		/**
5110
		 * Fires when a site is registered on WordPress.com.
5111
		 *
5112
		 * @since 3.7.0
5113
		 *
5114
		 * @param int $json->jetpack_id Jetpack Blog ID.
5115
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5116
		 * @param int|bool $jetpack_public Is the site public.
5117
		 */
5118
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5119
5120
		$jetpack = Jetpack::init();
0 ignored issues
show
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
5121
5122
		return true;
5123
	}
5124
5125
	/**
5126
	 * If the db version is showing something other that what we've got now, bump it to current.
5127
	 *
5128
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5129
	 */
5130
	public static function maybe_set_version_option() {
5131
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5132
		if ( JETPACK__VERSION != $version ) {
5133
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5134
5135
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5136
				/** This action is documented in class.jetpack.php */
5137
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5138
			}
5139
5140
			return true;
5141
		}
5142
		return false;
5143
	}
5144
5145
/* Client Server API */
5146
5147
	/**
5148
	 * Loads the Jetpack XML-RPC client
5149
	 */
5150
	public static function load_xml_rpc_client() {
5151
		require_once ABSPATH . WPINC . '/class-IXR.php';
5152
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5153
	}
5154
5155
	/**
5156
	 * Resets the saved authentication state in between testing requests.
5157
	 */
5158
	public function reset_saved_auth_state() {
5159
		$this->xmlrpc_verification = null;
5160
		$this->rest_authentication_status = null;
5161
	}
5162
5163
	/**
5164
	 * Verifies the signature of the current request.
5165
	 *
5166
	 * @return false|array
5167
	 */
5168
	function verify_xml_rpc_signature() {
5169
		if ( is_null( $this->xmlrpc_verification ) ) {
5170
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
5171
5172
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
5173
				/**
5174
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
5175
				 *
5176
				 * Error codes:
5177
				 * - malformed_token
5178
				 * - malformed_user_id
5179
				 * - unknown_token
5180
				 * - could_not_sign
5181
				 * - invalid_nonce
5182
				 * - signature_mismatch
5183
				 *
5184
				 * @since 7.5.0
5185
				 *
5186
				 * @param WP_Error $signature_verification_error The verification error
5187
				 */
5188
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
5189
			}
5190
		}
5191
5192
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
5193
	}
5194
5195
	/**
5196
	 * Verifies the signature of the current request.
5197
	 *
5198
	 * This function has side effects and should not be used. Instead,
5199
	 * use the memoized version `->verify_xml_rpc_signature()`.
5200
	 *
5201
	 * @internal
5202
	 */
5203
	private function internal_verify_xml_rpc_signature() {
5204
		// It's not for us
5205
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5206
			return false;
5207
		}
5208
5209
		$signature_details = array(
5210
			'token'     => isset( $_GET['token'] )     ? wp_unslash( $_GET['token'] )     : '',
5211
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
5212
			'nonce'     => isset( $_GET['nonce'] )     ? wp_unslash( $_GET['nonce'] )     : '',
5213
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
5214
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
5215
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
5216
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
5217
		);
5218
5219
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
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...
5220
		if (
5221
			empty( $token_key )
5222
		||
5223
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5224
		) {
5225
			return new WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'malformed_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...
5226
		}
5227
5228
		if ( '0' === $user_id ) {
5229
			$token_type = 'blog';
5230
			$user_id = 0;
5231
		} else {
5232
			$token_type = 'user';
5233
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5234
				return new WP_Error( 'malformed_user_id', 'Malformed user_id in request', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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...
5235
			}
5236
			$user_id = (int) $user_id;
5237
5238
			$user = new WP_User( $user_id );
5239
			if ( ! $user || ! $user->exists() ) {
5240
				return new WP_Error( 'unknown_user', sprintf( 'User %d does not exist', $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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...
5241
			}
5242
		}
5243
5244
		$token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
0 ignored issues
show
$user_id 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...
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...
5245
		if ( is_wp_error( $token ) ) {
5246
			$token->add_data( compact( 'signature_details' ) );
5247
			return $token;
5248
		} elseif ( ! $token ) {
5249
			return new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
5250
		}
5251
5252
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5253
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5254
			$post_data   = $_POST;
5255
			$file_hashes = array();
5256
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5257
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5258
					continue;
5259
				}
5260
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5261
				$file_hashes[$post_data_key] = $post_data_value;
5262
			}
5263
5264
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5265
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5266
				$post_data[$post_data_key] = $post_data_value;
5267
			}
5268
5269
			ksort( $post_data );
5270
5271
			$body = http_build_query( stripslashes_deep( $post_data ) );
5272
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5273
			$body = file_get_contents( 'php://input' );
5274
		} else {
5275
			$body = null;
5276
		}
5277
5278
		$signature = $jetpack_signature->sign_current_request(
5279
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5280
		);
5281
5282
		$signature_details['url'] = $jetpack_signature->current_request_url;
5283
5284
		if ( ! $signature ) {
5285
			return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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...
5286
		} else if ( is_wp_error( $signature ) ) {
5287
			return $signature;
5288
		}
5289
5290
		$timestamp = (int) $_GET['timestamp'];
5291
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5292
5293
		// Use up the nonce regardless of whether the signature matches.
5294
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5295
			return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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...
5296
		}
5297
5298
		// Be careful about what you do with this debugging data.
5299
		// If a malicious requester has access to the expected signature,
5300
		// bad things might be possible.
5301
		$signature_details['expected'] = $signature;
5302
5303
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5304
			return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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...
5305
		}
5306
5307
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5308
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5309
			if ( ! empty( $_GET['onboarding'] ) ) {
5310
				$jpo = $_GET;
5311
			} else {
5312
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5313
			}
5314
5315
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5316
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5317
5318
			if (
5319
				isset( $jpo_user ) && isset( $jpo_token ) &&
5320
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5321
				isset( $_GET['rest_route'] ) &&
5322
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5323
			) {
5324
				$jpUser = get_user_by( 'email', $jpo_user );
5325
				if ( is_a( $jpUser, 'WP_User' ) ) {
5326
					wp_set_current_user( $jpUser->ID );
5327
					$user_can = is_multisite()
5328
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5329
						: current_user_can( 'manage_options' );
5330
					if ( $user_can ) {
5331
						$token_type = 'user';
5332
						$token->external_user_id = $jpUser->ID;
5333
					}
5334
				}
5335
			}
5336
		}
5337
5338
		return array(
5339
			'type'      => $token_type,
5340
			'token_key' => $token_key,
5341
			'user_id'   => $token->external_user_id,
5342
		);
5343
	}
5344
5345
	/**
5346
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5347
	 */
5348
	function authenticate_jetpack( $user, $username, $password ) {
5349
		if ( is_a( $user, 'WP_User' ) ) {
5350
			return $user;
5351
		}
5352
5353
		$token_details = $this->verify_xml_rpc_signature();
5354
5355
		if ( ! $token_details ) {
5356
			return $user;
5357
		}
5358
5359
		if ( 'user' !== $token_details['type'] ) {
5360
			return $user;
5361
		}
5362
5363
		if ( ! $token_details['user_id'] ) {
5364
			return $user;
5365
		}
5366
5367
		nocache_headers();
5368
5369
		return new WP_User( $token_details['user_id'] );
5370
	}
5371
5372
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5373
	// Uses the existing XMLRPC request signing implementation.
5374
	function wp_rest_authenticate( $user ) {
5375
		if ( ! empty( $user ) ) {
5376
			// Another authentication method is in effect.
5377
			return $user;
5378
		}
5379
5380
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5381
			// Nothing to do for this authentication method.
5382
			return null;
5383
		}
5384
5385
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5386
			// Nothing to do for this authentication method.
5387
			return null;
5388
		}
5389
5390
		// Ensure that we always have the request body available.  At this
5391
		// point, the WP REST API code to determine the request body has not
5392
		// run yet.  That code may try to read from 'php://input' later, but
5393
		// this can only be done once per request in PHP versions prior to 5.6.
5394
		// So we will go ahead and perform this read now if needed, and save
5395
		// the request body where both the Jetpack signature verification code
5396
		// and the WP REST API code can see it.
5397
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5398
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5399
		}
5400
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5401
5402
		// Only support specific request parameters that have been tested and
5403
		// are known to work with signature verification.  A different method
5404
		// can be passed to the WP REST API via the '?_method=' parameter if
5405
		// needed.
5406
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5407
			$this->rest_authentication_status = new WP_Error(
5408
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5409
				__( 'This request method is not supported.', 'jetpack' ),
5410
				array( 'status' => 400 )
5411
			);
5412
			return null;
5413
		}
5414
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5415
			$this->rest_authentication_status = new WP_Error(
5416
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5417
				__( 'This request method does not support body parameters.', 'jetpack' ),
5418
				array( 'status' => 400 )
5419
			);
5420
			return null;
5421
		}
5422
5423
		$verified = $this->verify_xml_rpc_signature();
5424
5425
		if (
5426
			$verified &&
5427
			isset( $verified['type'] ) &&
5428
			'user' === $verified['type'] &&
5429
			! empty( $verified['user_id'] )
5430
		) {
5431
			// Authentication successful.
5432
			$this->rest_authentication_status = true;
5433
			return $verified['user_id'];
5434
		}
5435
5436
		// Something else went wrong.  Probably a signature error.
5437
		$this->rest_authentication_status = new WP_Error(
5438
			'rest_invalid_signature',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5439
			__( 'The request is not signed correctly.', 'jetpack' ),
5440
			array( 'status' => 400 )
5441
		);
5442
		return null;
5443
	}
5444
5445
	/**
5446
	 * Report authentication status to the WP REST API.
5447
	 *
5448
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5449
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5450
	 */
5451
	public function wp_rest_authentication_errors( $value ) {
5452
		if ( $value !== null ) {
5453
			return $value;
5454
		}
5455
		return $this->rest_authentication_status;
5456
	}
5457
5458
	function add_nonce( $timestamp, $nonce ) {
5459
		global $wpdb;
5460
		static $nonces_used_this_request = array();
5461
5462
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5463
			return $nonces_used_this_request["$timestamp:$nonce"];
5464
		}
5465
5466
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5467
		$timestamp = (int) $timestamp;
5468
		$nonce     = esc_sql( $nonce );
5469
5470
		// Raw query so we can avoid races: add_option will also update
5471
		$show_errors = $wpdb->show_errors( false );
5472
5473
		$old_nonce = $wpdb->get_row(
5474
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5475
		);
5476
5477
		if ( is_null( $old_nonce ) ) {
5478
			$return = $wpdb->query(
5479
				$wpdb->prepare(
5480
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5481
					"jetpack_nonce_{$timestamp}_{$nonce}",
5482
					time(),
5483
					'no'
5484
				)
5485
			);
5486
		} else {
5487
			$return = false;
5488
		}
5489
5490
		$wpdb->show_errors( $show_errors );
5491
5492
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5493
5494
		return $return;
5495
	}
5496
5497
	/**
5498
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5499
	 * Capture it here so we can verify the signature later.
5500
	 */
5501
	function xmlrpc_methods( $methods ) {
5502
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5503
		return $methods;
5504
	}
5505
5506
	function public_xmlrpc_methods( $methods ) {
5507
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5508
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5509
		}
5510
		return $methods;
5511
	}
5512
5513
	function jetpack_getOptions( $args ) {
5514
		global $wp_xmlrpc_server;
5515
5516
		$wp_xmlrpc_server->escape( $args );
5517
5518
		$username	= $args[1];
5519
		$password	= $args[2];
5520
5521
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5522
			return $wp_xmlrpc_server->error;
5523
		}
5524
5525
		$options = array();
5526
		$user_data = $this->get_connected_user_data();
5527
		if ( is_array( $user_data ) ) {
5528
			$options['jetpack_user_id'] = array(
5529
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5530
				'readonly'      => true,
5531
				'value'         => $user_data['ID'],
5532
			);
5533
			$options['jetpack_user_login'] = array(
5534
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5535
				'readonly'      => true,
5536
				'value'         => $user_data['login'],
5537
			);
5538
			$options['jetpack_user_email'] = array(
5539
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5540
				'readonly'      => true,
5541
				'value'         => $user_data['email'],
5542
			);
5543
			$options['jetpack_user_site_count'] = array(
5544
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5545
				'readonly'      => true,
5546
				'value'         => $user_data['site_count'],
5547
			);
5548
		}
5549
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5550
		$args = stripslashes_deep( $args );
5551
		return $wp_xmlrpc_server->wp_getOptions( $args );
5552
	}
5553
5554
	function xmlrpc_options( $options ) {
5555
		$jetpack_client_id = false;
5556
		if ( self::is_active() ) {
5557
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5558
		}
5559
		$options['jetpack_version'] = array(
5560
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5561
				'readonly'      => true,
5562
				'value'         => JETPACK__VERSION,
5563
		);
5564
5565
		$options['jetpack_client_id'] = array(
5566
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5567
				'readonly'      => true,
5568
				'value'         => $jetpack_client_id,
5569
		);
5570
		return $options;
5571
	}
5572
5573
	public static function clean_nonces( $all = false ) {
5574
		global $wpdb;
5575
5576
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5577
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5578
5579
		if ( true !== $all ) {
5580
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5581
			$sql_args[] = time() - 3600;
5582
		}
5583
5584
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5585
5586
		$sql = $wpdb->prepare( $sql, $sql_args );
5587
5588
		for ( $i = 0; $i < 1000; $i++ ) {
5589
			if ( ! $wpdb->query( $sql ) ) {
5590
				break;
5591
			}
5592
		}
5593
	}
5594
5595
	/**
5596
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5597
	 * SET: state( $key, $value );
5598
	 * GET: $value = state( $key );
5599
	 *
5600
	 * @param string $key
0 ignored issues
show
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

Loading history...
5602
	 * @param bool $restate private
5603
	 */
5604
	public static function state( $key = null, $value = null, $restate = false ) {
5605
		static $state = array();
5606
		static $path, $domain;
5607
		if ( ! isset( $path ) ) {
5608
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5609
			$admin_url = Jetpack::admin_url();
5610
			$bits      = wp_parse_url( $admin_url );
5611
5612
			if ( is_array( $bits ) ) {
5613
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5614
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5615
			} else {
5616
				$path = $domain = null;
5617
			}
5618
		}
5619
5620
		// Extract state from cookies and delete cookies
5621
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5622
			$yum = $_COOKIE[ 'jetpackState' ];
5623
			unset( $_COOKIE[ 'jetpackState' ] );
5624
			foreach ( $yum as $k => $v ) {
5625
				if ( strlen( $v ) )
5626
					$state[ $k ] = $v;
5627
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5628
			}
5629
		}
5630
5631
		if ( $restate ) {
5632
			foreach ( $state as $k => $v ) {
5633
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5634
			}
5635
			return;
5636
		}
5637
5638
		// Get a state variable
5639
		if ( isset( $key ) && ! isset( $value ) ) {
5640
			if ( array_key_exists( $key, $state ) )
5641
				return $state[ $key ];
5642
			return null;
5643
		}
5644
5645
		// Set a state variable
5646
		if ( isset ( $key ) && isset( $value ) ) {
5647
			if( is_array( $value ) && isset( $value[0] ) ) {
5648
				$value = $value[0];
5649
			}
5650
			$state[ $key ] = $value;
5651
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5652
		}
5653
	}
5654
5655
	public static function restate() {
5656
		Jetpack::state( null, null, true );
5657
	}
5658
5659
	public static function check_privacy( $file ) {
5660
		static $is_site_publicly_accessible = null;
5661
5662
		if ( is_null( $is_site_publicly_accessible ) ) {
5663
			$is_site_publicly_accessible = false;
5664
5665
			Jetpack::load_xml_rpc_client();
5666
			$rpc = new Jetpack_IXR_Client();
5667
5668
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5669
			if ( $success ) {
5670
				$response = $rpc->getResponse();
5671
				if ( $response ) {
5672
					$is_site_publicly_accessible = true;
5673
				}
5674
			}
5675
5676
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5677
		}
5678
5679
		if ( $is_site_publicly_accessible ) {
5680
			return;
5681
		}
5682
5683
		$module_slug = self::get_module_slug( $file );
5684
5685
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5686
		if ( ! $privacy_checks ) {
5687
			$privacy_checks = $module_slug;
5688
		} else {
5689
			$privacy_checks .= ",$module_slug";
5690
		}
5691
5692
		Jetpack::state( 'privacy_checks', $privacy_checks );
5693
	}
5694
5695
	/**
5696
	 * Helper method for multicall XMLRPC.
5697
	 */
5698
	public static function xmlrpc_async_call() {
5699
		global $blog_id;
5700
		static $clients = array();
5701
5702
		$client_blog_id = is_multisite() ? $blog_id : 0;
5703
5704
		if ( ! isset( $clients[$client_blog_id] ) ) {
5705
			Jetpack::load_xml_rpc_client();
5706
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5707
			if ( function_exists( 'ignore_user_abort' ) ) {
5708
				ignore_user_abort( true );
5709
			}
5710
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5711
		}
5712
5713
		$args = func_get_args();
5714
5715
		if ( ! empty( $args[0] ) ) {
5716
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5717
		} elseif ( is_multisite() ) {
5718
			foreach ( $clients as $client_blog_id => $client ) {
5719
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5720
					continue;
5721
				}
5722
5723
				$switch_success = switch_to_blog( $client_blog_id, true );
5724
				if ( ! $switch_success ) {
5725
					continue;
5726
				}
5727
5728
				flush();
5729
				$client->query();
5730
5731
				restore_current_blog();
5732
			}
5733
		} else {
5734
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5735
				flush();
5736
				$clients[0]->query();
5737
			}
5738
		}
5739
	}
5740
5741
	public static function staticize_subdomain( $url ) {
5742
5743
		// Extract hostname from URL
5744
		$host = parse_url( $url, PHP_URL_HOST );
5745
5746
		// Explode hostname on '.'
5747
		$exploded_host = explode( '.', $host );
5748
5749
		// Retrieve the name and TLD
5750
		if ( count( $exploded_host ) > 1 ) {
5751
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5752
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5753
			// Rebuild domain excluding subdomains
5754
			$domain = $name . '.' . $tld;
5755
		} else {
5756
			$domain = $host;
5757
		}
5758
		// Array of Automattic domains
5759
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5760
5761
		// Return $url if not an Automattic domain
5762
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5763
			return $url;
5764
		}
5765
5766
		if ( is_ssl() ) {
5767
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5768
		}
5769
5770
		srand( crc32( basename( $url ) ) );
5771
		$static_counter = rand( 0, 2 );
5772
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5773
5774
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5775
	}
5776
5777
/* JSON API Authorization */
5778
5779
	/**
5780
	 * Handles the login action for Authorizing the JSON API
5781
	 */
5782
	function login_form_json_api_authorization() {
5783
		$this->verify_json_api_authorization_request();
5784
5785
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5786
5787
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5788
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5789
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5790
	}
5791
5792
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5793
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5794
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5795
			return $url;
5796
		}
5797
5798
		$parsed_url = parse_url( $url );
5799
		$url = strtok( $url, '?' );
5800
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5801
		if ( ! empty( $parsed_url['query'] ) )
5802
			$url .= "&{$parsed_url['query']}";
5803
5804
		return $url;
5805
	}
5806
5807
	// Make sure the POSTed request is handled by the same action
5808
	function preserve_action_in_login_form_for_json_api_authorization() {
5809
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5810
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5811
	}
5812
5813
	// If someone logs in to approve API access, store the Access Code in usermeta
5814
	function store_json_api_authorization_token( $user_login, $user ) {
5815
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5816
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5817
		$token = wp_generate_password( 32, false );
5818
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5819
	}
5820
5821
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5822
	function allow_wpcom_public_api_domain( $domains ) {
5823
		$domains[] = 'public-api.wordpress.com';
5824
		return $domains;
5825
	}
5826
5827
	static function is_redirect_encoded( $redirect_url ) {
5828
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5829
	}
5830
5831
	// Add all wordpress.com environments to the safe redirect whitelist
5832
	function allow_wpcom_environments( $domains ) {
5833
		$domains[] = 'wordpress.com';
5834
		$domains[] = 'wpcalypso.wordpress.com';
5835
		$domains[] = 'horizon.wordpress.com';
5836
		$domains[] = 'calypso.localhost';
5837
		return $domains;
5838
	}
5839
5840
	// Add the Access Code details to the public-api.wordpress.com redirect
5841
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5842
		return add_query_arg(
5843
			urlencode_deep(
5844
				array(
5845
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5846
					'jetpack-user-id' => (int) $user->ID,
5847
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5848
				)
5849
			),
5850
			$redirect_to
5851
		);
5852
	}
5853
5854
5855
	/**
5856
	 * Verifies the request by checking the signature
5857
	 *
5858
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5859
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5860
	 *
5861
	 * @param null|array $environment
5862
	 */
5863
	function verify_json_api_authorization_request( $environment = null ) {
5864
		$environment = is_null( $environment )
5865
			? $_REQUEST
5866
			: $environment;
5867
5868
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

Loading history...
5870
		if ( ! $token || empty( $token->secret ) ) {
5871
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5872
		}
5873
5874
		$die_error = __( 'Someone may be trying to trick you into giving them access to your site.  Or it could be you just encountered a bug :).  Either way, please close this window.', 'jetpack' );
5875
5876
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5877
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5878
			/**
5879
			 * Jetpack authorisation request Error.
5880
			 *
5881
			 * @since 7.5.0
5882
			 *
5883
			 */
5884
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5885
			$die_error = sprintf(
5886
				/* translators: %s is a URL */
5887
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
5888
				'https://jetpack.com/support/double-encoding/'
5889
			);
5890
		}
5891
5892
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5893
5894
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5895
			$signature = $jetpack_signature->sign_request(
5896
				$environment['token'],
5897
				$environment['timestamp'],
5898
				$environment['nonce'],
5899
				'',
5900
				'GET',
5901
				$environment['jetpack_json_api_original_query'],
5902
				null,
5903
				true
5904
			);
5905
		} else {
5906
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5907
		}
5908
5909
		if ( ! $signature ) {
5910
			wp_die( $die_error );
5911
		} else if ( is_wp_error( $signature ) ) {
5912
			wp_die( $die_error );
5913
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5914
			if ( is_ssl() ) {
5915
				// If we signed an HTTP request on the Jetpack Servers, but got redirected to HTTPS by the local blog, check the HTTP signature as well
5916
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5917
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5918
					wp_die( $die_error );
5919
				}
5920
			} else {
5921
				wp_die( $die_error );
5922
			}
5923
		}
5924
5925
		$timestamp = (int) $environment['timestamp'];
5926
		$nonce     = stripslashes( (string) $environment['nonce'] );
5927
5928
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5929
			// De-nonce the nonce, at least for 5 minutes.
5930
			// We have to reuse this nonce at least once (used the first time when the initial request is made, used a second time when the login form is POSTed)
5931
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5932
			if ( $old_nonce_time < time() - 300 ) {
5933
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5934
			}
5935
		}
5936
5937
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5938
		$data_filters = array(
5939
			'state'        => 'opaque',
5940
			'client_id'    => 'int',
5941
			'client_title' => 'string',
5942
			'client_image' => 'url',
5943
		);
5944
5945
		foreach ( $data_filters as $key => $sanitation ) {
5946
			if ( ! isset( $data->$key ) ) {
5947
				wp_die( $die_error );
5948
			}
5949
5950
			switch ( $sanitation ) {
5951
			case 'int' :
5952
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5953
				break;
5954
			case 'opaque' :
5955
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5956
				break;
5957
			case 'string' :
5958
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5959
				break;
5960
			case 'url' :
5961
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5962
				break;
5963
			}
5964
		}
5965
5966
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5967
			wp_die( $die_error );
5968
		}
5969
	}
5970
5971
	function login_message_json_api_authorization( $message ) {
5972
		return '<p class="message">' . sprintf(
5973
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5974
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5975
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5976
	}
5977
5978
	/**
5979
	 * Get $content_width, but with a <s>twist</s> filter.
5980
	 */
5981
	public static function get_content_width() {
5982
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5983
			? $GLOBALS['content_width']
5984
			: false;
5985
		/**
5986
		 * Filter the Content Width value.
5987
		 *
5988
		 * @since 2.2.3
5989
		 *
5990
		 * @param string $content_width Content Width value.
5991
		 */
5992
		return apply_filters( 'jetpack_content_width', $content_width );
5993
	}
5994
5995
	/**
5996
	 * Pings the WordPress.com Mirror Site for the specified options.
5997
	 *
5998
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5999
	 *
6000
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6001
	 */
6002
	public function get_cloud_site_options( $option_names ) {
6003
		$option_names = array_filter( (array) $option_names, 'is_string' );
6004
6005
		Jetpack::load_xml_rpc_client();
6006
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6007
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6008
		if ( $xml->isError() ) {
6009
			return array(
6010
				'error_code' => $xml->getErrorCode(),
6011
				'error_msg'  => $xml->getErrorMessage(),
6012
			);
6013
		}
6014
		$cloud_site_options = $xml->getResponse();
6015
6016
		return $cloud_site_options;
6017
	}
6018
6019
	/**
6020
	 * Checks if the site is currently in an identity crisis.
6021
	 *
6022
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6023
	 */
6024
	public static function check_identity_crisis() {
6025
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6026
			return false;
6027
		}
6028
6029
		return Jetpack_Options::get_option( 'sync_error_idc' );
6030
	}
6031
6032
	/**
6033
	 * Checks whether the home and siteurl specifically are whitelisted
6034
	 * Written so that we don't have re-check $key and $value params every time
6035
	 * we want to check if this site is whitelisted, for example in footer.php
6036
	 *
6037
	 * @since  3.8.0
6038
	 * @return bool True = already whitelisted False = not whitelisted
6039
	 */
6040
	public static function is_staging_site() {
6041
		$is_staging = false;
6042
6043
		$known_staging = array(
6044
			'urls' => array(
6045
				'#\.staging\.wpengine\.com$#i', // WP Engine
6046
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6047
				'#\.stage\.site$#i'             // DreamPress
6048
			),
6049
			'constants' => array(
6050
				'IS_WPE_SNAPSHOT',      // WP Engine
6051
				'KINSTA_DEV_ENV',       // Kinsta.com
6052
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6053
				'JETPACK_STAGING_MODE', // Generic
6054
			)
6055
		);
6056
		/**
6057
		 * Filters the flags of known staging sites.
6058
		 *
6059
		 * @since 3.9.0
6060
		 *
6061
		 * @param array $known_staging {
6062
		 *     An array of arrays that each are used to check if the current site is staging.
6063
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6064
		 *     @type array $constants PHP constants of known staging/developement environments.
6065
		 *  }
6066
		 */
6067
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6068
6069
		if ( isset( $known_staging['urls'] ) ) {
6070
			foreach ( $known_staging['urls'] as $url ){
6071
				if ( preg_match( $url, site_url() ) ) {
6072
					$is_staging = true;
6073
					break;
6074
				}
6075
			}
6076
		}
6077
6078
		if ( isset( $known_staging['constants'] ) ) {
6079
			foreach ( $known_staging['constants'] as $constant ) {
6080
				if ( defined( $constant ) && constant( $constant ) ) {
6081
					$is_staging = true;
6082
				}
6083
			}
6084
		}
6085
6086
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6087
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6088
			$is_staging = true;
6089
		}
6090
6091
		/**
6092
		 * Filters is_staging_site check.
6093
		 *
6094
		 * @since 3.9.0
6095
		 *
6096
		 * @param bool $is_staging If the current site is a staging site.
6097
		 */
6098
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6099
	}
6100
6101
	/**
6102
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6103
	 *
6104
	 * @since 4.4.0
6105
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6106
	 *
6107
	 * @return bool
6108
	 */
6109
	public static function validate_sync_error_idc_option() {
6110
		$is_valid = false;
6111
6112
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6113
		if ( false === $idc_allowed ) {
6114
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6115
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6116
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6117
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6118
				$transient_duration = HOUR_IN_SECONDS;
6119
			} else {
6120
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6121
				$idc_allowed = '1';
6122
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6123
			}
6124
6125
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6126
		}
6127
6128
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6129
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6130
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6131
			$local_options = self::get_sync_error_idc_option();
6132
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6133
				$is_valid = true;
6134
			}
6135
		}
6136
6137
		/**
6138
		 * Filters whether the sync_error_idc option is valid.
6139
		 *
6140
		 * @since 4.4.0
6141
		 *
6142
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6143
		 */
6144
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6145
6146
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6147
			// Since the option exists, and did not validate, delete it
6148
			Jetpack_Options::delete_option( 'sync_error_idc' );
6149
		}
6150
6151
		return $is_valid;
6152
	}
6153
6154
	/**
6155
	 * Normalizes a url by doing three things:
6156
	 *  - Strips protocol
6157
	 *  - Strips www
6158
	 *  - Adds a trailing slash
6159
	 *
6160
	 * @since 4.4.0
6161
	 * @param string $url
6162
	 * @return WP_Error|string
6163
	 */
6164
	public static function normalize_url_protocol_agnostic( $url ) {
6165
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6166
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6167
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
6299
	 */
6300
	public static function set_suffix_on_min( $src, $handle ) {
6301
		if ( false === strpos( $src, '.min.css' ) ) {
6302
			return $src;
6303
		}
6304
6305
		if ( ! empty( self::$min_assets ) ) {
6306
			foreach ( self::$min_assets as $file => $path ) {
6307
				if ( false !== strpos( $src, $file ) ) {
6308
					wp_style_add_data( $handle, 'suffix', '.min' );
6309
					return $src;
6310
				}
6311
			}
6312
		}
6313
6314
		return $src;
6315
	}
6316
6317
	/**
6318
	 * Maybe inlines a stylesheet.
6319
	 *
6320
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6321
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6322
	 *
6323
	 * Attached to `style_loader_tag` filter.
6324
	 *
6325
	 * @param string $tag The tag that would link to the external asset.
6326
	 * @param string $handle The registered handle of the script in question.
6327
	 *
6328
	 * @return string
6329
	 */
6330
	public static function maybe_inline_style( $tag, $handle ) {
6331
		global $wp_styles;
6332
		$item = $wp_styles->registered[ $handle ];
6333
6334
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6335
			return $tag;
6336
		}
6337
6338
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6339
			$href = $matches[1];
6340
			// Strip off query string
6341
			if ( $pos = strpos( $href, '?' ) ) {
6342
				$href = substr( $href, 0, $pos );
6343
			}
6344
			// Strip off fragment
6345
			if ( $pos = strpos( $href, '#' ) ) {
6346
				$href = substr( $href, 0, $pos );
6347
			}
6348
		} else {
6349
			return $tag;
6350
		}
6351
6352
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6353
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6354
			return $tag;
6355
		}
6356
6357
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6358
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6359
			// And this isn't the pass that actually deals with the RTL version...
6360
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6361
				// Short out, as the RTL version will deal with it in a moment.
6362
				return $tag;
6363
			}
6364
		}
6365
6366
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6367
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6368
		if ( $css ) {
6369
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6370
			if ( empty( $item->extra['after'] ) ) {
6371
				wp_add_inline_style( $handle, $css );
6372
			} else {
6373
				array_unshift( $item->extra['after'], $css );
6374
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6375
			}
6376
		}
6377
6378
		return $tag;
6379
	}
6380
6381
	/**
6382
	 * Loads a view file from the views
6383
	 *
6384
	 * Data passed in with the $data parameter will be available in the
6385
	 * template file as $data['value']
6386
	 *
6387
	 * @param string $template - Template file to load
6388
	 * @param array $data - Any data to pass along to the template
6389
	 * @return boolean - If template file was found
6390
	 **/
6391
	public function load_view( $template, $data = array() ) {
6392
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6393
6394
		if( file_exists( $views_dir . $template ) ) {
6395
			require_once( $views_dir . $template );
6396
			return true;
6397
		}
6398
6399
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6400
		return false;
6401
	}
6402
6403
	/**
6404
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6405
	 */
6406
	public function deprecated_hooks() {
6407
		global $wp_filter;
6408
6409
		/*
6410
		 * Format:
6411
		 * deprecated_filter_name => replacement_name
6412
		 *
6413
		 * If there is no replacement, use null for replacement_name
6414
		 */
6415
		$deprecated_list = array(
6416
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6417
			'wpl_sharing_2014_1'                                     => null,
6418
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6419
			'jetpack_identity_crisis_options_to_check'               => null,
6420
			'update_option_jetpack_single_user_site'                 => null,
6421
			'audio_player_default_colors'                            => null,
6422
			'add_option_jetpack_featured_images_enabled'             => null,
6423
			'add_option_jetpack_update_details'                      => null,
6424
			'add_option_jetpack_updates'                             => null,
6425
			'add_option_jetpack_network_name'                        => null,
6426
			'add_option_jetpack_network_allow_new_registrations'     => null,
6427
			'add_option_jetpack_network_add_new_users'               => null,
6428
			'add_option_jetpack_network_site_upload_space'           => null,
6429
			'add_option_jetpack_network_upload_file_types'           => null,
6430
			'add_option_jetpack_network_enable_administration_menus' => null,
6431
			'add_option_jetpack_is_multi_site'                       => null,
6432
			'add_option_jetpack_is_main_network'                     => null,
6433
			'add_option_jetpack_main_network_site'                   => null,
6434
			'jetpack_sync_all_registered_options'                    => null,
6435
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6436
			'jetpack_is_post_mailable'                               => null,
6437
			'jetpack_seo_site_host'                                  => null,
6438
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6439
			'jetpack_holiday_snow_option_name'                       => null,
6440
			'jetpack_holiday_chance_of_snow'                         => null,
6441
			'jetpack_holiday_snow_js_url'                            => null,
6442
			'jetpack_is_holiday_snow_season'                         => null,
6443
			'jetpack_holiday_snow_option_updated'                    => null,
6444
			'jetpack_holiday_snowing'                                => null,
6445
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6446
			'jetpack_cache_plans'                                    => null,
6447
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6448
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6449
			'jetpack_enable_site_verification'                       => null,
6450
			'can_display_jetpack_manage_notice'                      => null,
6451
			// Removed in Jetpack 7.3.0
6452
			'atd_load_scripts'                                       => null,
6453
			'atd_http_post_timeout'                                  => null,
6454
			'atd_http_post_error'                                    => null,
6455
			'atd_service_domain'                                     => null,
6456
		);
6457
6458
		// This is a silly loop depth. Better way?
6459
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6460
			if ( has_action( $hook ) ) {
6461
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6462
					foreach( $values AS $hooked ) {
6463
						if ( is_callable( $hooked['function'] ) ) {
6464
							$function_name = 'an anonymous function';
6465
						} else {
6466
							$function_name = $hooked['function'];
6467
						}
6468
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6469
					}
6470
				}
6471
			}
6472
		}
6473
	}
6474
6475
	/**
6476
	 * Converts any url in a stylesheet, to the correct absolute url.
6477
	 *
6478
	 * Considerations:
6479
	 *  - Normal, relative URLs     `feh.png`
6480
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6481
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6482
	 *  - Absolute URLs             `http://domain.com/feh.png`
6483
	 *  - Domain root relative URLs `/feh.png`
6484
	 *
6485
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6486
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6487
	 *
6488
	 * @return mixed|string
6489
	 */
6490
	public static function absolutize_css_urls( $css, $css_file_url ) {
6491
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6492
		$css_dir = dirname( $css_file_url );
6493
		$p       = parse_url( $css_dir );
6494
		$domain  = sprintf(
6495
					'%1$s//%2$s%3$s%4$s',
6496
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6497
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6498
					$p['host'],
6499
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6500
				);
6501
6502
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6503
			$find = $replace = array();
6504
			foreach ( $matches as $match ) {
6505
				$url = trim( $match['path'], "'\" \t" );
6506
6507
				// If this is a data url, we don't want to mess with it.
6508
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6509
					continue;
6510
				}
6511
6512
				// If this is an absolute or protocol-agnostic url,
6513
				// we don't want to mess with it.
6514
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6515
					continue;
6516
				}
6517
6518
				switch ( substr( $url, 0, 1 ) ) {
6519
					case '/':
6520
						$absolute = $domain . $url;
6521
						break;
6522
					default:
6523
						$absolute = $css_dir . '/' . $url;
6524
				}
6525
6526
				$find[]    = $match[0];
6527
				$replace[] = sprintf( 'url("%s")', $absolute );
6528
			}
6529
			$css = str_replace( $find, $replace, $css );
6530
		}
6531
6532
		return $css;
6533
	}
6534
6535
	/**
6536
	 * This methods removes all of the registered css files on the front end
6537
	 * from Jetpack in favor of using a single file. In effect "imploding"
6538
	 * all the files into one file.
6539
	 *
6540
	 * Pros:
6541
	 * - Uses only ONE css asset connection instead of 15
6542
	 * - Saves a minimum of 56k
6543
	 * - Reduces server load
6544
	 * - Reduces time to first painted byte
6545
	 *
6546
	 * Cons:
6547
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6548
	 *		should not cause any issues with themes.
6549
	 * - Plugins/themes dequeuing styles no longer do anything. See
6550
	 *		jetpack_implode_frontend_css filter for a workaround
6551
	 *
6552
	 * For some situations developers may wish to disable css imploding and
6553
	 * instead operate in legacy mode where each file loads seperately and
6554
	 * can be edited individually or dequeued. This can be accomplished with
6555
	 * the following line:
6556
	 *
6557
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6558
	 *
6559
	 * @since 3.2
6560
	 **/
6561
	public function implode_frontend_css( $travis_test = false ) {
6562
		$do_implode = true;
6563
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6564
			$do_implode = false;
6565
		}
6566
6567
		// Do not implode CSS when the page loads via the AMP plugin.
6568
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6569
			$do_implode = false;
6570
		}
6571
6572
		/**
6573
		 * Allow CSS to be concatenated into a single jetpack.css file.
6574
		 *
6575
		 * @since 3.2.0
6576
		 *
6577
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6578
		 */
6579
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6580
6581
		// Do not use the imploded file when default behavior was altered through the filter
6582
		if ( ! $do_implode ) {
6583
			return;
6584
		}
6585
6586
		// We do not want to use the imploded file in dev mode, or if not connected
6587
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6588
			if ( ! $travis_test ) {
6589
				return;
6590
			}
6591
		}
6592
6593
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6594
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6595
			return;
6596
		}
6597
6598
		/*
6599
		 * Now we assume Jetpack is connected and able to serve the single
6600
		 * file.
6601
		 *
6602
		 * In the future there will be a check here to serve the file locally
6603
		 * or potentially from the Jetpack CDN
6604
		 *
6605
		 * For now:
6606
		 * - Enqueue a single imploded css file
6607
		 * - Zero out the style_loader_tag for the bundled ones
6608
		 * - Be happy, drink scotch
6609
		 */
6610
6611
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6612
6613
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6614
6615
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6616
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6617
	}
6618
6619
	function concat_remove_style_loader_tag( $tag, $handle ) {
6620
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6621
			$tag = '';
6622
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6623
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6624
			}
6625
		}
6626
6627
		return $tag;
6628
	}
6629
6630
	/*
6631
	 * Check the heartbeat data
6632
	 *
6633
	 * Organizes the heartbeat data by severity.  For example, if the site
6634
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6635
	 *
6636
	 * Data will be added to "caution" array, if it either:
6637
	 *  - Out of date Jetpack version
6638
	 *  - Out of date WP version
6639
	 *  - Out of date PHP version
6640
	 *
6641
	 * $return array $filtered_data
6642
	 */
6643
	public static function jetpack_check_heartbeat_data() {
6644
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6645
6646
		$good    = array();
6647
		$caution = array();
6648
		$bad     = array();
6649
6650
		foreach ( $raw_data as $stat => $value ) {
6651
6652
			// Check jetpack version
6653
			if ( 'version' == $stat ) {
6654
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6655
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6656
					continue;
6657
				}
6658
			}
6659
6660
			// Check WP version
6661
			if ( 'wp-version' == $stat ) {
6662
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6663
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6664
					continue;
6665
				}
6666
			}
6667
6668
			// Check PHP version
6669
			if ( 'php-version' == $stat ) {
6670
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6671
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6672
					continue;
6673
				}
6674
			}
6675
6676
			// Check ID crisis
6677
			if ( 'identitycrisis' == $stat ) {
6678
				if ( 'yes' == $value ) {
6679
					$bad[ $stat ] = $value;
6680
					continue;
6681
				}
6682
			}
6683
6684
			// The rest are good :)
6685
			$good[ $stat ] = $value;
6686
		}
6687
6688
		$filtered_data = array(
6689
			'good'    => $good,
6690
			'caution' => $caution,
6691
			'bad'     => $bad
6692
		);
6693
6694
		return $filtered_data;
6695
	}
6696
6697
6698
	/*
6699
	 * This method is used to organize all options that can be reset
6700
	 * without disconnecting Jetpack.
6701
	 *
6702
	 * It is used in class.jetpack-cli.php to reset options
6703
	 *
6704
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6705
	 *
6706
	 * @return array of options to delete.
6707
	 */
6708
	public static function get_jetpack_options_for_reset() {
6709
		return Jetpack_Options::get_options_for_reset();
6710
	}
6711
6712
	/*
6713
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6714
	 * so we can bring them directly to their site in calypso.
6715
	 *
6716
	 * @param string | url
6717
	 * @return string | url without the guff
6718
	 */
6719
	public static function build_raw_urls( $url ) {
6720
		$strip_http = '/.*?:\/\//i';
6721
		$url = preg_replace( $strip_http, '', $url  );
6722
		$url = str_replace( '/', '::', $url );
6723
		return $url;
6724
	}
6725
6726
	/**
6727
	 * Stores and prints out domains to prefetch for page speed optimization.
6728
	 *
6729
	 * @param mixed $new_urls
6730
	 */
6731
	public static function dns_prefetch( $new_urls = null ) {
6732
		static $prefetch_urls = array();
6733
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6734
			echo "\r\n";
6735
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6736
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6737
			}
6738
		} elseif ( ! empty( $new_urls ) ) {
6739
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6740
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6741
			}
6742
			foreach ( (array) $new_urls as $this_new_url ) {
6743
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6744
			}
6745
			$prefetch_urls = array_unique( $prefetch_urls );
6746
		}
6747
	}
6748
6749
	public function wp_dashboard_setup() {
6750
		if ( self::is_active() ) {
6751
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6752
		}
6753
6754
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6755
			$jetpack_logo = new Jetpack_Logo();
6756
			$widget_title = sprintf(
6757
				wp_kses(
6758
					/* translators: Placeholder is a Jetpack logo. */
6759
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6760
					array( 'span' => array() )
6761
				),
6762
				$jetpack_logo->get_jp_emblem( true )
6763
			);
6764
6765
			wp_add_dashboard_widget(
6766
				'jetpack_summary_widget',
6767
				$widget_title,
6768
				array( __CLASS__, 'dashboard_widget' )
6769
			);
6770
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6771
6772
			// If we're inactive and not in development mode, sort our box to the top.
6773
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6774
				global $wp_meta_boxes;
6775
6776
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6777
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6778
6779
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6780
			}
6781
		}
6782
	}
6783
6784
	/**
6785
	 * @param mixed $result Value for the user's option
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
6786
	 * @return mixed
6787
	 */
6788
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6789
		if ( ! is_array( $sorted ) ) {
6790
			return $sorted;
6791
		}
6792
6793
		foreach ( $sorted as $box_context => $ids ) {
6794
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6795
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6796
				continue;
6797
			}
6798
6799
			$ids_array = explode( ',', $ids );
6800
			$key = array_search( 'dashboard_stats', $ids_array );
6801
6802
			if ( false !== $key ) {
6803
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6804
				$ids_array[ $key ] = 'jetpack_summary_widget';
6805
				$sorted[ $box_context ] = implode( ',', $ids_array );
6806
				// We've found it, stop searching, and just return.
6807
				break;
6808
			}
6809
		}
6810
6811
		return $sorted;
6812
	}
6813
6814
	public static function dashboard_widget() {
6815
		/**
6816
		 * Fires when the dashboard is loaded.
6817
		 *
6818
		 * @since 3.4.0
6819
		 */
6820
		do_action( 'jetpack_dashboard_widget' );
6821
	}
6822
6823
	public static function dashboard_widget_footer() {
6824
		?>
6825
		<footer>
6826
6827
		<div class="protect">
6828
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6829
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6830
				<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>
6831
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6832
				<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' ); ?>">
6833
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6834
				</a>
6835
			<?php else : ?>
6836
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6837
			<?php endif; ?>
6838
		</div>
6839
6840
		<div class="akismet">
6841
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6842
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6843
				<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>
6844
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6845
				<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">
6846
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6847
				</a>
6848
			<?php else : ?>
6849
				<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>
6850
			<?php endif; ?>
6851
		</div>
6852
6853
		</footer>
6854
		<?php
6855
	}
6856
6857
	/*
6858
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6859
	 */
6860
	function jetpack_icon_user_connected( $columns ) {
6861
		$columns['user_jetpack'] = '';
6862
		return $columns;
6863
	}
6864
6865
	/*
6866
	 * Show Jetpack icon if the user is linked.
6867
	 */
6868
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6869
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6870
			$jetpack_logo = new Jetpack_Logo();
6871
			$emblem_html = sprintf(
6872
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6873
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6874
				$jetpack_logo->get_jp_emblem()
6875
			);
6876
			return $emblem_html;
6877
		}
6878
6879
		return $val;
6880
	}
6881
6882
	/*
6883
	 * Style the Jetpack user column
6884
	 */
6885
	function jetpack_user_col_style() {
6886
		global $current_screen;
6887
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6888
			<style>
6889
				.fixed .column-user_jetpack {
6890
					width: 21px;
6891
				}
6892
				.jp-emblem-user-admin svg {
6893
					width: 20px;
6894
					height: 20px;
6895
				}
6896
				.jp-emblem-user-admin path {
6897
					fill: #00BE28;
6898
				}
6899
			</style>
6900
		<?php }
6901
	}
6902
6903
	/**
6904
	 * Checks if Akismet is active and working.
6905
	 *
6906
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6907
	 * that implied usage of methods present since more recent version.
6908
	 * See https://github.com/Automattic/jetpack/pull/9585
6909
	 *
6910
	 * @since  5.1.0
6911
	 *
6912
	 * @return bool True = Akismet available. False = Aksimet not available.
6913
	 */
6914
	public static function is_akismet_active() {
6915
		static $status = null;
6916
6917
		if ( ! is_null( $status ) ) {
6918
			return $status;
6919
		}
6920
6921
		// Check if a modern version of Akismet is active.
6922
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6923
			$status = false;
6924
			return $status;
6925
		}
6926
6927
		// Make sure there is a key known to Akismet at all before verifying key.
6928
		$akismet_key = Akismet::get_api_key();
6929
		if ( ! $akismet_key ) {
6930
			$status = false;
6931
			return $status;
6932
		}
6933
6934
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6935
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6936
6937
		// 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.
6938
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6939
		// We cache the result of the Akismet key verification for ten minutes.
6940
		if ( ! $akismet_key_state || $recheck ) {
6941
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6942
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6943
		}
6944
6945
		$status = 'valid' === $akismet_key_state;
6946
6947
		return $status;
6948
	}
6949
6950
	/**
6951
	 * Checks if one or more function names is in debug_backtrace
6952
	 *
6953
	 * @param $names Mixed string name of function or array of string names of functions
6954
	 *
6955
	 * @return bool
6956
	 */
6957
	public static function is_function_in_backtrace( $names ) {
6958
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6959
		if ( ! is_array( $names ) ) {
6960
			$names = array( $names );
6961
		}
6962
		$names_as_keys = array_flip( $names );
6963
6964
		//Do check in constant O(1) time for PHP5.5+
6965
		if ( function_exists( 'array_column' ) ) {
6966
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6967
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6968
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6969
			return ! empty ( $intersection );
6970
		}
6971
6972
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6973
		foreach ( $backtrace as $call ) {
6974
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6975
				return true;
6976
			}
6977
		}
6978
		return false;
6979
	}
6980
6981
	/**
6982
	 * Given a minified path, and a non-minified path, will return
6983
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6984
	 *
6985
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6986
	 * root Jetpack directory.
6987
	 *
6988
	 * @since 5.6.0
6989
	 *
6990
	 * @param string $min_path
6991
	 * @param string $non_min_path
6992
	 * @return string The URL to the file
6993
	 */
6994
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6995
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6996
			? $non_min_path
6997
			: $min_path;
6998
6999
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
7000
	}
7001
7002
	/**
7003
	 * Checks for whether Jetpack Backup & Scan is enabled.
7004
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7005
	 * @return bool|int|mixed
7006
	 */
7007
	public static function is_rewind_enabled() {
7008
		if ( ! Jetpack::is_active() ) {
7009
			return false;
7010
		}
7011
7012
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7013
		if ( false === $rewind_enabled ) {
7014
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7015
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7016
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7017
				&& ! empty( $rewind_data['state'] )
7018
				&& 'active' === $rewind_data['state'] )
7019
				? 1
7020
				: 0;
7021
7022
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7023
		}
7024
		return $rewind_enabled;
7025
	}
7026
7027
	/**
7028
	 * Return Calypso environment value; used for developing Jetpack and pairing
7029
	 * it with different Calypso enrionments, such as localhost.
7030
	 *
7031
	 * @since 7.4.0
7032
	 *
7033
	 * @return string Calypso environment
7034
	 */
7035
	public static function get_calypso_env() {
7036
		if ( isset( $_GET['calypso_env'] ) ) {
7037
			return sanitize_key( $_GET['calypso_env'] );
7038
		}
7039
7040
		if ( getenv( 'CALYPSO_ENV' ) ) {
7041
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7042
		}
7043
7044
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7045
			return sanitize_key( CALYPSO_ENV );
7046
		}
7047
7048
		return '';
7049
	}
7050
7051
	/**
7052
	 * Checks whether or not TOS has been agreed upon.
7053
	 * Will return true if a user has clicked to register, or is already connected.
7054
	 */
7055
	public static function jetpack_tos_agreed() {
7056
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7057
	}
7058
7059
	/**
7060
	 * Handles activating default modules as well general cleanup for the new connection.
7061
	 *
7062
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7063
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7064
	 * @param boolean $send_state_messages          Whether to send state messages.
7065
	 * @return void
7066
	 */
7067
	public static function handle_post_authorization_actions(
7068
		$activate_sso = false,
7069
		$redirect_on_activation_error = false,
7070
		$send_state_messages = true
7071
	) {
7072
		$other_modules = $activate_sso
7073
			? array( 'sso' )
7074
			: array();
7075
7076
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7077
			Jetpack::delete_active_modules();
7078
7079
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7080
		} else {
7081
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7082
		}
7083
7084
		// Since this is a fresh connection, be sure to clear out IDC options
7085
		Jetpack_IDC::clear_all_idc_options();
7086
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7087
7088
		// Start nonce cleaner
7089
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7090
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7091
7092
		if ( $send_state_messages ) {
7093
			Jetpack::state( 'message', 'authorized' );
7094
		}
7095
	}
7096
7097
	/**
7098
	 * Returns a boolean for whether backups UI should be displayed or not.
7099
	 *
7100
	 * @return bool Should backups UI be displayed?
7101
	 */
7102
	public static function show_backups_ui() {
7103
		/**
7104
		 * Whether UI for backups should be displayed.
7105
		 *
7106
		 * @since 6.5.0
7107
		 *
7108
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7109
		 */
7110
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7111
	}
7112
7113
	/*
7114
	 * Deprecated manage functions
7115
	 */
7116
	function prepare_manage_jetpack_notice() {
7117
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7118
	}
7119
	function manage_activate_screen() {
7120
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7121
	}
7122
	function admin_jetpack_manage_notice() {
7123
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7124
	}
7125
	function opt_out_jetpack_manage_url() {
7126
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7127
	}
7128
	function opt_in_jetpack_manage_url() {
7129
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7130
	}
7131
	function opt_in_jetpack_manage_notice() {
7132
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7133
	}
7134
	function can_display_jetpack_manage_notice() {
7135
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7136
	}
7137
7138
	/**
7139
	 * Clean leftoveruser meta.
7140
	 *
7141
	 * Delete Jetpack-related user meta when it is no longer needed.
7142
	 *
7143
	 * @since 7.3.0
7144
	 *
7145
	 * @param int $user_id User ID being updated.
7146
	 */
7147
	public static function user_meta_cleanup( $user_id ) {
7148
		$meta_keys = array(
7149
			// AtD removed from Jetpack 7.3
7150
			'AtD_options',
7151
			'AtD_check_when',
7152
			'AtD_guess_lang',
7153
			'AtD_ignored_phrases',
7154
		);
7155
7156
		foreach ( $meta_keys as $meta_key ) {
7157
			if ( get_user_meta( $user_id, $meta_key ) ) {
7158
				delete_user_meta( $user_id, $meta_key );
7159
			}
7160
		}
7161
	}
7162
7163
	function is_active_and_not_development_mode( $maybe ) {
7164
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7165
			return false;
7166
		}
7167
		return true;
7168
	}
7169
7170
}
7171