PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 14.4
Jetpack – WP Security, Backup, Speed, & Growth v14.4
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / class.jetpack.php

class.jetpack.php in Jetpack – WP Security, Backup, Speed, & Growth 14.4, at class.jetpack.php

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