PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.6.4
Jetpack – WP Security, Backup, Speed, & Growth v7.6.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 7.6.4, at class.jetpack.php

7,213 lines 234.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4 use Automattic\Jetpack\Connection\Client;
5 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6 use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7 use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8 use Automattic\Jetpack\Constants;
9 use Automattic\Jetpack\Roles;
10 use Automattic\Jetpack\Sync\Functions;
11 use Automattic\Jetpack\Sync\Sender;
12 use Automattic\Jetpack\Sync\Users;
13 use Automattic\Jetpack\Tracking;
14 use Automattic\Jetpack\Assets;
15
16 /*
17 Options:
18 jetpack_options (array)
19 An array of options.
20 @see Jetpack_Options::get_option_names()
21
22 jetpack_register (string)
23 Temporary verification secrets.
24
25 jetpack_activated (int)
26 1: the plugin was activated normally
27 2: the plugin was activated on this site because of a network-wide activation
28 3: the plugin was auto-installed
29 4: the plugin was manually disconnected (but is still installed)
30
31 jetpack_active_modules (array)
32 Array of active module slugs.
33
34 jetpack_do_activate (bool)
35 Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36 */
37
38 require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40 class Jetpack {
41 public $xmlrpc_server = null;
42
43 private $xmlrpc_verification = null;
44 private $rest_authentication_status = null;
45
46 public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
47
48 private $tracking;
49
50 /**
51 * @var array The handles of styles that are concatenated into jetpack.css.
52 *
53 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
54 */
55 public $concatenated_style_handles = array(
56 'jetpack-carousel',
57 'grunion.css',
58 'the-neverending-homepage',
59 'jetpack_likes',
60 'jetpack_related-posts',
61 'sharedaddy',
62 'jetpack-slideshow',
63 'presentations',
64 'quiz',
65 'jetpack-subscriptions',
66 'jetpack-responsive-videos-style',
67 'jetpack-social-menu',
68 'tiled-gallery',
69 'jetpack_display_posts_widget',
70 'gravatar-profile-widget',
71 'goodreads-widget',
72 'jetpack_social_media_icons_widget',
73 'jetpack-top-posts-widget',
74 'jetpack_image_widget',
75 'jetpack-my-community-widget',
76 'jetpack-authors-widget',
77 'wordads',
78 'eu-cookie-law-style',
79 'flickr-widget-style',
80 'jetpack-search-widget',
81 'jetpack-simple-payments-widget-style',
82 'jetpack-widget-social-icons-styles',
83 );
84
85 /**
86 * Contains all assets that have had their URL rewritten to minified versions.
87 *
88 * @var array
89 */
90 static $min_assets = array();
91
92 public $plugins_to_deactivate = array(
93 'stats' => array( 'stats/stats.php', 'WordPress.com Stats' ),
94 'shortlinks' => array( 'stats/stats.php', 'WordPress.com Stats' ),
95 'sharedaddy' => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
96 'twitter-widget' => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
97 'contact-form' => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
98 'contact-form' => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
99 'custom-css' => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
100 'random-redirect' => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
101 'videopress' => array( 'video/video.php', 'VideoPress' ),
102 'widget-visibility' => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
103 'widget-visibility' => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
104 'sharedaddy' => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
105 'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
106 'latex' => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
107 );
108
109 /**
110 * Map of roles we care about, and their corresponding minimum capabilities.
111 *
112 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
113 *
114 * @access public
115 * @static
116 *
117 * @var array
118 */
119 public static $capability_translations = array(
120 'administrator' => 'manage_options',
121 'editor' => 'edit_others_posts',
122 'author' => 'publish_posts',
123 'contributor' => 'edit_posts',
124 'subscriber' => 'read',
125 );
126
127 /**
128 * Map of modules that have conflicts with plugins and should not be auto-activated
129 * if the plugins are active. Used by filter_default_modules
130 *
131 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
132 * change `module-slug` and add this to your plugin:
133 *
134 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
135 * function my_jetpack_get_default_modules( $modules ) {
136 * return array_diff( $modules, array( 'module-slug' ) );
137 * }
138 *
139 * @var array
140 */
141 private $conflicting_plugins = array(
142 'comments' => array(
143 'Intense Debate' => 'intensedebate/intensedebate.php',
144 'Disqus' => 'disqus-comment-system/disqus.php',
145 'Livefyre' => 'livefyre-comments/livefyre.php',
146 'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
147 'Google+ Comments' => 'google-plus-comments/google-plus-comments.php',
148 'WP-SpamShield Anti-Spam' => 'wp-spamshield/wp-spamshield.php',
149 ),
150 'comment-likes' => array(
151 'Epoch' => 'epoch/plugincore.php',
152 ),
153 'contact-form' => array(
154 'Contact Form 7' => 'contact-form-7/wp-contact-form-7.php',
155 'Gravity Forms' => 'gravityforms/gravityforms.php',
156 'Contact Form Plugin' => 'contact-form-plugin/contact_form.php',
157 'Easy Contact Forms' => 'easy-contact-forms/easy-contact-forms.php',
158 'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
159 'Ninja Forms' => 'ninja-forms/ninja-forms.php',
160 ),
161 'minileven' => array(
162 'WPtouch' => 'wptouch/wptouch.php',
163 ),
164 'latex' => array(
165 'LaTeX for WordPress' => 'latex/latex.php',
166 'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
167 'Easy WP LaTeX' => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
168 'MathJax-LaTeX' => 'mathjax-latex/mathjax-latex.php',
169 'Enable Latex' => 'enable-latex/enable-latex.php',
170 'WP QuickLaTeX' => 'wp-quicklatex/wp-quicklatex.php',
171 ),
172 'protect' => array(
173 'Limit Login Attempts' => 'limit-login-attempts/limit-login-attempts.php',
174 'Captcha' => 'captcha/captcha.php',
175 'Brute Force Login Protection' => 'brute-force-login-protection/brute-force-login-protection.php',
176 'Login Security Solution' => 'login-security-solution/login-security-solution.php',
177 'WPSecureOps Brute Force Protect' => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
178 'BulletProof Security' => 'bulletproof-security/bulletproof-security.php',
179 'SiteGuard WP Plugin' => 'siteguard/siteguard.php',
180 'Security-protection' => 'security-protection/security-protection.php',
181 'Login Security' => 'login-security/login-security.php',
182 'Botnet Attack Blocker' => 'botnet-attack-blocker/botnet-attack-blocker.php',
183 'Wordfence Security' => 'wordfence/wordfence.php',
184 'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
185 'iThemes Security' => 'better-wp-security/better-wp-security.php',
186 ),
187 'random-redirect' => array(
188 'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
189 ),
190 'related-posts' => array(
191 'YARPP' => 'yet-another-related-posts-plugin/yarpp.php',
192 'WordPress Related Posts' => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
193 'nrelate Related Content' => 'nrelate-related-content/nrelate-related.php',
194 'Contextual Related Posts' => 'contextual-related-posts/contextual-related-posts.php',
195 'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
196 'outbrain' => 'outbrain/outbrain.php',
197 'Shareaholic' => 'shareaholic/shareaholic.php',
198 'Sexybookmarks' => 'sexybookmarks/shareaholic.php',
199 ),
200 'sharedaddy' => array(
201 'AddThis' => 'addthis/addthis_social_widget.php',
202 'Add To Any' => 'add-to-any/add-to-any.php',
203 'ShareThis' => 'share-this/sharethis.php',
204 'Shareaholic' => 'shareaholic/shareaholic.php',
205 ),
206 'seo-tools' => array(
207 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
208 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
209 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210 'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211 'The SEO Framework' => 'autodescription/autodescription.php',
212 ),
213 'verification-tools' => array(
214 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
215 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
216 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217 'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218 'The SEO Framework' => 'autodescription/autodescription.php',
219 ),
220 'widget-visibility' => array(
221 'Widget Logic' => 'widget-logic/widget_logic.php',
222 'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
223 ),
224 'sitemaps' => array(
225 'Google XML Sitemaps' => 'google-sitemap-generator/sitemap.php',
226 'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
227 'Google XML Sitemaps for qTranslate' => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
228 'XML Sitemap & Google News feeds' => 'xml-sitemap-feed/xml-sitemap.php',
229 'Google Sitemap by BestWebSoft' => 'google-sitemap-plugin/google-sitemap-plugin.php',
230 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
231 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
232 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
233 'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
234 'The SEO Framework' => 'autodescription/autodescription.php',
235 'Sitemap' => 'sitemap/sitemap.php',
236 'Simple Wp Sitemap' => 'simple-wp-sitemap/simple-wp-sitemap.php',
237 'Simple Sitemap' => 'simple-sitemap/simple-sitemap.php',
238 'XML Sitemaps' => 'xml-sitemaps/xml-sitemaps.php',
239 'MSM Sitemaps' => 'msm-sitemap/msm-sitemap.php',
240 ),
241 'lazy-images' => array(
242 'Lazy Load' => 'lazy-load/lazy-load.php',
243 'BJ Lazy Load' => 'bj-lazy-load/bj-lazy-load.php',
244 'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
245 ),
246 );
247
248 /**
249 * Plugins for which we turn off our Facebook OG Tags implementation.
250 *
251 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
252 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
253 *
254 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
255 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
256 */
257 private $open_graph_conflicting_plugins = array(
258 '2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
259 // 2 Click Social Media Buttons
260 'add-link-to-facebook/add-link-to-facebook.php', // Add Link to Facebook
261 'add-meta-tags/add-meta-tags.php', // Add Meta Tags
262 'easy-facebook-share-thumbnails/esft.php', // Easy Facebook Share Thumbnail
263 'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
264 // Open Graph Meta Tags by Heateor
265 'facebook/facebook.php', // Facebook (official plugin)
266 'facebook-awd/AWD_facebook.php', // Facebook AWD All in one
267 'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
268 // Facebook Featured Image & OG Meta Tags
269 'facebook-meta-tags/facebook-metatags.php', // Facebook Meta Tags
270 'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
271 // Facebook Open Graph Meta Tags for WordPress
272 'facebook-revised-open-graph-meta-tag/index.php', // Facebook Revised Open Graph Meta Tag
273 'facebook-thumb-fixer/_facebook-thumb-fixer.php', // Facebook Thumb Fixer
274 'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
275 // Fedmich's Facebook Open Graph Meta
276 'network-publisher/networkpub.php', // Network Publisher
277 'nextgen-facebook/nextgen-facebook.php', // NextGEN Facebook OG
278 'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
279 // NextScripts SNAP
280 'og-tags/og-tags.php', // OG Tags
281 'opengraph/opengraph.php', // Open Graph
282 'open-graph-protocol-framework/open-graph-protocol-framework.php',
283 // Open Graph Protocol Framework
284 'seo-facebook-comments/seofacebook.php', // SEO Facebook Comments
285 'seo-ultimate/seo-ultimate.php', // SEO Ultimate
286 'sexybookmarks/sexy-bookmarks.php', // Shareaholic
287 'shareaholic/sexy-bookmarks.php', // Shareaholic
288 'sharepress/sharepress.php', // SharePress
289 'simple-facebook-connect/sfc.php', // Simple Facebook Connect
290 'social-discussions/social-discussions.php', // Social Discussions
291 'social-sharing-toolkit/social_sharing_toolkit.php', // Social Sharing Toolkit
292 'socialize/socialize.php', // Socialize
293 'squirrly-seo/squirrly.php', // SEO by SQUIRRLY™
294 'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
295 // Tweet, Like, Google +1 and Share
296 'wordbooker/wordbooker.php', // Wordbooker
297 'wpsso/wpsso.php', // WordPress Social Sharing Optimization
298 'wp-caregiver/wp-caregiver.php', // WP Caregiver
299 'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
300 // WP Facebook Like Send & Open Graph Meta
301 'wp-facebook-open-graph-protocol/wp-facebook-ogp.php', // WP Facebook Open Graph protocol
302 'wp-ogp/wp-ogp.php', // WP-OGP
303 'zoltonorg-social-plugin/zosp.php', // Zolton.org Social Plugin
304 'wp-fb-share-like-button/wp_fb_share-like_widget.php', // WP Facebook Like Button
305 'open-graph-metabox/open-graph-metabox.php' // Open Graph Metabox
306 );
307
308 /**
309 * Plugins for which we turn off our Twitter Cards Tags implementation.
310 */
311 private $twitter_cards_conflicting_plugins = array(
312 // 'twitter/twitter.php', // The official one handles this on its own.
313 // // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
314 'eewee-twitter-card/index.php', // Eewee Twitter Card
315 'ig-twitter-cards/ig-twitter-cards.php', // IG:Twitter Cards
316 'jm-twitter-cards/jm-twitter-cards.php', // JM Twitter Cards
317 'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
318 // Pure Web Brilliant's Social Graph Twitter Cards Extension
319 'twitter-cards/twitter-cards.php', // Twitter Cards
320 'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
321 'wp-to-twitter/wp-to-twitter.php', // WP to Twitter
322 'wp-twitter-cards/twitter_cards.php', // WP Twitter Cards
323 );
324
325 /**
326 * Message to display in admin_notice
327 * @var string
328 */
329 public $message = '';
330
331 /**
332 * Error to display in admin_notice
333 * @var string
334 */
335 public $error = '';
336
337 /**
338 * Modules that need more privacy description.
339 * @var string
340 */
341 public $privacy_checks = '';
342
343 /**
344 * Stats to record once the page loads
345 *
346 * @var array
347 */
348 public $stats = array();
349
350 /**
351 * Jetpack_Sync object
352 */
353 public $sync;
354
355 /**
356 * Verified data for JSON authorization request
357 */
358 public $json_api_authorization_request = array();
359
360 /**
361 * @var \Automattic\Jetpack\Connection\Manager
362 */
363 protected $connection_manager;
364
365 /**
366 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
367 */
368 public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
369
370 /**
371 * Holds the singleton instance of this class
372 * @since 2.3.3
373 * @var Jetpack
374 */
375 static $instance = false;
376
377 /**
378 * Singleton
379 * @static
380 */
381 public static function init() {
382 if ( ! self::$instance ) {
383 self::$instance = new Jetpack;
384
385 self::$instance->plugin_upgrade();
386 }
387
388 return self::$instance;
389 }
390
391 /**
392 * Must never be called statically
393 */
394 function plugin_upgrade() {
395 if ( Jetpack::is_active() ) {
396 list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
397 if ( JETPACK__VERSION != $version ) {
398 // Prevent multiple upgrades at once - only a single process should trigger
399 // an upgrade to avoid stampedes
400 if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
401 return;
402 }
403
404 // Set a short lock to prevent multiple instances of the upgrade
405 set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
406
407 // check which active modules actually exist and remove others from active_modules list
408 $unfiltered_modules = Jetpack::get_active_modules();
409 $modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
410 if ( array_diff( $unfiltered_modules, $modules ) ) {
411 Jetpack::update_active_modules( $modules );
412 }
413
414 add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
415
416 // Upgrade to 4.3.0
417 if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
418 Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
419 }
420
421 // Make sure Markdown for posts gets turned back on
422 if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
423 update_option( 'wpcom_publish_posts_with_markdown', true );
424 }
425
426 if ( did_action( 'wp_loaded' ) ) {
427 self::upgrade_on_load();
428 } else {
429 add_action(
430 'wp_loaded',
431 array( __CLASS__, 'upgrade_on_load' )
432 );
433 }
434 }
435 }
436 }
437
438 /**
439 * Runs upgrade routines that need to have modules loaded.
440 */
441 static function upgrade_on_load() {
442
443 // Not attempting any upgrades if jetpack_modules_loaded did not fire.
444 // This can happen in case Jetpack has been just upgraded and is
445 // being initialized late during the page load. In this case we wait
446 // until the next proper admin page load with Jetpack active.
447 if ( ! did_action( 'jetpack_modules_loaded' ) ) {
448 delete_transient( self::$plugin_upgrade_lock_key );
449
450 return;
451 }
452
453 Jetpack::maybe_set_version_option();
454
455 if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
456 Jetpack_Widget_Conditions::migrate_post_type_rules();
457 }
458
459 if (
460 class_exists( 'Jetpack_Sitemap_Manager' )
461 && version_compare( JETPACK__VERSION, '5.3', '>=' )
462 ) {
463 do_action( 'jetpack_sitemaps_purge_data' );
464 }
465
466 // Delete old stats cache
467 delete_option( 'jetpack_restapi_stats_cache' );
468
469 delete_transient( self::$plugin_upgrade_lock_key );
470 }
471
472 /**
473 * Saves all the currently active modules to options.
474 * Also fires Action hooks for each newly activated and deactivated module.
475 *
476 * @param $modules Array Array of active modules to be saved in options.
477 *
478 * @return $success bool true for success, false for failure.
479 */
480 static function update_active_modules( $modules ) {
481 $current_modules = Jetpack_Options::get_option( 'active_modules', array() );
482 $active_modules = Jetpack::get_active_modules();
483 $new_active_modules = array_diff( $modules, $current_modules );
484 $new_inactive_modules = array_diff( $active_modules, $modules );
485 $new_current_modules = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
486 $reindexed_modules = array_values( $new_current_modules );
487 $success = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
488
489 foreach ( $new_active_modules as $module ) {
490 /**
491 * Fires when a specific module is activated.
492 *
493 * @since 1.9.0
494 *
495 * @param string $module Module slug.
496 * @param boolean $success whether the module was activated. @since 4.2
497 */
498 do_action( 'jetpack_activate_module', $module, $success );
499 /**
500 * Fires when a module is activated.
501 * The dynamic part of the filter, $module, is the module slug.
502 *
503 * @since 1.9.0
504 *
505 * @param string $module Module slug.
506 */
507 do_action( "jetpack_activate_module_$module", $module );
508 }
509
510 foreach ( $new_inactive_modules as $module ) {
511 /**
512 * Fired after a module has been deactivated.
513 *
514 * @since 4.2.0
515 *
516 * @param string $module Module slug.
517 * @param boolean $success whether the module was deactivated.
518 */
519 do_action( 'jetpack_deactivate_module', $module, $success );
520 /**
521 * Fires when a module is deactivated.
522 * The dynamic part of the filter, $module, is the module slug.
523 *
524 * @since 1.9.0
525 *
526 * @param string $module Module slug.
527 */
528 do_action( "jetpack_deactivate_module_$module", $module );
529 }
530
531 return $success;
532 }
533
534 static function delete_active_modules() {
535 self::update_active_modules( array() );
536 }
537
538 /**
539 * Constructor. Initializes WordPress hooks
540 */
541 private function __construct() {
542 /*
543 * Check for and alert any deprecated hooks
544 */
545 add_action( 'init', array( $this, 'deprecated_hooks' ) );
546
547 /*
548 * Enable enhanced handling of previewing sites in Calypso
549 */
550 if ( Jetpack::is_active() ) {
551 require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
552 add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
553 require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
554 add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
555 }
556
557 if ( self::jetpack_tos_agreed() ) {
558 $tracking = new Automattic\Jetpack\Plugin\Tracking();
559 add_action( 'init', array( $tracking, 'init' ) );
560 }
561
562 /*
563 * Load things that should only be in Network Admin.
564 *
565 * For now blow away everything else until a more full
566 * understanding of what is needed at the network level is
567 * available
568 */
569 if ( is_multisite() ) {
570 Jetpack_Network::init();
571 }
572
573 add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
574 return function() {
575 return wp_generate_password( 32, false );
576 };
577 } );
578
579 $this->connection_manager = new Connection_Manager( );
580
581 /**
582 * Prepare Gutenberg Editor functionality
583 */
584 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
585 Jetpack_Gutenberg::init();
586 Jetpack_Gutenberg::load_independent_blocks();
587 add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
588
589 add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
590
591 // Unlink user before deleting the user from .com
592 add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
593 add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
594
595 $is_jetpack_xmlrpc_request = $this->setup_xmlrpc_handlers( $_GET, Jetpack::is_active(), $this->verify_xml_rpc_signature() );
596
597 if ( $is_jetpack_xmlrpc_request ) {
598 // pass
599 } elseif (
600 is_admin() &&
601 isset( $_POST['action'] ) && (
602 'jetpack_upload_file' == $_POST['action'] ||
603 'jetpack_update_file' == $_POST['action']
604 )
605 ) {
606 $this->require_jetpack_authentication();
607 $this->add_remote_request_handlers();
608 } else {
609 if ( Jetpack::is_active() ) {
610 add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
611 add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
612 } else {
613 add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
614 }
615 }
616
617 if ( Jetpack::is_active() ) {
618 Jetpack_Heartbeat::init();
619 if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
620 require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
621 Jetpack_Search_Performance_Logger::init();
622 }
623 }
624
625 add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
626 add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
627
628 add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
629 if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
630 wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
631 }
632
633 add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
634
635 add_action( 'admin_init', array( $this, 'admin_init' ) );
636 add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
637
638 add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
639
640 add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
641 // Filter the dashboard meta box order to swap the new one in in place of the old one.
642 add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
643
644 // returns HTTPS support status
645 add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
646
647 // JITM AJAX callback function
648 add_action( 'wp_ajax_jitm_ajax', array( $this, 'jetpack_jitm_ajax_callback' ) );
649
650 add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
651
652 add_action( 'wp_loaded', array( $this, 'register_assets' ) );
653 add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
654 add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
655 add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
656
657 add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
658
659 /**
660 * These actions run checks to load additional files.
661 * They check for external files or plugins, so they need to run as late as possible.
662 */
663 add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
664 add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
665 add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
666
667 add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
668 add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
669 add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
670
671 add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
672 add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
673
674 add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
675 add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
676
677 // A filter to control all just in time messages
678 add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
679
680 add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
681
682 // If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
683 // We should make sure to only do this for front end links.
684 if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
685 add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
686 add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
687
688 //we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
689 //so they point moderation links on emails to Calypso
690 jetpack_require_lib( 'functions.wp-notify' );
691 }
692
693 // Hide edit post link if mobile app.
694 if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
695 add_filter( 'edit_post_link', '__return_empty_string' );
696 }
697
698 // Update the Jetpack plan from API on heartbeats
699 add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
700
701 /**
702 * This is the hack to concatenate all css files into one.
703 * For description and reasoning see the implode_frontend_css method
704 *
705 * Super late priority so we catch all the registered styles
706 */
707 if( !is_admin() ) {
708 add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
709 add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
710 }
711
712
713 /**
714 * These are sync actions that we need to keep track of for jitms
715 */
716 add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
717
718 // Actually push the stats on shutdown.
719 if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
720 add_action( 'shutdown', array( $this, 'push_stats' ) );
721 }
722 }
723
724 function setup_xmlrpc_handlers( $request_params, $is_active, $is_signed, Jetpack_XMLRPC_Server $xmlrpc_server = null ) {
725 if ( ! isset( $request_params['for'] ) || 'jetpack' != $request_params['for'] ) {
726 return false;
727 }
728
729 // Alternate XML-RPC, via ?for=jetpack&jetpack=comms
730 if ( isset( $request_params['jetpack'] ) && 'comms' == $request_params['jetpack'] ) {
731 if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
732 // Use the real constant here for WordPress' sake.
733 define( 'XMLRPC_REQUEST', true );
734 }
735
736 add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
737
738 add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
739 }
740
741 if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
742 return false;
743 }
744
745 @ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
746
747 if ( $xmlrpc_server ) {
748 $this->xmlrpc_server = $xmlrpc_server;
749 } else {
750 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
751 $this->xmlrpc_server = new Jetpack_XMLRPC_Server();
752 }
753
754 $this->require_jetpack_authentication();
755
756 if ( $is_active ) {
757 // Hack to preserve $HTTP_RAW_POST_DATA
758 add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
759
760 if ( $is_signed ) {
761 // The actual API methods.
762 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
763 } else {
764 // The jetpack.authorize method should be available for unauthenticated users on a site with an
765 // active Jetpack connection, so that additional users can link their account.
766 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
767 }
768 } else {
769 // The bootstrap API methods.
770 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
771
772 new XMLRPC_Connector( $this->connection_manager );
773
774 if ( $is_signed ) {
775 // the jetpack Provision method is available for blog-token-signed requests
776 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
777 }
778 }
779
780 // Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
781 add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
782
783 return true;
784 }
785
786 function initialize_rest_api_registration_connector() {
787 new REST_Connector( $this->connection_manager );
788 }
789
790 /**
791 * This is ported over from the manage module, which has been deprecated and baked in here.
792 *
793 * @param $domains
794 */
795 function add_wpcom_to_allowed_redirect_hosts( $domains ) {
796 add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
797 }
798
799 /**
800 * Return $domains, with 'wordpress.com' appended.
801 * This is ported over from the manage module, which has been deprecated and baked in here.
802 *
803 * @param $domains
804 * @return array
805 */
806 function allow_wpcom_domain( $domains ) {
807 if ( empty( $domains ) ) {
808 $domains = array();
809 }
810 $domains[] = 'wordpress.com';
811 return array_unique( $domains );
812 }
813
814 function point_edit_post_links_to_calypso( $default_url, $post_id ) {
815 $post = get_post( $post_id );
816
817 if ( empty( $post ) ) {
818 return $default_url;
819 }
820
821 $post_type = $post->post_type;
822
823 // Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
824 // https://en.support.wordpress.com/custom-post-types/
825 $allowed_post_types = array(
826 'post' => 'post',
827 'page' => 'page',
828 'jetpack-portfolio' => 'edit/jetpack-portfolio',
829 'jetpack-testimonial' => 'edit/jetpack-testimonial',
830 );
831
832 if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
833 return $default_url;
834 }
835
836 $path_prefix = $allowed_post_types[ $post_type ];
837
838 $site_slug = Jetpack::build_raw_urls( get_home_url() );
839
840 return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
841 }
842
843 function point_edit_comment_links_to_calypso( $url ) {
844 // Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
845 wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
846 return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
847 Jetpack::build_raw_urls( get_home_url() ),
848 $query_args['amp;c']
849 ) );
850 }
851
852 function jetpack_track_last_sync_callback( $params ) {
853 /**
854 * Filter to turn off jitm caching
855 *
856 * @since 5.4.0
857 *
858 * @param bool false Whether to cache just in time messages
859 */
860 if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
861 return $params;
862 }
863
864 if ( is_array( $params ) && isset( $params[0] ) ) {
865 $option = $params[0];
866 if ( 'active_plugins' === $option ) {
867 // use the cache if we can, but not terribly important if it gets evicted
868 set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
869 }
870 }
871
872 return $params;
873 }
874
875 function jetpack_connection_banner_callback() {
876 check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
877
878 if ( isset( $_REQUEST['dismissBanner'] ) ) {
879 Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
880 wp_send_json_success();
881 }
882
883 wp_die();
884 }
885
886 /**
887 * Removes all XML-RPC methods that are not `jetpack.*`.
888 * Only used in our alternate XML-RPC endpoint, where we want to
889 * ensure that Core and other plugins' methods are not exposed.
890 *
891 * @param array $methods
892 * @return array filtered $methods
893 */
894 function remove_non_jetpack_xmlrpc_methods( $methods ) {
895 $jetpack_methods = array();
896
897 foreach ( $methods as $method => $callback ) {
898 if ( 0 === strpos( $method, 'jetpack.' ) ) {
899 $jetpack_methods[ $method ] = $callback;
900 }
901 }
902
903 return $jetpack_methods;
904 }
905
906 /**
907 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
908 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
909 * security/firewall policies, we provide our own alternate XML RPC API endpoint
910 * which is accessible via a different URI. Most of the below is copied directly
911 * from /xmlrpc.php so that we're replicating it as closely as possible.
912 */
913 function alternate_xmlrpc() {
914 // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
915 global $HTTP_RAW_POST_DATA;
916
917 // Some browser-embedded clients send cookies. We don't want them.
918 $_COOKIE = array();
919
920 // A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
921 // but we can do it ourself.
922 if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
923 $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
924 }
925
926 // fix for mozBlog and other cases where '<?xml' isn't on the very first line
927 if ( isset( $HTTP_RAW_POST_DATA ) ) {
928 $HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
929 }
930
931 // phpcs:enable
932
933 include_once( ABSPATH . 'wp-admin/includes/admin.php' );
934 include_once( ABSPATH . WPINC . '/class-IXR.php' );
935 include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
936
937 /**
938 * Filters the class used for handling XML-RPC requests.
939 *
940 * @since 3.1.0
941 *
942 * @param string $class The name of the XML-RPC server class.
943 */
944 $wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
945 $wp_xmlrpc_server = new $wp_xmlrpc_server_class;
946
947 // Fire off the request
948 nocache_headers();
949 $wp_xmlrpc_server->serve_request();
950
951 exit;
952 }
953
954 /**
955 * The callback for the JITM ajax requests.
956 */
957 function jetpack_jitm_ajax_callback() {
958 // Check for nonce
959 if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
960 wp_die( 'Module activation failed due to lack of appropriate permissions' );
961 }
962 if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
963 $module_slug = $_REQUEST['jitmModule'];
964 Jetpack::log( 'activate', $module_slug );
965 Jetpack::activate_module( $module_slug, false, false );
966 Jetpack::state( 'message', 'no_message' );
967
968 //A Jetpack module is being activated through a JITM, track it
969 $this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
970 $this->do_stats( 'server_side' );
971
972 wp_send_json_success();
973 }
974 if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
975 // get the hide_jitm options array
976 $jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
977 $module_slug = $_REQUEST['jitmModule'];
978
979 if( ! $jetpack_hide_jitm ) {
980 $jetpack_hide_jitm = array(
981 $module_slug => 'hide'
982 );
983 } else {
984 $jetpack_hide_jitm[$module_slug] = 'hide';
985 }
986
987 Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
988
989 //jitm is being dismissed forever, track it
990 $this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
991 $this->do_stats( 'server_side' );
992
993 wp_send_json_success();
994 }
995 if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
996 $module_slug = $_REQUEST['jitmModule'];
997
998 // User went to WordPress.com, track this
999 $this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
1000 $this->do_stats( 'server_side' );
1001
1002 wp_send_json_success();
1003 }
1004 if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
1005 $track = $_REQUEST['jitmModule'];
1006
1007 // User is viewing JITM, track it.
1008 $this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
1009 $this->do_stats( 'server_side' );
1010
1011 wp_send_json_success();
1012 }
1013 }
1014
1015 /**
1016 * If there are any stats that need to be pushed, but haven't been, push them now.
1017 */
1018 function push_stats() {
1019 if ( ! empty( $this->stats ) ) {
1020 $this->do_stats( 'server_side' );
1021 }
1022 }
1023
1024 function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1025 switch( $cap ) {
1026 case 'jetpack_connect' :
1027 case 'jetpack_reconnect' :
1028 if ( Jetpack::is_development_mode() ) {
1029 $caps = array( 'do_not_allow' );
1030 break;
1031 }
1032 /**
1033 * Pass through. If it's not development mode, these should match disconnect.
1034 * Let users disconnect if it's development mode, just in case things glitch.
1035 */
1036 case 'jetpack_disconnect' :
1037 /**
1038 * In multisite, can individual site admins manage their own connection?
1039 *
1040 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1041 */
1042 if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1043 if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1044 /**
1045 * We need to update the option name -- it's terribly unclear which
1046 * direction the override goes.
1047 *
1048 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1049 */
1050 $caps = array( 'do_not_allow' );
1051 break;
1052 }
1053 }
1054
1055 $caps = array( 'manage_options' );
1056 break;
1057 case 'jetpack_manage_modules' :
1058 case 'jetpack_activate_modules' :
1059 case 'jetpack_deactivate_modules' :
1060 $caps = array( 'manage_options' );
1061 break;
1062 case 'jetpack_configure_modules' :
1063 $caps = array( 'manage_options' );
1064 break;
1065 case 'jetpack_manage_autoupdates' :
1066 $caps = array(
1067 'manage_options',
1068 'update_plugins',
1069 );
1070 break;
1071 case 'jetpack_network_admin_page':
1072 case 'jetpack_network_settings_page':
1073 $caps = array( 'manage_network_plugins' );
1074 break;
1075 case 'jetpack_network_sites_page':
1076 $caps = array( 'manage_sites' );
1077 break;
1078 case 'jetpack_admin_page' :
1079 if ( Jetpack::is_development_mode() ) {
1080 $caps = array( 'manage_options' );
1081 break;
1082 } else {
1083 $caps = array( 'read' );
1084 }
1085 break;
1086 case 'jetpack_connect_user' :
1087 if ( Jetpack::is_development_mode() ) {
1088 $caps = array( 'do_not_allow' );
1089 break;
1090 }
1091 $caps = array( 'read' );
1092 break;
1093 }
1094 return $caps;
1095 }
1096
1097 function require_jetpack_authentication() {
1098 // Don't let anyone authenticate
1099 $_COOKIE = array();
1100 remove_all_filters( 'authenticate' );
1101 remove_all_actions( 'wp_login_failed' );
1102
1103 if ( Jetpack::is_active() ) {
1104 // Allow Jetpack authentication
1105 add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1106 }
1107 }
1108
1109 /**
1110 * Load language files
1111 * @action plugins_loaded
1112 */
1113 public static function plugin_textdomain() {
1114 // Note to self, the third argument must not be hardcoded, to account for relocated folders.
1115 load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1116 }
1117
1118 /**
1119 * Register assets for use in various modules and the Jetpack admin page.
1120 *
1121 * @uses wp_script_is, wp_register_script, plugins_url
1122 * @action wp_loaded
1123 * @return null
1124 */
1125 public function register_assets() {
1126 if ( ! wp_script_is( 'spin', 'registered' ) ) {
1127 wp_register_script(
1128 'spin',
1129 Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1130 false,
1131 '1.3'
1132 );
1133 }
1134
1135 if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1136 wp_register_script(
1137 'jquery.spin',
1138 Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1139 array( 'jquery', 'spin' ),
1140 '1.3'
1141 );
1142 }
1143
1144 if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1145 wp_register_script(
1146 'jetpack-gallery-settings',
1147 Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1148 array( 'media-views' ),
1149 '20121225'
1150 );
1151 }
1152
1153 if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1154 wp_register_script(
1155 'jetpack-twitter-timeline',
1156 Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1157 array( 'jquery' ),
1158 '4.0.0',
1159 true
1160 );
1161 }
1162
1163 if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1164 wp_register_script(
1165 'jetpack-facebook-embed',
1166 Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1167 array( 'jquery' ),
1168 null,
1169 true
1170 );
1171
1172 /** This filter is documented in modules/sharedaddy/sharing-sources.php */
1173 $fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1174 if ( ! is_numeric( $fb_app_id ) ) {
1175 $fb_app_id = '';
1176 }
1177 wp_localize_script(
1178 'jetpack-facebook-embed',
1179 'jpfbembed',
1180 array(
1181 'appid' => $fb_app_id,
1182 'locale' => $this->get_locale(),
1183 )
1184 );
1185 }
1186
1187 /**
1188 * As jetpack_register_genericons is by default fired off a hook,
1189 * the hook may have already fired by this point.
1190 * So, let's just trigger it manually.
1191 */
1192 require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1193 jetpack_register_genericons();
1194
1195 /**
1196 * Register the social logos
1197 */
1198 require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1199 jetpack_register_social_logos();
1200
1201 if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1202 wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1203 }
1204
1205 /**
1206 * Guess locale from language code.
1207 *
1208 * @param string $lang Language code.
1209 * @return string|bool
1210 */
1211 function guess_locale_from_lang( $lang ) {
1212 if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1213 return 'en_US';
1214 }
1215
1216 if ( ! class_exists( 'GP_Locales' ) ) {
1217 if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1218 return false;
1219 }
1220
1221 require JETPACK__GLOTPRESS_LOCALES_PATH;
1222 }
1223
1224 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1225 // WP.com: get_locale() returns 'it'
1226 $locale = GP_Locales::by_slug( $lang );
1227 } else {
1228 // Jetpack: get_locale() returns 'it_IT';
1229 $locale = GP_Locales::by_field( 'facebook_locale', $lang );
1230 }
1231
1232 if ( ! $locale ) {
1233 return false;
1234 }
1235
1236 if ( empty( $locale->facebook_locale ) ) {
1237 if ( empty( $locale->wp_locale ) ) {
1238 return false;
1239 } else {
1240 // Facebook SDK is smart enough to fall back to en_US if a
1241 // locale isn't supported. Since supported Facebook locales
1242 // can fall out of sync, we'll attempt to use the known
1243 // wp_locale value and rely on said fallback.
1244 return $locale->wp_locale;
1245 }
1246 }
1247
1248 return $locale->facebook_locale;
1249 }
1250
1251 /**
1252 * Get the locale.
1253 *
1254 * @return string|bool
1255 */
1256 function get_locale() {
1257 $locale = $this->guess_locale_from_lang( get_locale() );
1258
1259 if ( ! $locale ) {
1260 $locale = 'en_US';
1261 }
1262
1263 return $locale;
1264 }
1265
1266 /**
1267 * Device Pixels support
1268 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1269 */
1270 function devicepx() {
1271 if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1272 wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1273 }
1274 }
1275
1276 /**
1277 * Return the network_site_url so that .com knows what network this site is a part of.
1278 * @param bool $option
1279 * @return string
1280 */
1281 public function jetpack_main_network_site_option( $option ) {
1282 return network_site_url();
1283 }
1284 /**
1285 * Network Name.
1286 */
1287 static function network_name( $option = null ) {
1288 global $current_site;
1289 return $current_site->site_name;
1290 }
1291 /**
1292 * Does the network allow new user and site registrations.
1293 * @return string
1294 */
1295 static function network_allow_new_registrations( $option = null ) {
1296 return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1297 }
1298 /**
1299 * Does the network allow admins to add new users.
1300 * @return boolian
1301 */
1302 static function network_add_new_users( $option = null ) {
1303 return (bool) get_site_option( 'add_new_users' );
1304 }
1305 /**
1306 * File upload psace left per site in MB.
1307 * -1 means NO LIMIT.
1308 * @return number
1309 */
1310 static function network_site_upload_space( $option = null ) {
1311 // value in MB
1312 return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1313 }
1314
1315 /**
1316 * Network allowed file types.
1317 * @return string
1318 */
1319 static function network_upload_file_types( $option = null ) {
1320 return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1321 }
1322
1323 /**
1324 * Maximum file upload size set by the network.
1325 * @return number
1326 */
1327 static function network_max_upload_file_size( $option = null ) {
1328 // value in KB
1329 return get_site_option( 'fileupload_maxk', 300 );
1330 }
1331
1332 /**
1333 * Lets us know if a site allows admins to manage the network.
1334 * @return array
1335 */
1336 static function network_enable_administration_menus( $option = null ) {
1337 return get_site_option( 'menu_items' );
1338 }
1339
1340 /**
1341 * If a user has been promoted to or demoted from admin, we need to clear the
1342 * jetpack_other_linked_admins transient.
1343 *
1344 * @since 4.3.2
1345 * @since 4.4.0 $old_roles is null by default and if it's not passed, the transient is cleared.
1346 *
1347 * @param int $user_id The user ID whose role changed.
1348 * @param string $role The new role.
1349 * @param array $old_roles An array of the user's previous roles.
1350 */
1351 function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1352 if ( 'administrator' == $role
1353 || ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1354 || is_null( $old_roles )
1355 ) {
1356 delete_transient( 'jetpack_other_linked_admins' );
1357 }
1358 }
1359
1360 /**
1361 * Checks to see if there are any other users available to become primary
1362 * Users must both:
1363 * - Be linked to wpcom
1364 * - Be an admin
1365 *
1366 * @return mixed False if no other users are linked, Int if there are.
1367 */
1368 static function get_other_linked_admins() {
1369 $other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1370
1371 if ( false === $other_linked_users ) {
1372 $admins = get_users( array( 'role' => 'administrator' ) );
1373 if ( count( $admins ) > 1 ) {
1374 $available = array();
1375 foreach ( $admins as $admin ) {
1376 if ( Jetpack::is_user_connected( $admin->ID ) ) {
1377 $available[] = $admin->ID;
1378 }
1379 }
1380
1381 $count_connected_admins = count( $available );
1382 if ( count( $available ) > 1 ) {
1383 $other_linked_users = $count_connected_admins;
1384 } else {
1385 $other_linked_users = 0;
1386 }
1387 } else {
1388 $other_linked_users = 0;
1389 }
1390
1391 set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1392 }
1393
1394 return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1395 }
1396
1397 /**
1398 * Return whether we are dealing with a multi network setup or not.
1399 * The reason we are type casting this is because we want to avoid the situation where
1400 * the result is false since when is_main_network_option return false it cases
1401 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1402 * database which could be set to anything as opposed to what this function returns.
1403 * @param bool $option
1404 *
1405 * @return boolean
1406 */
1407 public function is_main_network_option( $option ) {
1408 // return '1' or ''
1409 return (string) (bool) Jetpack::is_multi_network();
1410 }
1411
1412 /**
1413 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1414 *
1415 * @param string $option
1416 * @return boolean
1417 */
1418 public function is_multisite( $option ) {
1419 return (string) (bool) is_multisite();
1420 }
1421
1422 /**
1423 * Implemented since there is no core is multi network function
1424 * Right now there is no way to tell if we which network is the dominant network on the system
1425 *
1426 * @since 3.3
1427 * @return boolean
1428 */
1429 public static function is_multi_network() {
1430 global $wpdb;
1431
1432 // if we don't have a multi site setup no need to do any more
1433 if ( ! is_multisite() ) {
1434 return false;
1435 }
1436
1437 $num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1438 if ( $num_sites > 1 ) {
1439 return true;
1440 } else {
1441 return false;
1442 }
1443 }
1444
1445 /**
1446 * Trigger an update to the main_network_site when we update the siteurl of a site.
1447 * @return null
1448 */
1449 function update_jetpack_main_network_site_option() {
1450 _deprecated_function( __METHOD__, 'jetpack-4.2' );
1451 }
1452 /**
1453 * Triggered after a user updates the network settings via Network Settings Admin Page
1454 *
1455 */
1456 function update_jetpack_network_settings() {
1457 _deprecated_function( __METHOD__, 'jetpack-4.2' );
1458 // Only sync this info for the main network site.
1459 }
1460
1461 /**
1462 * Get back if the current site is single user site.
1463 *
1464 * @return bool
1465 */
1466 public static function is_single_user_site() {
1467 global $wpdb;
1468
1469 if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1470 $some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1471 set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1472 }
1473 return 1 === (int) $some_users;
1474 }
1475
1476 /**
1477 * Returns true if the site has file write access false otherwise.
1478 * @return string ( '1' | '0' )
1479 **/
1480 public static function file_system_write_access() {
1481 if ( ! function_exists( 'get_filesystem_method' ) ) {
1482 require_once( ABSPATH . 'wp-admin/includes/file.php' );
1483 }
1484
1485 require_once( ABSPATH . 'wp-admin/includes/template.php' );
1486
1487 $filesystem_method = get_filesystem_method();
1488 if ( $filesystem_method === 'direct' ) {
1489 return 1;
1490 }
1491
1492 ob_start();
1493 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1494 ob_end_clean();
1495 if ( $filesystem_credentials_are_stored ) {
1496 return 1;
1497 }
1498 return 0;
1499 }
1500
1501 /**
1502 * Finds out if a site is using a version control system.
1503 * @return string ( '1' | '0' )
1504 **/
1505 public static function is_version_controlled() {
1506 _deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1507 return (string) (int) Functions::is_version_controlled();
1508 }
1509
1510 /**
1511 * Determines whether the current theme supports featured images or not.
1512 * @return string ( '1' | '0' )
1513 */
1514 public static function featured_images_enabled() {
1515 _deprecated_function( __METHOD__, 'jetpack-4.2' );
1516 return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1517 }
1518
1519 /**
1520 * Wrapper for core's get_avatar_url(). This one is deprecated.
1521 *
1522 * @deprecated 4.7 use get_avatar_url instead.
1523 * @param int|string|object $id_or_email A user ID, email address, or comment object
1524 * @param int $size Size of the avatar image
1525 * @param string $default URL to a default image to use if no avatar is available
1526 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1527 *
1528 * @return array
1529 */
1530 public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1531 _deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1532 return get_avatar_url( $id_or_email, array(
1533 'size' => $size,
1534 'default' => $default,
1535 'force_default' => $force_display,
1536 ) );
1537 }
1538
1539 /**
1540 * jetpack_updates is saved in the following schema:
1541 *
1542 * array (
1543 * 'plugins' => (int) Number of plugin updates available.
1544 * 'themes' => (int) Number of theme updates available.
1545 * 'wordpress' => (int) Number of WordPress core updates available.
1546 * 'translations' => (int) Number of translation updates available.
1547 * 'total' => (int) Total of all available updates.
1548 * 'wp_update_version' => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1549 * )
1550 * @return array
1551 */
1552 public static function get_updates() {
1553 $update_data = wp_get_update_data();
1554
1555 // Stores the individual update counts as well as the total count.
1556 if ( isset( $update_data['counts'] ) ) {
1557 $updates = $update_data['counts'];
1558 }
1559
1560 // If we need to update WordPress core, let's find the latest version number.
1561 if ( ! empty( $updates['wordpress'] ) ) {
1562 $cur = get_preferred_from_update_core();
1563 if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1564 $updates['wp_update_version'] = $cur->current;
1565 }
1566 }
1567 return isset( $updates ) ? $updates : array();
1568 }
1569
1570 public static function get_update_details() {
1571 $update_details = array(
1572 'update_core' => get_site_transient( 'update_core' ),
1573 'update_plugins' => get_site_transient( 'update_plugins' ),
1574 'update_themes' => get_site_transient( 'update_themes' ),
1575 );
1576 return $update_details;
1577 }
1578
1579 public static function refresh_update_data() {
1580 _deprecated_function( __METHOD__, 'jetpack-4.2' );
1581
1582 }
1583
1584 public static function refresh_theme_data() {
1585 _deprecated_function( __METHOD__, 'jetpack-4.2' );
1586 }
1587
1588 /**
1589 * Is Jetpack active?
1590 */
1591 public static function is_active() {
1592 return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1593 }
1594
1595 /**
1596 * Make an API call to WordPress.com for plan status
1597 *
1598 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1599 *
1600 * @return bool True if plan is updated, false if no update
1601 */
1602 public static function refresh_active_plan_from_wpcom() {
1603 _deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1604 return Jetpack_Plan::refresh_from_wpcom();
1605 }
1606
1607 /**
1608 * Get the plan that this Jetpack site is currently using
1609 *
1610 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1611 * @return array Active Jetpack plan details.
1612 */
1613 public static function get_active_plan() {
1614 _deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1615 return Jetpack_Plan::get();
1616 }
1617
1618 /**
1619 * Determine whether the active plan supports a particular feature
1620 *
1621 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1622 * @return bool True if plan supports feature, false if not.
1623 */
1624 public static function active_plan_supports( $feature ) {
1625 _deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1626 return Jetpack_Plan::supports( $feature );
1627 }
1628
1629 /**
1630 * Is Jetpack in development (offline) mode?
1631 */
1632 public static function is_development_mode() {
1633 $development_mode = false;
1634
1635 if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1636 $development_mode = JETPACK_DEV_DEBUG;
1637 } elseif ( $site_url = site_url() ) {
1638 $development_mode = false === strpos( $site_url, '.' );
1639 }
1640
1641 /**
1642 * Filters Jetpack's development mode.
1643 *
1644 * @see https://jetpack.com/support/development-mode/
1645 *
1646 * @since 2.2.1
1647 *
1648 * @param bool $development_mode Is Jetpack's development mode active.
1649 */
1650 $development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1651 return $development_mode;
1652 }
1653
1654 /**
1655 * Whether the site is currently onboarding or not.
1656 * A site is considered as being onboarded if it currently has an onboarding token.
1657 *
1658 * @since 5.8
1659 *
1660 * @access public
1661 * @static
1662 *
1663 * @return bool True if the site is currently onboarding, false otherwise
1664 */
1665 public static function is_onboarding() {
1666 return Jetpack_Options::get_option( 'onboarding' ) !== false;
1667 }
1668
1669 /**
1670 * Determines reason for Jetpack development mode.
1671 */
1672 public static function development_mode_trigger_text() {
1673 if ( ! Jetpack::is_development_mode() ) {
1674 return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1675 }
1676
1677 if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1678 $notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1679 } elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1680 $notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1681 } else {
1682 $notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1683 }
1684
1685 return $notice;
1686
1687 }
1688 /**
1689 * Get Jetpack development mode notice text and notice class.
1690 *
1691 * Mirrors the checks made in Jetpack::is_development_mode
1692 *
1693 */
1694 public static function show_development_mode_notice() {
1695 if ( Jetpack::is_development_mode() ) {
1696 $notice = sprintf(
1697 /* translators: %s is a URL */
1698 __( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1699 'https://jetpack.com/support/development-mode/'
1700 );
1701
1702 $notice .= ' ' . Jetpack::development_mode_trigger_text();
1703
1704 echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1705 }
1706
1707 // Throw up a notice if using a development version and as for feedback.
1708 if ( Jetpack::is_development_version() ) {
1709 /* translators: %s is a URL */
1710 $notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1711
1712 echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1713 }
1714 // Throw up a notice if using staging mode
1715 if ( Jetpack::is_staging_site() ) {
1716 /* translators: %s is a URL */
1717 $notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1718
1719 echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1720 }
1721 }
1722
1723 /**
1724 * Whether Jetpack's version maps to a public release, or a development version.
1725 */
1726 public static function is_development_version() {
1727 /**
1728 * Allows filtering whether this is a development version of Jetpack.
1729 *
1730 * This filter is especially useful for tests.
1731 *
1732 * @since 4.3.0
1733 *
1734 * @param bool $development_version Is this a develoment version of Jetpack?
1735 */
1736 return (bool) apply_filters(
1737 'jetpack_development_version',
1738 ! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1739 );
1740 }
1741
1742 /**
1743 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1744 */
1745 public static function is_user_connected( $user_id = false ) {
1746 return self::connection()->is_user_connected( $user_id );
1747 }
1748
1749 /**
1750 * Get the wpcom user data of the current|specified connected user.
1751 */
1752 public static function get_connected_user_data( $user_id = null ) {
1753 // TODO: remove in favor of Connection_Manager->get_connected_user_data
1754 if ( ! $user_id ) {
1755 $user_id = get_current_user_id();
1756 }
1757
1758 $transient_key = "jetpack_connected_user_data_$user_id";
1759
1760 if ( $cached_user_data = get_transient( $transient_key ) ) {
1761 return $cached_user_data;
1762 }
1763
1764 Jetpack::load_xml_rpc_client();
1765 $xml = new Jetpack_IXR_Client( array(
1766 'user_id' => $user_id,
1767 ) );
1768 $xml->query( 'wpcom.getUser' );
1769 if ( ! $xml->isError() ) {
1770 $user_data = $xml->getResponse();
1771 set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1772 return $user_data;
1773 }
1774
1775 return false;
1776 }
1777
1778 /**
1779 * Get the wpcom email of the current|specified connected user.
1780 */
1781 public static function get_connected_user_email( $user_id = null ) {
1782 if ( ! $user_id ) {
1783 $user_id = get_current_user_id();
1784 }
1785 Jetpack::load_xml_rpc_client();
1786 $xml = new Jetpack_IXR_Client( array(
1787 'user_id' => $user_id,
1788 ) );
1789 $xml->query( 'wpcom.getUserEmail' );
1790 if ( ! $xml->isError() ) {
1791 return $xml->getResponse();
1792 }
1793 return false;
1794 }
1795
1796 /**
1797 * Get the wpcom email of the master user.
1798 */
1799 public static function get_master_user_email() {
1800 $master_user_id = Jetpack_Options::get_option( 'master_user' );
1801 if ( $master_user_id ) {
1802 return self::get_connected_user_email( $master_user_id );
1803 }
1804 return '';
1805 }
1806
1807 function current_user_is_connection_owner() {
1808 $user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1809 return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1810 }
1811
1812 /**
1813 * Gets current user IP address.
1814 *
1815 * @param bool $check_all_headers Check all headers? Default is `false`.
1816 *
1817 * @return string Current user IP address.
1818 */
1819 public static function current_user_ip( $check_all_headers = false ) {
1820 if ( $check_all_headers ) {
1821 foreach ( array(
1822 'HTTP_CF_CONNECTING_IP',
1823 'HTTP_CLIENT_IP',
1824 'HTTP_X_FORWARDED_FOR',
1825 'HTTP_X_FORWARDED',
1826 'HTTP_X_CLUSTER_CLIENT_IP',
1827 'HTTP_FORWARDED_FOR',
1828 'HTTP_FORWARDED',
1829 'HTTP_VIA',
1830 ) as $key ) {
1831 if ( ! empty( $_SERVER[ $key ] ) ) {
1832 return $_SERVER[ $key ];
1833 }
1834 }
1835 }
1836
1837 return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1838 }
1839
1840 /**
1841 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1842 */
1843 function extra_oembed_providers() {
1844 // Cloudup: https://dev.cloudup.com/#oembed
1845 wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1846 wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1847 wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1848 wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1849 wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1850 wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1851 wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1852 }
1853
1854 /**
1855 * Synchronize connected user role changes
1856 */
1857 function user_role_change( $user_id ) {
1858 _deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1859 Users::user_role_change( $user_id );
1860 }
1861
1862 /**
1863 * Loads the currently active modules.
1864 */
1865 public static function load_modules() {
1866 if (
1867 ! self::is_active()
1868 && ! self::is_development_mode()
1869 && ! self::is_onboarding()
1870 && (
1871 ! is_multisite()
1872 || ! get_site_option( 'jetpack_protect_active' )
1873 )
1874 ) {
1875 return;
1876 }
1877
1878 $version = Jetpack_Options::get_option( 'version' );
1879 if ( ! $version ) {
1880 $version = $old_version = JETPACK__VERSION . ':' . time();
1881 /** This action is documented in class.jetpack.php */
1882 do_action( 'updating_jetpack_version', $version, false );
1883 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1884 }
1885 list( $version ) = explode( ':', $version );
1886
1887 $modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1888
1889 $modules_data = array();
1890
1891 // Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1892 if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1893 $updated_modules = array();
1894 foreach ( $modules as $module ) {
1895 $modules_data[ $module ] = Jetpack::get_module( $module );
1896 if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1897 continue;
1898 }
1899
1900 if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1901 continue;
1902 }
1903
1904 $updated_modules[] = $module;
1905 }
1906
1907 $modules = array_diff( $modules, $updated_modules );
1908 }
1909
1910 $is_development_mode = Jetpack::is_development_mode();
1911
1912 foreach ( $modules as $index => $module ) {
1913 // If we're in dev mode, disable modules requiring a connection
1914 if ( $is_development_mode ) {
1915 // Prime the pump if we need to
1916 if ( empty( $modules_data[ $module ] ) ) {
1917 $modules_data[ $module ] = Jetpack::get_module( $module );
1918 }
1919 // If the module requires a connection, but we're in local mode, don't include it.
1920 if ( $modules_data[ $module ]['requires_connection'] ) {
1921 continue;
1922 }
1923 }
1924
1925 if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1926 continue;
1927 }
1928
1929 if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1930 unset( $modules[ $index ] );
1931 self::update_active_modules( array_values( $modules ) );
1932 continue;
1933 }
1934
1935 /**
1936 * Fires when a specific module is loaded.
1937 * The dynamic part of the hook, $module, is the module slug.
1938 *
1939 * @since 1.1.0
1940 */
1941 do_action( 'jetpack_module_loaded_' . $module );
1942 }
1943
1944 /**
1945 * Fires when all the modules are loaded.
1946 *
1947 * @since 1.1.0
1948 */
1949 do_action( 'jetpack_modules_loaded' );
1950
1951 // 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.
1952 require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1953 }
1954
1955 /**
1956 * Check if Jetpack's REST API compat file should be included
1957 * @action plugins_loaded
1958 * @return null
1959 */
1960 public function check_rest_api_compat() {
1961 /**
1962 * Filters the list of REST API compat files to be included.
1963 *
1964 * @since 2.2.5
1965 *
1966 * @param array $args Array of REST API compat files to include.
1967 */
1968 $_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1969
1970 if ( function_exists( 'bbpress' ) )
1971 $_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1972
1973 foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1974 require_once $_jetpack_rest_api_compat_include;
1975 }
1976
1977 /**
1978 * Gets all plugins currently active in values, regardless of whether they're
1979 * traditionally activated or network activated.
1980 *
1981 * @todo Store the result in core's object cache maybe?
1982 */
1983 public static function get_active_plugins() {
1984 $active_plugins = (array) get_option( 'active_plugins', array() );
1985
1986 if ( is_multisite() ) {
1987 // Due to legacy code, active_sitewide_plugins stores them in the keys,
1988 // whereas active_plugins stores them in the values.
1989 $network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1990 if ( $network_plugins ) {
1991 $active_plugins = array_merge( $active_plugins, $network_plugins );
1992 }
1993 }
1994
1995 sort( $active_plugins );
1996
1997 return array_unique( $active_plugins );
1998 }
1999
2000 /**
2001 * Gets and parses additional plugin data to send with the heartbeat data
2002 *
2003 * @since 3.8.1
2004 *
2005 * @return array Array of plugin data
2006 */
2007 public static function get_parsed_plugin_data() {
2008 if ( ! function_exists( 'get_plugins' ) ) {
2009 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
2010 }
2011 /** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2012 $all_plugins = apply_filters( 'all_plugins', get_plugins() );
2013 $active_plugins = Jetpack::get_active_plugins();
2014
2015 $plugins = array();
2016 foreach ( $all_plugins as $path => $plugin_data ) {
2017 $plugins[ $path ] = array(
2018 'is_active' => in_array( $path, $active_plugins ),
2019 'file' => $path,
2020 'name' => $plugin_data['Name'],
2021 'version' => $plugin_data['Version'],
2022 'author' => $plugin_data['Author'],
2023 );
2024 }
2025
2026 return $plugins;
2027 }
2028
2029 /**
2030 * Gets and parses theme data to send with the heartbeat data
2031 *
2032 * @since 3.8.1
2033 *
2034 * @return array Array of theme data
2035 */
2036 public static function get_parsed_theme_data() {
2037 $all_themes = wp_get_themes( array( 'allowed' => true ) );
2038 $header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2039
2040 $themes = array();
2041 foreach ( $all_themes as $slug => $theme_data ) {
2042 $theme_headers = array();
2043 foreach ( $header_keys as $header_key ) {
2044 $theme_headers[ $header_key ] = $theme_data->get( $header_key );
2045 }
2046
2047 $themes[ $slug ] = array(
2048 'is_active_theme' => $slug == wp_get_theme()->get_template(),
2049 'slug' => $slug,
2050 'theme_root' => $theme_data->get_theme_root_uri(),
2051 'parent' => $theme_data->parent(),
2052 'headers' => $theme_headers
2053 );
2054 }
2055
2056 return $themes;
2057 }
2058
2059 /**
2060 * Checks whether a specific plugin is active.
2061 *
2062 * We don't want to store these in a static variable, in case
2063 * there are switch_to_blog() calls involved.
2064 */
2065 public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2066 return in_array( $plugin, self::get_active_plugins() );
2067 }
2068
2069 /**
2070 * Check if Jetpack's Open Graph tags should be used.
2071 * If certain plugins are active, Jetpack's og tags are suppressed.
2072 *
2073 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2074 * @action plugins_loaded
2075 * @return null
2076 */
2077 public function check_open_graph() {
2078 if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2079 add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2080 }
2081
2082 $active_plugins = self::get_active_plugins();
2083
2084 if ( ! empty( $active_plugins ) ) {
2085 foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2086 if ( in_array( $plugin, $active_plugins ) ) {
2087 add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2088 break;
2089 }
2090 }
2091 }
2092
2093 /**
2094 * Allow the addition of Open Graph Meta Tags to all pages.
2095 *
2096 * @since 2.0.3
2097 *
2098 * @param bool false Should Open Graph Meta tags be added. Default to false.
2099 */
2100 if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2101 require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2102 }
2103 }
2104
2105 /**
2106 * Check if Jetpack's Twitter tags should be used.
2107 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2108 *
2109 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2110 * @action plugins_loaded
2111 * @return null
2112 */
2113 public function check_twitter_tags() {
2114
2115 $active_plugins = self::get_active_plugins();
2116
2117 if ( ! empty( $active_plugins ) ) {
2118 foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2119 if ( in_array( $plugin, $active_plugins ) ) {
2120 add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2121 break;
2122 }
2123 }
2124 }
2125
2126 /**
2127 * Allow Twitter Card Meta tags to be disabled.
2128 *
2129 * @since 2.6.0
2130 *
2131 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2132 */
2133 if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2134 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2135 }
2136 }
2137
2138 /**
2139 * Allows plugins to submit security reports.
2140 *
2141 * @param string $type Report type (login_form, backup, file_scanning, spam)
2142 * @param string $plugin_file Plugin __FILE__, so that we can pull plugin data
2143 * @param array $args See definitions above
2144 */
2145 public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2146 _deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2147 }
2148
2149 /* Jetpack Options API */
2150
2151 public static function get_option_names( $type = 'compact' ) {
2152 return Jetpack_Options::get_option_names( $type );
2153 }
2154
2155 /**
2156 * Returns the requested option. Looks in jetpack_options or jetpack_$name as appropriate.
2157 *
2158 * @param string $name Option name
2159 * @param mixed $default (optional)
2160 */
2161 public static function get_option( $name, $default = false ) {
2162 return Jetpack_Options::get_option( $name, $default );
2163 }
2164
2165 /**
2166 * Updates the single given option. Updates jetpack_options or jetpack_$name as appropriate.
2167 *
2168 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2169 * @param string $name Option name
2170 * @param mixed $value Option value
2171 */
2172 public static function update_option( $name, $value ) {
2173 _deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2174 return Jetpack_Options::update_option( $name, $value );
2175 }
2176
2177 /**
2178 * Updates the multiple given options. Updates jetpack_options and/or jetpack_$name as appropriate.
2179 *
2180 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2181 * @param array $array array( option name => option value, ... )
2182 */
2183 public static function update_options( $array ) {
2184 _deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2185 return Jetpack_Options::update_options( $array );
2186 }
2187
2188 /**
2189 * Deletes the given option. May be passed multiple option names as an array.
2190 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2191 *
2192 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2193 * @param string|array $names
2194 */
2195 public static function delete_option( $names ) {
2196 _deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2197 return Jetpack_Options::delete_option( $names );
2198 }
2199
2200 /**
2201 * Enters a user token into the user_tokens option
2202 *
2203 * @param int $user_id
2204 * @param string $token
2205 * return bool
2206 */
2207 public static function update_user_token( $user_id, $token, $is_master_user ) {
2208 // not designed for concurrent updates
2209 $user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2210 if ( ! is_array( $user_tokens ) )
2211 $user_tokens = array();
2212 $user_tokens[$user_id] = $token;
2213 if ( $is_master_user ) {
2214 $master_user = $user_id;
2215 $options = compact( 'user_tokens', 'master_user' );
2216 } else {
2217 $options = compact( 'user_tokens' );
2218 }
2219 return Jetpack_Options::update_options( $options );
2220 }
2221
2222 /**
2223 * Returns an array of all PHP files in the specified absolute path.
2224 * Equivalent to glob( "$absolute_path/*.php" ).
2225 *
2226 * @param string $absolute_path The absolute path of the directory to search.
2227 * @return array Array of absolute paths to the PHP files.
2228 */
2229 public static function glob_php( $absolute_path ) {
2230 if ( function_exists( 'glob' ) ) {
2231 return glob( "$absolute_path/*.php" );
2232 }
2233
2234 $absolute_path = untrailingslashit( $absolute_path );
2235 $files = array();
2236 if ( ! $dir = @opendir( $absolute_path ) ) {
2237 return $files;
2238 }
2239
2240 while ( false !== $file = readdir( $dir ) ) {
2241 if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2242 continue;
2243 }
2244
2245 $file = "$absolute_path/$file";
2246
2247 if ( ! is_file( $file ) ) {
2248 continue;
2249 }
2250
2251 $files[] = $file;
2252 }
2253
2254 closedir( $dir );
2255
2256 return $files;
2257 }
2258
2259 public static function activate_new_modules( $redirect = false ) {
2260 if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2261 return;
2262 }
2263
2264 $jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2265 if ( ! $jetpack_old_version ) {
2266 $jetpack_old_version = $version = $old_version = '1.1:' . time();
2267 /** This action is documented in class.jetpack.php */
2268 do_action( 'updating_jetpack_version', $version, false );
2269 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2270 }
2271
2272 list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2273
2274 if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2275 return;
2276 }
2277
2278 $active_modules = Jetpack::get_active_modules();
2279 $reactivate_modules = array();
2280 foreach ( $active_modules as $active_module ) {
2281 $module = Jetpack::get_module( $active_module );
2282 if ( ! isset( $module['changed'] ) ) {
2283 continue;
2284 }
2285
2286 if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2287 continue;
2288 }
2289
2290 $reactivate_modules[] = $active_module;
2291 Jetpack::deactivate_module( $active_module );
2292 }
2293
2294 $new_version = JETPACK__VERSION . ':' . time();
2295 /** This action is documented in class.jetpack.php */
2296 do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2297 Jetpack_Options::update_options(
2298 array(
2299 'version' => $new_version,
2300 'old_version' => $jetpack_old_version,
2301 )
2302 );
2303
2304 Jetpack::state( 'message', 'modules_activated' );
2305 Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2306
2307 if ( $redirect ) {
2308 $page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2309 if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2310 $page = $_GET['page'];
2311 }
2312
2313 wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2314 exit;
2315 }
2316 }
2317
2318 /**
2319 * List available Jetpack modules. Simply lists .php files in /modules/.
2320 * Make sure to tuck away module "library" files in a sub-directory.
2321 */
2322 public static function get_available_modules( $min_version = false, $max_version = false ) {
2323 static $modules = null;
2324
2325 if ( ! isset( $modules ) ) {
2326 $available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2327 // Use the cache if we're on the front-end and it's available...
2328 if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2329 $modules = $available_modules_option[ JETPACK__VERSION ];
2330 } else {
2331 $files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2332
2333 $modules = array();
2334
2335 foreach ( $files as $file ) {
2336 if ( ! $headers = Jetpack::get_module( $file ) ) {
2337 continue;
2338 }
2339
2340 $modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2341 }
2342
2343 Jetpack_Options::update_option( 'available_modules', array(
2344 JETPACK__VERSION => $modules,
2345 ) );
2346 }
2347 }
2348
2349 /**
2350 * Filters the array of modules available to be activated.
2351 *
2352 * @since 2.4.0
2353 *
2354 * @param array $modules Array of available modules.
2355 * @param string $min_version Minimum version number required to use modules.
2356 * @param string $max_version Maximum version number required to use modules.
2357 */
2358 $mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2359
2360 if ( ! $min_version && ! $max_version ) {
2361 return array_keys( $mods );
2362 }
2363
2364 $r = array();
2365 foreach ( $mods as $slug => $introduced ) {
2366 if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2367 continue;
2368 }
2369
2370 if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2371 continue;
2372 }
2373
2374 $r[] = $slug;
2375 }
2376
2377 return $r;
2378 }
2379
2380 /**
2381 * Default modules loaded on activation.
2382 */
2383 public static function get_default_modules( $min_version = false, $max_version = false ) {
2384 $return = array();
2385
2386 foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2387 $module_data = Jetpack::get_module( $module );
2388
2389 switch ( strtolower( $module_data['auto_activate'] ) ) {
2390 case 'yes' :
2391 $return[] = $module;
2392 break;
2393 case 'public' :
2394 if ( Jetpack_Options::get_option( 'public' ) ) {
2395 $return[] = $module;
2396 }
2397 break;
2398 case 'no' :
2399 default :
2400 break;
2401 }
2402 }
2403 /**
2404 * Filters the array of default modules.
2405 *
2406 * @since 2.5.0
2407 *
2408 * @param array $return Array of default modules.
2409 * @param string $min_version Minimum version number required to use modules.
2410 * @param string $max_version Maximum version number required to use modules.
2411 */
2412 return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2413 }
2414
2415 /**
2416 * Checks activated modules during auto-activation to determine
2417 * if any of those modules are being deprecated. If so, close
2418 * them out, and add any replacement modules.
2419 *
2420 * Runs at priority 99 by default.
2421 *
2422 * This is run late, so that it can still activate a module if
2423 * the new module is a replacement for another that the user
2424 * currently has active, even if something at the normal priority
2425 * would kibosh everything.
2426 *
2427 * @since 2.6
2428 * @uses jetpack_get_default_modules filter
2429 * @param array $modules
2430 * @return array
2431 */
2432 function handle_deprecated_modules( $modules ) {
2433 $deprecated_modules = array(
2434 'debug' => null, // Closed out and moved to the debugger library.
2435 'wpcc' => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2436 'gplus-authorship' => null, // Closed out in 3.2 -- Google dropped support.
2437 );
2438
2439 // Don't activate SSO if they never completed activating WPCC.
2440 if ( Jetpack::is_module_active( 'wpcc' ) ) {
2441 $wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2442 if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2443 $deprecated_modules['wpcc'] = null;
2444 }
2445 }
2446
2447 foreach ( $deprecated_modules as $module => $replacement ) {
2448 if ( Jetpack::is_module_active( $module ) ) {
2449 self::deactivate_module( $module );
2450 if ( $replacement ) {
2451 $modules[] = $replacement;
2452 }
2453 }
2454 }
2455
2456 return array_unique( $modules );
2457 }
2458
2459 /**
2460 * Checks activated plugins during auto-activation to determine
2461 * if any of those plugins are in the list with a corresponding module
2462 * that is not compatible with the plugin. The module will not be allowed
2463 * to auto-activate.
2464 *
2465 * @since 2.6
2466 * @uses jetpack_get_default_modules filter
2467 * @param array $modules
2468 * @return array
2469 */
2470 function filter_default_modules( $modules ) {
2471
2472 $active_plugins = self::get_active_plugins();
2473
2474 if ( ! empty( $active_plugins ) ) {
2475
2476 // For each module we'd like to auto-activate...
2477 foreach ( $modules as $key => $module ) {
2478 // If there are potential conflicts for it...
2479 if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2480 // For each potential conflict...
2481 foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2482 // If that conflicting plugin is active...
2483 if ( in_array( $plugin, $active_plugins ) ) {
2484 // Remove that item from being auto-activated.
2485 unset( $modules[ $key ] );
2486 }
2487 }
2488 }
2489 }
2490 }
2491
2492 return $modules;
2493 }
2494
2495 /**
2496 * Extract a module's slug from its full path.
2497 */
2498 public static function get_module_slug( $file ) {
2499 return str_replace( '.php', '', basename( $file ) );
2500 }
2501
2502 /**
2503 * Generate a module's path from its slug.
2504 */
2505 public static function get_module_path( $slug ) {
2506 /**
2507 * Filters the path of a modules.
2508 *
2509 * @since 7.4.0
2510 *
2511 * @param array $return The absolute path to a module's root php file
2512 * @param string $slug The module slug
2513 */
2514 return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2515 }
2516
2517 /**
2518 * Load module data from module file. Headers differ from WordPress
2519 * plugin headers to avoid them being identified as standalone
2520 * plugins on the WordPress plugins page.
2521 */
2522 public static function get_module( $module ) {
2523 $headers = array(
2524 'name' => 'Module Name',
2525 'description' => 'Module Description',
2526 'sort' => 'Sort Order',
2527 'recommendation_order' => 'Recommendation Order',
2528 'introduced' => 'First Introduced',
2529 'changed' => 'Major Changes In',
2530 'deactivate' => 'Deactivate',
2531 'free' => 'Free',
2532 'requires_connection' => 'Requires Connection',
2533 'auto_activate' => 'Auto Activate',
2534 'module_tags' => 'Module Tags',
2535 'feature' => 'Feature',
2536 'additional_search_queries' => 'Additional Search Queries',
2537 'plan_classes' => 'Plans',
2538 );
2539
2540 $file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2541
2542 $mod = Jetpack::get_file_data( $file, $headers );
2543 if ( empty( $mod['name'] ) ) {
2544 return false;
2545 }
2546
2547 $mod['sort'] = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2548 $mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2549 $mod['deactivate'] = empty( $mod['deactivate'] );
2550 $mod['free'] = empty( $mod['free'] );
2551 $mod['requires_connection'] = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2552
2553 if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2554 $mod['auto_activate'] = 'No';
2555 } else {
2556 $mod['auto_activate'] = (string) $mod['auto_activate'];
2557 }
2558
2559 if ( $mod['module_tags'] ) {
2560 $mod['module_tags'] = explode( ',', $mod['module_tags'] );
2561 $mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2562 $mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2563 } else {
2564 $mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2565 }
2566
2567 if ( $mod['plan_classes'] ) {
2568 $mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2569 $mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2570 } else {
2571 $mod['plan_classes'] = array( 'free' );
2572 }
2573
2574 if ( $mod['feature'] ) {
2575 $mod['feature'] = explode( ',', $mod['feature'] );
2576 $mod['feature'] = array_map( 'trim', $mod['feature'] );
2577 } else {
2578 $mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2579 }
2580
2581 /**
2582 * Filters the feature array on a module.
2583 *
2584 * This filter allows you to control where each module is filtered: Recommended,
2585 * and the default "Other" listing.
2586 *
2587 * @since 3.5.0
2588 *
2589 * @param array $mod['feature'] The areas to feature this module:
2590 * 'Recommended' shows on the main Jetpack admin screen.
2591 * 'Other' should be the default if no other value is in the array.
2592 * @param string $module The slug of the module, e.g. sharedaddy.
2593 * @param array $mod All the currently assembled module data.
2594 */
2595 $mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2596
2597 /**
2598 * Filter the returned data about a module.
2599 *
2600 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2601 * so please be careful.
2602 *
2603 * @since 3.6.0
2604 *
2605 * @param array $mod The details of the requested module.
2606 * @param string $module The slug of the module, e.g. sharedaddy
2607 * @param string $file The path to the module source file.
2608 */
2609 return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2610 }
2611
2612 /**
2613 * Like core's get_file_data implementation, but caches the result.
2614 */
2615 public static function get_file_data( $file, $headers ) {
2616 //Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2617 $file_name = basename( $file );
2618
2619 $cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2620
2621 $file_data_option = get_transient( $cache_key );
2622
2623 if ( false === $file_data_option ) {
2624 $file_data_option = array();
2625 }
2626
2627 $key = md5( $file_name . serialize( $headers ) );
2628 $refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2629
2630 // If we don't need to refresh the cache, and already have the value, short-circuit!
2631 if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2632 return $file_data_option[ $key ];
2633 }
2634
2635 $data = get_file_data( $file, $headers );
2636
2637 $file_data_option[ $key ] = $data;
2638
2639 set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2640
2641 return $data;
2642 }
2643
2644
2645 /**
2646 * Return translated module tag.
2647 *
2648 * @param string $tag Tag as it appears in each module heading.
2649 *
2650 * @return mixed
2651 */
2652 public static function translate_module_tag( $tag ) {
2653 return jetpack_get_module_i18n_tag( $tag );
2654 }
2655
2656 /**
2657 * Get i18n strings as a JSON-encoded string
2658 *
2659 * @return string The locale as JSON
2660 */
2661 public static function get_i18n_data_json() {
2662
2663 // WordPress 5.0 uses md5 hashes of file paths to associate translation
2664 // JSON files with the file they should be included for. This is an md5
2665 // of '_inc/build/admin.js'.
2666 $path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2667
2668 $i18n_json =
2669 JETPACK__PLUGIN_DIR
2670 . 'languages/json/jetpack-'
2671 . get_user_locale()
2672 . '-'
2673 . $path_md5
2674 . '.json';
2675
2676 if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2677 $locale_data = @file_get_contents( $i18n_json );
2678 if ( $locale_data ) {
2679 return $locale_data;
2680 }
2681 }
2682
2683 // Return valid empty Jed locale
2684 return '{ "locale_data": { "messages": { "": {} } } }';
2685 }
2686
2687 /**
2688 * Add locale data setup to wp-i18n
2689 *
2690 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2691 *
2692 * The locale setup depends on an adding inline script. This is error-prone and could easily
2693 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2694 *
2695 * This method provides a safe way to request the setup multiple times but add the script at
2696 * most once.
2697 *
2698 * @since 6.7.0
2699 *
2700 * @return void
2701 */
2702 public static function setup_wp_i18n_locale_data() {
2703 static $script_added = false;
2704 if ( ! $script_added ) {
2705 $script_added = true;
2706 wp_add_inline_script(
2707 'wp-i18n',
2708 'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2709 );
2710 }
2711 }
2712
2713 /**
2714 * Return module name translation. Uses matching string created in modules/module-headings.php.
2715 *
2716 * @since 3.9.2
2717 *
2718 * @param array $modules
2719 *
2720 * @return string|void
2721 */
2722 public static function get_translated_modules( $modules ) {
2723 foreach ( $modules as $index => $module ) {
2724 $i18n_module = jetpack_get_module_i18n( $module['module'] );
2725 if ( isset( $module['name'] ) ) {
2726 $modules[ $index ]['name'] = $i18n_module['name'];
2727 }
2728 if ( isset( $module['description'] ) ) {
2729 $modules[ $index ]['description'] = $i18n_module['description'];
2730 $modules[ $index ]['short_description'] = $i18n_module['description'];
2731 }
2732 }
2733 return $modules;
2734 }
2735
2736 /**
2737 * Get a list of activated modules as an array of module slugs.
2738 */
2739 public static function get_active_modules() {
2740 $active = Jetpack_Options::get_option( 'active_modules' );
2741
2742 if ( ! is_array( $active ) ) {
2743 $active = array();
2744 }
2745
2746 if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2747 $active[] = 'vaultpress';
2748 } else {
2749 $active = array_diff( $active, array( 'vaultpress' ) );
2750 }
2751
2752 //If protect is active on the main site of a multisite, it should be active on all sites.
2753 if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2754 $active[] = 'protect';
2755 }
2756
2757 /**
2758 * Allow filtering of the active modules.
2759 *
2760 * Gives theme and plugin developers the power to alter the modules that
2761 * are activated on the fly.
2762 *
2763 * @since 5.8.0
2764 *
2765 * @param array $active Array of active module slugs.
2766 */
2767 $active = apply_filters( 'jetpack_active_modules', $active );
2768
2769 return array_unique( $active );
2770 }
2771
2772 /**
2773 * Check whether or not a Jetpack module is active.
2774 *
2775 * @param string $module The slug of a Jetpack module.
2776 * @return bool
2777 *
2778 * @static
2779 */
2780 public static function is_module_active( $module ) {
2781 return in_array( $module, self::get_active_modules() );
2782 }
2783
2784 public static function is_module( $module ) {
2785 return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2786 }
2787
2788 /**
2789 * Catches PHP errors. Must be used in conjunction with output buffering.
2790 *
2791 * @param bool $catch True to start catching, False to stop.
2792 *
2793 * @static
2794 */
2795 public static function catch_errors( $catch ) {
2796 static $display_errors, $error_reporting;
2797
2798 if ( $catch ) {
2799 $display_errors = @ini_set( 'display_errors', 1 );
2800 $error_reporting = @error_reporting( E_ALL );
2801 add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2802 } else {
2803 @ini_set( 'display_errors', $display_errors );
2804 @error_reporting( $error_reporting );
2805 remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2806 }
2807 }
2808
2809 /**
2810 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2811 */
2812 public static function catch_errors_on_shutdown() {
2813 Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2814 }
2815
2816 /**
2817 * Rewrite any string to make paths easier to read.
2818 *
2819 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2820 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2821 *
2822 * @param $string
2823 * @return mixed
2824 */
2825 public static function alias_directories( $string ) {
2826 // ABSPATH has a trailing slash.
2827 $string = str_replace( ABSPATH, 'ABSPATH/', $string );
2828 // WP_CONTENT_DIR does not have a trailing slash.
2829 $string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2830
2831 return $string;
2832 }
2833
2834 public static function activate_default_modules(
2835 $min_version = false,
2836 $max_version = false,
2837 $other_modules = array(),
2838 $redirect = true,
2839 $send_state_messages = true
2840 ) {
2841 $jetpack = Jetpack::init();
2842
2843 $modules = Jetpack::get_default_modules( $min_version, $max_version );
2844 $modules = array_merge( $other_modules, $modules );
2845
2846 // Look for standalone plugins and disable if active.
2847
2848 $to_deactivate = array();
2849 foreach ( $modules as $module ) {
2850 if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2851 $to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2852 }
2853 }
2854
2855 $deactivated = array();
2856 foreach ( $to_deactivate as $module => $deactivate_me ) {
2857 list( $probable_file, $probable_title ) = $deactivate_me;
2858 if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2859 $deactivated[] = $module;
2860 }
2861 }
2862
2863 if ( $deactivated && $redirect ) {
2864 Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2865
2866 $url = add_query_arg(
2867 array(
2868 'action' => 'activate_default_modules',
2869 '_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2870 ),
2871 add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2872 );
2873 wp_safe_redirect( $url );
2874 exit;
2875 }
2876
2877 /**
2878 * Fires before default modules are activated.
2879 *
2880 * @since 1.9.0
2881 *
2882 * @param string $min_version Minimum version number required to use modules.
2883 * @param string $max_version Maximum version number required to use modules.
2884 * @param array $other_modules Array of other modules to activate alongside the default modules.
2885 */
2886 do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2887
2888 // Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2889 if ( $send_state_messages ) {
2890 Jetpack::restate();
2891 Jetpack::catch_errors( true );
2892 }
2893
2894 $active = Jetpack::get_active_modules();
2895
2896 foreach ( $modules as $module ) {
2897 if ( did_action( "jetpack_module_loaded_$module" ) ) {
2898 $active[] = $module;
2899 self::update_active_modules( $active );
2900 continue;
2901 }
2902
2903 if ( $send_state_messages && in_array( $module, $active ) ) {
2904 $module_info = Jetpack::get_module( $module );
2905 if ( ! $module_info['deactivate'] ) {
2906 $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2907 if ( $active_state = Jetpack::state( $state ) ) {
2908 $active_state = explode( ',', $active_state );
2909 } else {
2910 $active_state = array();
2911 }
2912 $active_state[] = $module;
2913 Jetpack::state( $state, implode( ',', $active_state ) );
2914 }
2915 continue;
2916 }
2917
2918 $file = Jetpack::get_module_path( $module );
2919 if ( ! file_exists( $file ) ) {
2920 continue;
2921 }
2922
2923 // we'll override this later if the plugin can be included without fatal error
2924 if ( $redirect ) {
2925 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2926 }
2927
2928 if ( $send_state_messages ) {
2929 Jetpack::state( 'error', 'module_activation_failed' );
2930 Jetpack::state( 'module', $module );
2931 }
2932
2933 ob_start();
2934 require_once $file;
2935
2936 $active[] = $module;
2937
2938 if ( $send_state_messages ) {
2939
2940 $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2941 if ( $active_state = Jetpack::state( $state ) ) {
2942 $active_state = explode( ',', $active_state );
2943 } else {
2944 $active_state = array();
2945 }
2946 $active_state[] = $module;
2947 Jetpack::state( $state, implode( ',', $active_state ) );
2948 }
2949
2950 Jetpack::update_active_modules( $active );
2951
2952 ob_end_clean();
2953 }
2954
2955 if ( $send_state_messages ) {
2956 Jetpack::state( 'error', false );
2957 Jetpack::state( 'module', false );
2958 }
2959
2960 Jetpack::catch_errors( false );
2961 /**
2962 * Fires when default modules are activated.
2963 *
2964 * @since 1.9.0
2965 *
2966 * @param string $min_version Minimum version number required to use modules.
2967 * @param string $max_version Maximum version number required to use modules.
2968 * @param array $other_modules Array of other modules to activate alongside the default modules.
2969 */
2970 do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2971 }
2972
2973 public static function activate_module( $module, $exit = true, $redirect = true ) {
2974 /**
2975 * Fires before a module is activated.
2976 *
2977 * @since 2.6.0
2978 *
2979 * @param string $module Module slug.
2980 * @param bool $exit Should we exit after the module has been activated. Default to true.
2981 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2982 */
2983 do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2984
2985 $jetpack = Jetpack::init();
2986
2987 if ( ! strlen( $module ) )
2988 return false;
2989
2990 if ( ! Jetpack::is_module( $module ) )
2991 return false;
2992
2993 // If it's already active, then don't do it again
2994 $active = Jetpack::get_active_modules();
2995 foreach ( $active as $act ) {
2996 if ( $act == $module )
2997 return true;
2998 }
2999
3000 $module_data = Jetpack::get_module( $module );
3001
3002 if ( ! Jetpack::is_active() ) {
3003 if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
3004 return false;
3005
3006 // If we're not connected but in development mode, make sure the module doesn't require a connection
3007 if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
3008 return false;
3009 }
3010
3011 // Check and see if the old plugin is active
3012 if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3013 // Deactivate the old plugin
3014 if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3015 // If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3016 // We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3017 Jetpack::state( 'deactivated_plugins', $module );
3018 wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3019 exit;
3020 }
3021 }
3022
3023 // Protect won't work with mis-configured IPs
3024 if ( 'protect' === $module ) {
3025 include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3026 if ( ! jetpack_protect_get_ip() ) {
3027 Jetpack::state( 'message', 'protect_misconfigured_ip' );
3028 return false;
3029 }
3030 }
3031
3032 if ( ! Jetpack_Plan::supports( $module ) ) {
3033 return false;
3034 }
3035
3036 // Check the file for fatal errors, a la wp-admin/plugins.php::activate
3037 Jetpack::state( 'module', $module );
3038 Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3039
3040 Jetpack::catch_errors( true );
3041 ob_start();
3042 require Jetpack::get_module_path( $module );
3043 /** This action is documented in class.jetpack.php */
3044 do_action( 'jetpack_activate_module', $module );
3045 $active[] = $module;
3046 Jetpack::update_active_modules( $active );
3047
3048 Jetpack::state( 'error', false ); // the override
3049 ob_end_clean();
3050 Jetpack::catch_errors( false );
3051
3052 if ( $redirect ) {
3053 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3054 }
3055 if ( $exit ) {
3056 exit;
3057 }
3058 return true;
3059 }
3060
3061 function activate_module_actions( $module ) {
3062 _deprecated_function( __METHOD__, 'jetpack-4.2' );
3063 }
3064
3065 public static function deactivate_module( $module ) {
3066 /**
3067 * Fires when a module is deactivated.
3068 *
3069 * @since 1.9.0
3070 *
3071 * @param string $module Module slug.
3072 */
3073 do_action( 'jetpack_pre_deactivate_module', $module );
3074
3075 $jetpack = Jetpack::init();
3076
3077 $active = Jetpack::get_active_modules();
3078 $new = array_filter( array_diff( $active, (array) $module ) );
3079
3080 return self::update_active_modules( $new );
3081 }
3082
3083 public static function enable_module_configurable( $module ) {
3084 $module = Jetpack::get_module_slug( $module );
3085 add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3086 }
3087
3088 /**
3089 * Composes a module configure URL. It uses Jetpack settings search as default value
3090 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3091 *
3092 * @param string $module Module slug
3093 * @return string $url module configuration URL
3094 */
3095 public static function module_configuration_url( $module ) {
3096 $module = Jetpack::get_module_slug( $module );
3097 $default_url = Jetpack::admin_url() . "#/settings?term=$module";
3098 /**
3099 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3100 *
3101 * @since 6.9.0
3102 *
3103 * @param string $default_url Default url, which redirects to jetpack settings page.
3104 */
3105 $url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3106
3107 return $url;
3108 }
3109
3110 /* Installation */
3111 public static function bail_on_activation( $message, $deactivate = true ) {
3112 ?>
3113 <!doctype html>
3114 <html>
3115 <head>
3116 <meta charset="<?php bloginfo( 'charset' ); ?>">
3117 <style>
3118 * {
3119 text-align: center;
3120 margin: 0;
3121 padding: 0;
3122 font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3123 }
3124 p {
3125 margin-top: 1em;
3126 font-size: 18px;
3127 }
3128 </style>
3129 <body>
3130 <p><?php echo esc_html( $message ); ?></p>
3131 </body>
3132 </html>
3133 <?php
3134 if ( $deactivate ) {
3135 $plugins = get_option( 'active_plugins' );
3136 $jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3137 $update = false;
3138 foreach ( $plugins as $i => $plugin ) {
3139 if ( $plugin === $jetpack ) {
3140 $plugins[$i] = false;
3141 $update = true;
3142 }
3143 }
3144
3145 if ( $update ) {
3146 update_option( 'active_plugins', array_filter( $plugins ) );
3147 }
3148 }
3149 exit;
3150 }
3151
3152 /**
3153 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3154 * @static
3155 */
3156 public static function plugin_activation( $network_wide ) {
3157 Jetpack_Options::update_option( 'activated', 1 );
3158
3159 if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3160 Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3161 }
3162
3163 if ( $network_wide )
3164 Jetpack::state( 'network_nag', true );
3165
3166 // For firing one-off events (notices) immediately after activation
3167 set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3168
3169 update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3170
3171 Jetpack::plugin_initialize();
3172 }
3173
3174 public static function get_activation_source( $referer_url ) {
3175
3176 if ( defined( 'WP_CLI' ) && WP_CLI ) {
3177 return array( 'wp-cli', null );
3178 }
3179
3180 $referer = parse_url( $referer_url );
3181
3182 $source_type = 'unknown';
3183 $source_query = null;
3184
3185 if ( ! is_array( $referer ) ) {
3186 return array( $source_type, $source_query );
3187 }
3188
3189 $plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3190 $plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3191
3192 if ( isset( $referer['query'] ) ) {
3193 parse_str( $referer['query'], $query_parts );
3194 } else {
3195 $query_parts = array();
3196 }
3197
3198 if ( $plugins_path === $referer['path'] ) {
3199 $source_type = 'list';
3200 } elseif ( $plugins_install_path === $referer['path'] ) {
3201 $tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3202 switch( $tab ) {
3203 case 'popular':
3204 $source_type = 'popular';
3205 break;
3206 case 'recommended':
3207 $source_type = 'recommended';
3208 break;
3209 case 'favorites':
3210 $source_type = 'favorites';
3211 break;
3212 case 'search':
3213 $source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3214 $source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3215 break;
3216 default:
3217 $source_type = 'featured';
3218 }
3219 }
3220
3221 return array( $source_type, $source_query );
3222 }
3223
3224 /**
3225 * Runs before bumping version numbers up to a new version
3226 * @param string $version Version:timestamp
3227 * @param string $old_version Old Version:timestamp or false if not set yet.
3228 * @return null [description]
3229 */
3230 public static function do_version_bump( $version, $old_version ) {
3231 if ( ! $old_version ) { // For new sites
3232 // There used to be stuff here, but this seems like it might be useful to someone in the future...
3233 }
3234 }
3235
3236 /**
3237 * Sets the internal version number and activation state.
3238 * @static
3239 */
3240 public static function plugin_initialize() {
3241 if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3242 Jetpack_Options::update_option( 'activated', 2 );
3243 }
3244
3245 if ( ! Jetpack_Options::get_option( 'version' ) ) {
3246 $version = $old_version = JETPACK__VERSION . ':' . time();
3247 /** This action is documented in class.jetpack.php */
3248 do_action( 'updating_jetpack_version', $version, false );
3249 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3250 }
3251
3252 Jetpack::load_modules();
3253
3254 Jetpack_Options::delete_option( 'do_activate' );
3255 Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3256 }
3257
3258 /**
3259 * Removes all connection options
3260 * @static
3261 */
3262 public static function plugin_deactivation( ) {
3263 require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3264 if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3265 Jetpack_Network::init()->deactivate();
3266 } else {
3267 Jetpack::disconnect( false );
3268 //Jetpack_Heartbeat::init()->deactivate();
3269 }
3270 }
3271
3272 /**
3273 * Disconnects from the Jetpack servers.
3274 * Forgets all connection details and tells the Jetpack servers to do the same.
3275 * @static
3276 */
3277 public static function disconnect( $update_activated_state = true ) {
3278 wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3279 Jetpack::clean_nonces( true );
3280
3281 // If the site is in an IDC because sync is not allowed,
3282 // let's make sure to not disconnect the production site.
3283 if ( ! self::validate_sync_error_idc_option() ) {
3284 $tracking = new Tracking();
3285 $tracking->record_user_event( 'disconnect_site', array() );
3286 Jetpack::load_xml_rpc_client();
3287 $xml = new Jetpack_IXR_Client();
3288 $xml->query( 'jetpack.deregister' );
3289 }
3290
3291 Jetpack_Options::delete_option(
3292 array(
3293 'blog_token',
3294 'user_token',
3295 'user_tokens',
3296 'master_user',
3297 'time_diff',
3298 'fallback_no_verify_ssl_certs',
3299 )
3300 );
3301
3302 Jetpack_IDC::clear_all_idc_options();
3303 Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3304
3305 if ( $update_activated_state ) {
3306 Jetpack_Options::update_option( 'activated', 4 );
3307 }
3308
3309 if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3310 // Check then record unique disconnection if site has never been disconnected previously
3311 if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3312 $jetpack_unique_connection['disconnected'] = 1;
3313 } else {
3314 if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3315 //track unique disconnect
3316 $jetpack = Jetpack::init();
3317
3318 $jetpack->stat( 'connections', 'unique-disconnect' );
3319 $jetpack->do_stats( 'server_side' );
3320 }
3321 // increment number of times disconnected
3322 $jetpack_unique_connection['disconnected'] += 1;
3323 }
3324
3325 Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3326 }
3327
3328 // Delete cached connected user data
3329 $transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3330 delete_transient( $transient_key );
3331
3332 // Delete all the sync related data. Since it could be taking up space.
3333 Sender::get_instance()->uninstall();
3334
3335 // Disable the Heartbeat cron
3336 Jetpack_Heartbeat::init()->deactivate();
3337 }
3338
3339 /**
3340 * Unlinks the current user from the linked WordPress.com user
3341 */
3342 public static function unlink_user( $user_id = null ) {
3343 if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3344 return false;
3345
3346 $user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3347
3348 if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3349 return false;
3350
3351 if ( ! isset( $tokens[ $user_id ] ) )
3352 return false;
3353
3354 Jetpack::load_xml_rpc_client();
3355 $xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3356 $xml->query( 'jetpack.unlink_user', $user_id );
3357
3358 unset( $tokens[ $user_id ] );
3359
3360 Jetpack_Options::update_option( 'user_tokens', $tokens );
3361
3362 /**
3363 * Fires after the current user has been unlinked from WordPress.com.
3364 *
3365 * @since 4.1.0
3366 *
3367 * @param int $user_id The current user's ID.
3368 */
3369 do_action( 'jetpack_unlinked_user', $user_id );
3370
3371 return true;
3372 }
3373
3374 /**
3375 * Attempts Jetpack registration. If it fail, a state flag is set: @see ::admin_page_load()
3376 */
3377 public static function try_registration() {
3378 // The user has agreed to the TOS at some point by now.
3379 Jetpack_Options::update_option( 'tos_agreed', true );
3380
3381 // Let's get some testing in beta versions and such.
3382 if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3383 // Before attempting to connect, let's make sure that the domains are viable.
3384 $domains_to_check = array_unique( array(
3385 'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3386 'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3387 ) );
3388 foreach ( $domains_to_check as $domain ) {
3389 $result = self::connection()->is_usable_domain( $domain );
3390 if ( is_wp_error( $result ) ) {
3391 return $result;
3392 }
3393 }
3394 }
3395
3396 $result = Jetpack::register();
3397
3398 // If there was an error with registration and the site was not registered, record this so we can show a message.
3399 if ( ! $result || is_wp_error( $result ) ) {
3400 return $result;
3401 } else {
3402 return true;
3403 }
3404 }
3405
3406 /**
3407 * Tracking an internal event log. Try not to put too much chaff in here.
3408 *
3409 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3410 */
3411 public static function log( $code, $data = null ) {
3412 // only grab the latest 200 entries
3413 $log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3414
3415 // Append our event to the log
3416 $log_entry = array(
3417 'time' => time(),
3418 'user_id' => get_current_user_id(),
3419 'blog_id' => Jetpack_Options::get_option( 'id' ),
3420 'code' => $code,
3421 );
3422 // Don't bother storing it unless we've got some.
3423 if ( ! is_null( $data ) ) {
3424 $log_entry['data'] = $data;
3425 }
3426 $log[] = $log_entry;
3427
3428 // Try add_option first, to make sure it's not autoloaded.
3429 // @todo: Add an add_option method to Jetpack_Options
3430 if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3431 Jetpack_Options::update_option( 'log', $log );
3432 }
3433
3434 /**
3435 * Fires when Jetpack logs an internal event.
3436 *
3437 * @since 3.0.0
3438 *
3439 * @param array $log_entry {
3440 * Array of details about the log entry.
3441 *
3442 * @param string time Time of the event.
3443 * @param int user_id ID of the user who trigerred the event.
3444 * @param int blog_id Jetpack Blog ID.
3445 * @param string code Unique name for the event.
3446 * @param string data Data about the event.
3447 * }
3448 */
3449 do_action( 'jetpack_log_entry', $log_entry );
3450 }
3451
3452 /**
3453 * Get the internal event log.
3454 *
3455 * @param $event (string) - only return the specific log events
3456 * @param $num (int) - get specific number of latest results, limited to 200
3457 *
3458 * @return array of log events || WP_Error for invalid params
3459 */
3460 public static function get_log( $event = false, $num = false ) {
3461 if ( $event && ! is_string( $event ) ) {
3462 return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3463 }
3464
3465 if ( $num && ! is_numeric( $num ) ) {
3466 return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3467 }
3468
3469 $entire_log = Jetpack_Options::get_option( 'log', array() );
3470
3471 // If nothing set - act as it did before, otherwise let's start customizing the output
3472 if ( ! $num && ! $event ) {
3473 return $entire_log;
3474 } else {
3475 $entire_log = array_reverse( $entire_log );
3476 }
3477
3478 $custom_log_output = array();
3479
3480 if ( $event ) {
3481 foreach ( $entire_log as $log_event ) {
3482 if ( $event == $log_event[ 'code' ] ) {
3483 $custom_log_output[] = $log_event;
3484 }
3485 }
3486 } else {
3487 $custom_log_output = $entire_log;
3488 }
3489
3490 if ( $num ) {
3491 $custom_log_output = array_slice( $custom_log_output, 0, $num );
3492 }
3493
3494 return $custom_log_output;
3495 }
3496
3497 /**
3498 * Log modification of important settings.
3499 */
3500 public static function log_settings_change( $option, $old_value, $value ) {
3501 switch( $option ) {
3502 case 'jetpack_sync_non_public_post_stati':
3503 self::log( $option, $value );
3504 break;
3505 }
3506 }
3507
3508 /**
3509 * Return stat data for WPCOM sync
3510 */
3511 public static function get_stat_data( $encode = true, $extended = true ) {
3512 $data = Jetpack_Heartbeat::generate_stats_array();
3513
3514 if ( $extended ) {
3515 $additional_data = self::get_additional_stat_data();
3516 $data = array_merge( $data, $additional_data );
3517 }
3518
3519 if ( $encode ) {
3520 return json_encode( $data );
3521 }
3522
3523 return $data;
3524 }
3525
3526 /**
3527 * Get additional stat data to sync to WPCOM
3528 */
3529 public static function get_additional_stat_data( $prefix = '' ) {
3530 $return["{$prefix}themes"] = Jetpack::get_parsed_theme_data();
3531 $return["{$prefix}plugins-extra"] = Jetpack::get_parsed_plugin_data();
3532 $return["{$prefix}users"] = (int) Jetpack::get_site_user_count();
3533 $return["{$prefix}site-count"] = 0;
3534
3535 if ( function_exists( 'get_blog_count' ) ) {
3536 $return["{$prefix}site-count"] = get_blog_count();
3537 }
3538 return $return;
3539 }
3540
3541 private static function get_site_user_count() {
3542 global $wpdb;
3543
3544 if ( function_exists( 'wp_is_large_network' ) ) {
3545 if ( wp_is_large_network( 'users' ) ) {
3546 return -1; // Not a real value but should tell us that we are dealing with a large network.
3547 }
3548 }
3549 if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3550 // It wasn't there, so regenerate the data and save the transient
3551 $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3552 set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3553 }
3554 return $user_count;
3555 }
3556
3557 /* Admin Pages */
3558
3559 function admin_init() {
3560 // If the plugin is not connected, display a connect message.
3561 if (
3562 // the plugin was auto-activated and needs its candy
3563 Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3564 ||
3565 // the plugin is active, but was never activated. Probably came from a site-wide network activation
3566 ! Jetpack_Options::get_option( 'activated' )
3567 ) {
3568 Jetpack::plugin_initialize();
3569 }
3570
3571 if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3572 Jetpack_Connection_Banner::init();
3573 } elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3574 // Upgrade: 1.1 -> 1.1.1
3575 // Check and see if host can verify the Jetpack servers' SSL certificate
3576 $args = array();
3577 Client::_wp_remote_request(
3578 Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3579 $args,
3580 true
3581 );
3582 }
3583
3584 if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3585 add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3586 }
3587
3588 add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3589 add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3590 add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3591
3592 if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3593 // Artificially throw errors in certain whitelisted cases during plugin activation
3594 add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3595 }
3596
3597 // Add custom column in wp-admin/users.php to show whether user is linked.
3598 add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3599 add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3600 add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3601 }
3602
3603 function admin_body_class( $admin_body_class = '' ) {
3604 $classes = explode( ' ', trim( $admin_body_class ) );
3605
3606 $classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3607
3608 $admin_body_class = implode( ' ', array_unique( $classes ) );
3609 return " $admin_body_class ";
3610 }
3611
3612 static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3613 return $admin_body_class . ' jetpack-pagestyles ';
3614 }
3615
3616 /**
3617 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3618 * This function artificially throws errors for such cases (whitelisted).
3619 *
3620 * @param string $plugin The activated plugin.
3621 */
3622 function throw_error_on_activate_plugin( $plugin ) {
3623 $active_modules = Jetpack::get_active_modules();
3624
3625 // The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3626 if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3627 $throw = false;
3628
3629 // Try and make sure it really was the stats plugin
3630 if ( ! class_exists( 'ReflectionFunction' ) ) {
3631 if ( 'stats.php' == basename( $plugin ) ) {
3632 $throw = true;
3633 }
3634 } else {
3635 $reflection = new ReflectionFunction( 'stats_get_api_key' );
3636 if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3637 $throw = true;
3638 }
3639 }
3640
3641 if ( $throw ) {
3642 trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3643 }
3644 }
3645 }
3646
3647 function intercept_plugin_error_scrape_init() {
3648 add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3649 }
3650
3651 function intercept_plugin_error_scrape( $action, $result ) {
3652 if ( ! $result ) {
3653 return;
3654 }
3655
3656 foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3657 if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3658 Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3659 }
3660 }
3661 }
3662
3663 function add_remote_request_handlers() {
3664 add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3665 add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3666 }
3667
3668 function remote_request_handlers() {
3669 $action = current_filter();
3670
3671 switch ( current_filter() ) {
3672 case 'wp_ajax_nopriv_jetpack_upload_file' :
3673 $response = $this->upload_handler();
3674 break;
3675
3676 case 'wp_ajax_nopriv_jetpack_update_file' :
3677 $response = $this->upload_handler( true );
3678 break;
3679 default :
3680 $response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3681 break;
3682 }
3683
3684 if ( ! $response ) {
3685 $response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3686 }
3687
3688 if ( is_wp_error( $response ) ) {
3689 $status_code = $response->get_error_data();
3690 $error = $response->get_error_code();
3691 $error_description = $response->get_error_message();
3692
3693 if ( ! is_int( $status_code ) ) {
3694 $status_code = 400;
3695 }
3696
3697 status_header( $status_code );
3698 die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3699 }
3700
3701 status_header( 200 );
3702 if ( true === $response ) {
3703 exit;
3704 }
3705
3706 die( json_encode( (object) $response ) );
3707 }
3708
3709 /**
3710 * Uploads a file gotten from the global $_FILES.
3711 * If `$update_media_item` is true and `post_id` is defined
3712 * the attachment file of the media item (gotten through of the post_id)
3713 * will be updated instead of add a new one.
3714 *
3715 * @param boolean $update_media_item - update media attachment
3716 * @return array - An array describing the uploadind files process
3717 */
3718 function upload_handler( $update_media_item = false ) {
3719 if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3720 return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3721 }
3722
3723 $user = wp_authenticate( '', '' );
3724 if ( ! $user || is_wp_error( $user ) ) {
3725 return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3726 }
3727
3728 wp_set_current_user( $user->ID );
3729
3730 if ( ! current_user_can( 'upload_files' ) ) {
3731 return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3732 }
3733
3734 if ( empty( $_FILES ) ) {
3735 return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3736 }
3737
3738 foreach ( array_keys( $_FILES ) as $files_key ) {
3739 if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3740 return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3741 }
3742 }
3743
3744 $media_keys = array_keys( $_FILES['media'] );
3745
3746 $token = Jetpack_Data::get_access_token( get_current_user_id() );
3747 if ( ! $token || is_wp_error( $token ) ) {
3748 return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3749 }
3750
3751 $uploaded_files = array();
3752 $global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3753 unset( $GLOBALS['post'] );
3754 foreach ( $_FILES['media']['name'] as $index => $name ) {
3755 $file = array();
3756 foreach ( $media_keys as $media_key ) {
3757 $file[$media_key] = $_FILES['media'][$media_key][$index];
3758 }
3759
3760 list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3761
3762 $hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3763 if ( $hmac_provided !== $hmac_file ) {
3764 $uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3765 continue;
3766 }
3767
3768 $_FILES['.jetpack.upload.'] = $file;
3769 $post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3770 if ( ! current_user_can( 'edit_post', $post_id ) ) {
3771 $post_id = 0;
3772 }
3773
3774 if ( $update_media_item ) {
3775 if ( ! isset( $post_id ) || $post_id === 0 ) {
3776 return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3777 }
3778
3779 $media_array = $_FILES['media'];
3780
3781 $file_array['name'] = $media_array['name'][0];
3782 $file_array['type'] = $media_array['type'][0];
3783 $file_array['tmp_name'] = $media_array['tmp_name'][0];
3784 $file_array['error'] = $media_array['error'][0];
3785 $file_array['size'] = $media_array['size'][0];
3786
3787 $edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3788
3789 if ( is_wp_error( $edited_media_item ) ) {
3790 return $edited_media_item;
3791 }
3792
3793 $response = (object) array(
3794 'id' => (string) $post_id,
3795 'file' => (string) $edited_media_item->post_title,
3796 'url' => (string) wp_get_attachment_url( $post_id ),
3797 'type' => (string) $edited_media_item->post_mime_type,
3798 'meta' => (array) wp_get_attachment_metadata( $post_id ),
3799 );
3800
3801 return (array) array( $response );
3802 }
3803
3804 $attachment_id = media_handle_upload(
3805 '.jetpack.upload.',
3806 $post_id,
3807 array(),
3808 array(
3809 'action' => 'jetpack_upload_file',
3810 )
3811 );
3812
3813 if ( ! $attachment_id ) {
3814 $uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3815 } elseif ( is_wp_error( $attachment_id ) ) {
3816 $uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3817 } else {
3818 $attachment = get_post( $attachment_id );
3819 $uploaded_files[$index] = (object) array(
3820 'id' => (string) $attachment_id,
3821 'file' => $attachment->post_title,
3822 'url' => wp_get_attachment_url( $attachment_id ),
3823 'type' => $attachment->post_mime_type,
3824 'meta' => wp_get_attachment_metadata( $attachment_id ),
3825 );
3826 // Zip files uploads are not supported unless they are done for installation purposed
3827 // lets delete them in case something goes wrong in this whole process
3828 if ( 'application/zip' === $attachment->post_mime_type ) {
3829 // Schedule a cleanup for 2 hours from now in case of failed install.
3830 wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3831 }
3832 }
3833 }
3834 if ( ! is_null( $global_post ) ) {
3835 $GLOBALS['post'] = $global_post;
3836 }
3837
3838 return $uploaded_files;
3839 }
3840
3841 /**
3842 * Add help to the Jetpack page
3843 *
3844 * @since Jetpack (1.2.3)
3845 * @return false if not the Jetpack page
3846 */
3847 function admin_help() {
3848 $current_screen = get_current_screen();
3849
3850 // Overview
3851 $current_screen->add_help_tab(
3852 array(
3853 'id' => 'home',
3854 'title' => __( 'Home', 'jetpack' ),
3855 'content' =>
3856 '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3857 '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3858 '<p>' . __( 'On this page, you are able to view the modules available within Jetpack, learn more about them, and activate or deactivate them as needed.', 'jetpack' ) . '</p>',
3859 )
3860 );
3861
3862 // Screen Content
3863 if ( current_user_can( 'manage_options' ) ) {
3864 $current_screen->add_help_tab(
3865 array(
3866 'id' => 'settings',
3867 'title' => __( 'Settings', 'jetpack' ),
3868 'content' =>
3869 '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3870 '<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3871 '<ol>' .
3872 '<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3873 '<li>' . __( 'Using the checkboxes next to each module, you can select multiple modules to toggle via the Bulk Actions menu at the top of the list.', 'jetpack' ) . '</li>' .
3874 '</ol>' .
3875 '<p>' . __( 'Using the tools on the right, you can search for specific modules, filter by module categories or which are active, or change the sorting order.', 'jetpack' ) . '</p>'
3876 )
3877 );
3878 }
3879
3880 // Help Sidebar
3881 $current_screen->set_help_sidebar(
3882 '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3883 '<p><a href="https://jetpack.com/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3884 '<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3885 '<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3886 );
3887 }
3888
3889 function admin_menu_css() {
3890 wp_enqueue_style( 'jetpack-icons' );
3891 }
3892
3893 function admin_menu_order() {
3894 return true;
3895 }
3896
3897 function jetpack_menu_order( $menu_order ) {
3898 $jp_menu_order = array();
3899
3900 foreach ( $menu_order as $index => $item ) {
3901 if ( $item != 'jetpack' ) {
3902 $jp_menu_order[] = $item;
3903 }
3904
3905 if ( $index == 0 ) {
3906 $jp_menu_order[] = 'jetpack';
3907 }
3908 }
3909
3910 return $jp_menu_order;
3911 }
3912
3913 function admin_banner_styles() {
3914 $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3915
3916 if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3917 wp_register_style(
3918 'jetpack-dops-style',
3919 plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3920 array(),
3921 JETPACK__VERSION
3922 );
3923 }
3924
3925 wp_enqueue_style(
3926 'jetpack',
3927 plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3928 array( 'jetpack-dops-style' ),
3929 JETPACK__VERSION . '-20121016'
3930 );
3931 wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3932 wp_style_add_data( 'jetpack', 'suffix', $min );
3933 }
3934
3935 function plugin_action_links( $actions ) {
3936
3937 $jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3938
3939 if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3940 return array_merge(
3941 $jetpack_home,
3942 array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3943 array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3944 $actions
3945 );
3946 }
3947
3948 return array_merge( $jetpack_home, $actions );
3949 }
3950
3951 /*
3952 * Registration flow:
3953 * 1 - ::admin_page_load() action=register
3954 * 2 - ::try_registration()
3955 * 3 - ::register()
3956 * - Creates jetpack_register option containing two secrets and a timestamp
3957 * - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3958 * siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3959 * - That request to jetpack.wordpress.com does not immediately respond. It first makes a request BACK to this site's
3960 * xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3961 * - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3962 * - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3963 * jetpack_id, jetpack_secret, jetpack_public
3964 * - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3965 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3966 * 5 - user logs in with WP.com account
3967 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3968 * - Jetpack_Client_Server::authorize()
3969 * - Jetpack_Client_Server::get_token()
3970 * - GET https://jetpack.wordpress.com/jetpack.token/1/ with
3971 * client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3972 * - which responds with access_token, token_type, scope
3973 * - Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3974 * - Jetpack::activate_default_modules()
3975 * - Deactivates deprecated plugins
3976 * - Activates all default modules
3977 * - Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3978 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3979 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3980 * Done!
3981 */
3982
3983 /**
3984 * Handles the page load events for the Jetpack admin page
3985 */
3986 function admin_page_load() {
3987 $error = false;
3988
3989 // Make sure we have the right body class to hook stylings for subpages off of.
3990 add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3991
3992 if ( ! empty( $_GET['jetpack_restate'] ) ) {
3993 // Should only be used in intermediate redirects to preserve state across redirects
3994 Jetpack::restate();
3995 }
3996
3997 if ( isset( $_GET['connect_url_redirect'] ) ) {
3998 // @todo: Add validation against a known whitelist
3999 $from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4000 // User clicked in the iframe to link their accounts
4001 if ( ! Jetpack::is_user_connected() ) {
4002 $redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4003
4004 add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4005 $connect_url = $this->build_connect_url( true, $redirect, $from );
4006 remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4007
4008 if ( isset( $_GET['notes_iframe'] ) )
4009 $connect_url .= '&notes_iframe';
4010 wp_redirect( $connect_url );
4011 exit;
4012 } else {
4013 if ( ! isset( $_GET['calypso_env'] ) ) {
4014 Jetpack::state( 'message', 'already_authorized' );
4015 wp_safe_redirect( Jetpack::admin_url() );
4016 exit;
4017 } else {
4018 $connect_url = $this->build_connect_url( true, false, $from );
4019 $connect_url .= '&already_authorized=true';
4020 wp_redirect( $connect_url );
4021 exit;
4022 }
4023 }
4024 }
4025
4026
4027 if ( isset( $_GET['action'] ) ) {
4028 switch ( $_GET['action'] ) {
4029 case 'authorize':
4030 if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4031 Jetpack::state( 'message', 'already_authorized' );
4032 wp_safe_redirect( Jetpack::admin_url() );
4033 exit;
4034 }
4035 Jetpack::log( 'authorize' );
4036 $client_server = new Jetpack_Client_Server;
4037 $client_server->client_authorize();
4038 exit;
4039 case 'register' :
4040 if ( ! current_user_can( 'jetpack_connect' ) ) {
4041 $error = 'cheatin';
4042 break;
4043 }
4044 check_admin_referer( 'jetpack-register' );
4045 Jetpack::log( 'register' );
4046 Jetpack::maybe_set_version_option();
4047 $registered = Jetpack::try_registration();
4048 if ( is_wp_error( $registered ) ) {
4049 $error = $registered->get_error_code();
4050 Jetpack::state( 'error', $error );
4051 Jetpack::state( 'error', $registered->get_error_message() );
4052
4053 /**
4054 * Jetpack registration Error.
4055 *
4056 * @since 7.5.0
4057 *
4058 * @param string|int $error The error code.
4059 * @param \WP_Error $registered The error object.
4060 */
4061 do_action( 'jetpack_connection_register_fail', $error, $registered );
4062 break;
4063 }
4064
4065 $from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4066 $redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4067
4068 /**
4069 * Jetpack registration Success.
4070 *
4071 * @since 7.5.0
4072 *
4073 * @param string $from 'from' GET parameter;
4074 */
4075 do_action( 'jetpack_connection_register_success', $from );
4076
4077 $url = $this->build_connect_url( true, $redirect, $from );
4078
4079 if ( ! empty( $_GET['onboarding'] ) ) {
4080 $url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4081 }
4082
4083 if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4084 $url = add_query_arg( 'auth_approved', 'true', $url );
4085 }
4086
4087 wp_redirect( $url );
4088 exit;
4089 case 'activate' :
4090 if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4091 $error = 'cheatin';
4092 break;
4093 }
4094
4095 $module = stripslashes( $_GET['module'] );
4096 check_admin_referer( "jetpack_activate-$module" );
4097 Jetpack::log( 'activate', $module );
4098 if ( ! Jetpack::activate_module( $module ) ) {
4099 Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4100 }
4101 // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4102 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4103 exit;
4104 case 'activate_default_modules' :
4105 check_admin_referer( 'activate_default_modules' );
4106 Jetpack::log( 'activate_default_modules' );
4107 Jetpack::restate();
4108 $min_version = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4109 $max_version = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4110 $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4111 Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4112 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4113 exit;
4114 case 'disconnect' :
4115 if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4116 $error = 'cheatin';
4117 break;
4118 }
4119
4120 check_admin_referer( 'jetpack-disconnect' );
4121 Jetpack::log( 'disconnect' );
4122 Jetpack::disconnect();
4123 wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4124 exit;
4125 case 'reconnect' :
4126 if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4127 $error = 'cheatin';
4128 break;
4129 }
4130
4131 check_admin_referer( 'jetpack-reconnect' );
4132 Jetpack::log( 'reconnect' );
4133 $this->disconnect();
4134 wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4135 exit;
4136 case 'deactivate' :
4137 if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4138 $error = 'cheatin';
4139 break;
4140 }
4141
4142 $modules = stripslashes( $_GET['module'] );
4143 check_admin_referer( "jetpack_deactivate-$modules" );
4144 foreach ( explode( ',', $modules ) as $module ) {
4145 Jetpack::log( 'deactivate', $module );
4146 Jetpack::deactivate_module( $module );
4147 Jetpack::state( 'message', 'module_deactivated' );
4148 }
4149 Jetpack::state( 'module', $modules );
4150 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4151 exit;
4152 case 'unlink' :
4153 $redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4154 check_admin_referer( 'jetpack-unlink' );
4155 Jetpack::log( 'unlink' );
4156 $this->unlink_user();
4157 Jetpack::state( 'message', 'unlinked' );
4158 if ( 'sub-unlink' == $redirect ) {
4159 wp_safe_redirect( admin_url() );
4160 } else {
4161 wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4162 }
4163 exit;
4164 case 'onboard' :
4165 if ( ! current_user_can( 'manage_options' ) ) {
4166 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4167 } else {
4168 Jetpack::create_onboarding_token();
4169 $url = $this->build_connect_url( true );
4170
4171 if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4172 $url = add_query_arg( 'onboarding', $token, $url );
4173 }
4174
4175 $calypso_env = $this->get_calypso_env();
4176 if ( ! empty( $calypso_env ) ) {
4177 $url = add_query_arg( 'calypso_env', $calypso_env, $url );
4178 }
4179
4180 wp_redirect( $url );
4181 exit;
4182 }
4183 exit;
4184 default:
4185 /**
4186 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4187 *
4188 * @since 2.6.0
4189 *
4190 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4191 */
4192 do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4193 }
4194 }
4195
4196 if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4197 self::activate_new_modules( true );
4198 }
4199
4200 $message_code = Jetpack::state( 'message' );
4201 if ( Jetpack::state( 'optin-manage' ) ) {
4202 $activated_manage = $message_code;
4203 $message_code = 'jetpack-manage';
4204 }
4205
4206 switch ( $message_code ) {
4207 case 'jetpack-manage':
4208 $this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), 'https://wordpress.com/sites' ) . '</strong>';
4209 if ( $activated_manage ) {
4210 $this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4211 }
4212 break;
4213
4214 }
4215
4216 $deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4217
4218 if ( ! empty( $deactivated_plugins ) ) {
4219 $deactivated_plugins = explode( ',', $deactivated_plugins );
4220 $deactivated_titles = array();
4221 foreach ( $deactivated_plugins as $deactivated_plugin ) {
4222 if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4223 continue;
4224 }
4225
4226 $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4227 }
4228
4229 if ( $deactivated_titles ) {
4230 if ( $this->message ) {
4231 $this->message .= "<br /><br />\n";
4232 }
4233
4234 $this->message .= wp_sprintf(
4235 _n(
4236 'Jetpack contains the most recent version of the old %l plugin.',
4237 'Jetpack contains the most recent versions of the old %l plugins.',
4238 count( $deactivated_titles ),
4239 'jetpack'
4240 ),
4241 $deactivated_titles
4242 );
4243
4244 $this->message .= "<br />\n";
4245
4246 $this->message .= _n(
4247 'The old version has been deactivated and can be removed from your site.',
4248 'The old versions have been deactivated and can be removed from your site.',
4249 count( $deactivated_titles ),
4250 'jetpack'
4251 );
4252 }
4253 }
4254
4255 $this->privacy_checks = Jetpack::state( 'privacy_checks' );
4256
4257 if ( $this->message || $this->error || $this->privacy_checks ) {
4258 add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4259 }
4260
4261 add_filter( 'jetpack_short_module_description', 'wptexturize' );
4262 }
4263
4264 function admin_notices() {
4265
4266 if ( $this->error ) {
4267 ?>
4268 <div id="message" class="jetpack-message jetpack-err">
4269 <div class="squeezer">
4270 <h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4271 <?php if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4272 <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4273 <?php endif; ?>
4274 </div>
4275 </div>
4276 <?php
4277 }
4278
4279 if ( $this->message ) {
4280 ?>
4281 <div id="message" class="jetpack-message">
4282 <div class="squeezer">
4283 <h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4284 </div>
4285 </div>
4286 <?php
4287 }
4288
4289 if ( $this->privacy_checks ) :
4290 $module_names = $module_slugs = array();
4291
4292 $privacy_checks = explode( ',', $this->privacy_checks );
4293 $privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4294 foreach ( $privacy_checks as $module_slug ) {
4295 $module = Jetpack::get_module( $module_slug );
4296 if ( ! $module ) {
4297 continue;
4298 }
4299
4300 $module_slugs[] = $module_slug;
4301 $module_names[] = "<strong>{$module['name']}</strong>";
4302 }
4303
4304 $module_slugs = join( ',', $module_slugs );
4305 ?>
4306 <div id="message" class="jetpack-message jetpack-err">
4307 <div class="squeezer">
4308 <h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4309 <p><?php
4310 echo wp_kses(
4311 wptexturize(
4312 wp_sprintf(
4313 _nx(
4314 "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4315 "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4316 count( $privacy_checks ),
4317 '%l = list of Jetpack module/feature names',
4318 'jetpack'
4319 ),
4320 $module_names
4321 )
4322 ),
4323 array( 'strong' => true )
4324 );
4325
4326 echo "\n<br />\n";
4327
4328 echo wp_kses(
4329 sprintf(
4330 _nx(
4331 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4332 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4333 count( $privacy_checks ),
4334 '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4335 'jetpack'
4336 ),
4337 wp_nonce_url(
4338 Jetpack::admin_url(
4339 array(
4340 'page' => 'jetpack',
4341 'action' => 'deactivate',
4342 'module' => urlencode( $module_slugs ),
4343 )
4344 ),
4345 "jetpack_deactivate-$module_slugs"
4346 ),
4347 esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4348 ),
4349 array( 'a' => array( 'href' => true, 'title' => true ) )
4350 );
4351 ?></p>
4352 </div>
4353 </div>
4354 <?php endif;
4355 }
4356
4357 /**
4358 * Record a stat for later output. This will only currently output in the admin_footer.
4359 */
4360 function stat( $group, $detail ) {
4361 if ( ! isset( $this->stats[ $group ] ) )
4362 $this->stats[ $group ] = array();
4363 $this->stats[ $group ][] = $detail;
4364 }
4365
4366 /**
4367 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4368 */
4369 function do_stats( $method = '' ) {
4370 if ( is_array( $this->stats ) && count( $this->stats ) ) {
4371 foreach ( $this->stats as $group => $stats ) {
4372 if ( is_array( $stats ) && count( $stats ) ) {
4373 $args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4374 if ( 'server_side' === $method ) {
4375 self::do_server_side_stat( $args );
4376 } else {
4377 echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4378 }
4379 }
4380 unset( $this->stats[ $group ] );
4381 }
4382 }
4383 }
4384
4385 /**
4386 * Runs stats code for a one-off, server-side.
4387 *
4388 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4389 *
4390 * @return bool If it worked.
4391 */
4392 static function do_server_side_stat( $args ) {
4393 $response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4394 if ( is_wp_error( $response ) )
4395 return false;
4396
4397 if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4398 return false;
4399
4400 return true;
4401 }
4402
4403 /**
4404 * Builds the stats url.
4405 *
4406 * @param $args array|string The arguments to append to the URL.
4407 *
4408 * @return string The URL to be pinged.
4409 */
4410 static function build_stats_url( $args ) {
4411 $defaults = array(
4412 'v' => 'wpcom2',
4413 'rand' => md5( mt_rand( 0, 999 ) . time() ),
4414 );
4415 $args = wp_parse_args( $args, $defaults );
4416 /**
4417 * Filter the URL used as the Stats tracking pixel.
4418 *
4419 * @since 2.3.2
4420 *
4421 * @param string $url Base URL used as the Stats tracking pixel.
4422 */
4423 $base_url = apply_filters(
4424 'jetpack_stats_base_url',
4425 'https://pixel.wp.com/g.gif'
4426 );
4427 $url = add_query_arg( $args, $base_url );
4428 return $url;
4429 }
4430
4431 /**
4432 * Get the role of the current user.
4433 *
4434 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4435 *
4436 * @access public
4437 * @static
4438 *
4439 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4440 */
4441 public static function translate_current_user_to_role() {
4442 _deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4443
4444 $roles = new Roles();
4445 return $roles->translate_current_user_to_role();
4446 }
4447
4448 /**
4449 * Get the role of a particular user.
4450 *
4451 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4452 *
4453 * @access public
4454 * @static
4455 *
4456 * @param \WP_User $user User object.
4457 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4458 */
4459 public static function translate_user_to_role( $user ) {
4460 _deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4461
4462 $roles = new Roles();
4463 return $roles->translate_user_to_role( $user );
4464 }
4465
4466 /**
4467 * Get the minimum capability for a role.
4468 *
4469 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4470 *
4471 * @access public
4472 * @static
4473 *
4474 * @param string $role Role name.
4475 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4476 */
4477 public static function translate_role_to_cap( $role ) {
4478 _deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4479
4480 $roles = new Roles();
4481 return $roles->translate_role_to_cap( $role );
4482 }
4483
4484 static function sign_role( $role, $user_id = null ) {
4485 if ( empty( $user_id ) ) {
4486 $user_id = (int) get_current_user_id();
4487 }
4488
4489 if ( ! $user_id ) {
4490 return false;
4491 }
4492
4493 $token = Jetpack_Data::get_access_token();
4494 if ( ! $token || is_wp_error( $token ) ) {
4495 return false;
4496 }
4497
4498 return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4499 }
4500
4501
4502 /**
4503 * Builds a URL to the Jetpack connection auth page
4504 *
4505 * @since 3.9.5
4506 *
4507 * @param bool $raw If true, URL will not be escaped.
4508 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4509 * If string, will be a custom redirect.
4510 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4511 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4512 *
4513 * @return string Connect URL
4514 */
4515 function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4516 $site_id = Jetpack_Options::get_option( 'id' );
4517 $blog_token = Jetpack_Data::get_access_token();
4518
4519 if ( $register || ! $blog_token || ! $site_id ) {
4520 $url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4521
4522 if ( ! empty( $redirect ) ) {
4523 $url = add_query_arg(
4524 'redirect',
4525 urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4526 $url
4527 );
4528 }
4529
4530 if( is_network_admin() ) {
4531 $url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4532 }
4533 } else {
4534
4535 // Let's check the existing blog token to see if we need to re-register. We only check once per minute
4536 // because otherwise this logic can get us in to a loop.
4537 $last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4538 if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4539 Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4540
4541 $response = Client::wpcom_json_api_request_as_blog(
4542 sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4543 '1.1'
4544 );
4545
4546 if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4547
4548 // Generating a register URL instead to refresh the existing token
4549 return $this->build_connect_url( $raw, $redirect, $from, true );
4550 }
4551 }
4552
4553 if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4554 $gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4555 }
4556
4557 $roles = new Roles();
4558 $role = $roles->translate_current_user_to_role();
4559 $signed_role = self::sign_role( $role );
4560
4561 $user = wp_get_current_user();
4562
4563 $jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4564 $redirect = $redirect
4565 ? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4566 : $jetpack_admin_page;
4567
4568 if( isset( $_REQUEST['is_multisite'] ) ) {
4569 $redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4570 }
4571
4572 $secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4573
4574 /**
4575 * Filter the type of authorization.
4576 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4577 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4578 *
4579 * @since 4.3.3
4580 *
4581 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4582 */
4583 $auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4584
4585
4586 $tracks = new Tracking();
4587 $tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4588
4589 $args = urlencode_deep(
4590 array(
4591 'response_type' => 'code',
4592 'client_id' => Jetpack_Options::get_option( 'id' ),
4593 'redirect_uri' => add_query_arg(
4594 array(
4595 'action' => 'authorize',
4596 '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4597 'redirect' => urlencode( $redirect ),
4598 ),
4599 esc_url( admin_url( 'admin.php?page=jetpack' ) )
4600 ),
4601 'state' => $user->ID,
4602 'scope' => $signed_role,
4603 'user_email' => $user->user_email,
4604 'user_login' => $user->user_login,
4605 'is_active' => Jetpack::is_active(),
4606 'jp_version' => JETPACK__VERSION,
4607 'auth_type' => $auth_type,
4608 'secret' => $secrets['secret_1'],
4609 'locale' => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4610 'blogname' => get_option( 'blogname' ),
4611 'site_url' => site_url(),
4612 'home_url' => home_url(),
4613 'site_icon' => get_site_icon_url(),
4614 'site_lang' => get_locale(),
4615 '_ui' => $tracks_identity['_ui'],
4616 '_ut' => $tracks_identity['_ut'],
4617 'site_created' => Jetpack::get_assumed_site_creation_date(),
4618 )
4619 );
4620
4621 self::apply_activation_source_to_args( $args );
4622
4623 $url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4624 }
4625
4626 if ( $from ) {
4627 $url = add_query_arg( 'from', $from, $url );
4628 }
4629
4630 // Ensure that class to get the affiliate code is loaded
4631 if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4632 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4633 }
4634 // Get affiliate code and add it to the URL
4635 $url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4636
4637 $calypso_env = $this->get_calypso_env();
4638
4639 if ( ! empty( $calypso_env ) ) {
4640 $url = add_query_arg( 'calypso_env', $calypso_env, $url );
4641 }
4642
4643 return $raw ? esc_url_raw( $url ) : esc_url( $url );
4644 }
4645
4646 /**
4647 * Get our assumed site creation date.
4648 * Calculated based on the earlier date of either:
4649 * - Earliest admin user registration date.
4650 * - Earliest date of post of any post type.
4651 *
4652 * @since 7.2.0
4653 *
4654 * @return string Assumed site creation date and time.
4655 */
4656 public static function get_assumed_site_creation_date() {
4657 $earliest_registered_users = get_users( array(
4658 'role' => 'administrator',
4659 'orderby' => 'user_registered',
4660 'order' => 'ASC',
4661 'fields' => array( 'user_registered' ),
4662 'number' => 1,
4663 ) );
4664 $earliest_registration_date = $earliest_registered_users[0]->user_registered;
4665
4666 $earliest_posts = get_posts( array(
4667 'posts_per_page' => 1,
4668 'post_type' => 'any',
4669 'post_status' => 'any',
4670 'orderby' => 'date',
4671 'order' => 'ASC',
4672 ) );
4673
4674 // If there are no posts at all, we'll count only on user registration date.
4675 if ( $earliest_posts ) {
4676 $earliest_post_date = $earliest_posts[0]->post_date;
4677 } else {
4678 $earliest_post_date = PHP_INT_MAX;
4679 }
4680
4681 return min( $earliest_registration_date, $earliest_post_date );
4682 }
4683
4684 public static function apply_activation_source_to_args( &$args ) {
4685 list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4686
4687 if ( $activation_source_name ) {
4688 $args['_as'] = urlencode( $activation_source_name );
4689 }
4690
4691 if ( $activation_source_keyword ) {
4692 $args['_ak'] = urlencode( $activation_source_keyword );
4693 }
4694 }
4695
4696 function build_reconnect_url( $raw = false ) {
4697 $url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4698 return $raw ? $url : esc_url( $url );
4699 }
4700
4701 public static function admin_url( $args = null ) {
4702 $args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4703 $url = add_query_arg( $args, admin_url( 'admin.php' ) );
4704 return $url;
4705 }
4706
4707 public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4708 $actionurl = str_replace( '&amp;', '&', $actionurl );
4709 return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4710 }
4711
4712 function dismiss_jetpack_notice() {
4713
4714 if ( ! isset( $_GET['jetpack-notice'] ) ) {
4715 return;
4716 }
4717
4718 switch( $_GET['jetpack-notice'] ) {
4719 case 'dismiss':
4720 if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4721
4722 require_once ABSPATH . 'wp-admin/includes/plugin.php';
4723 deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4724 wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4725 }
4726 break;
4727 case 'jetpack-protect-multisite-opt-out':
4728
4729 if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4730 // Don't show the banner again
4731
4732 update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4733 // redirect back to the page that had the notice
4734 if ( wp_get_referer() ) {
4735 wp_safe_redirect( wp_get_referer() );
4736 } else {
4737 // Take me to Jetpack
4738 wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4739 }
4740 }
4741 break;
4742 }
4743 }
4744
4745 public static function sort_modules( $a, $b ) {
4746 if ( $a['sort'] == $b['sort'] )
4747 return 0;
4748
4749 return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4750 }
4751
4752 function ajax_recheck_ssl() {
4753 check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4754 $result = Jetpack::permit_ssl( true );
4755 wp_send_json( array(
4756 'enabled' => $result,
4757 'message' => get_transient( 'jetpack_https_test_message' )
4758 ) );
4759 }
4760
4761 /* Client API */
4762
4763 /**
4764 * Returns the requested Jetpack API URL
4765 *
4766 * @return string
4767 */
4768 public static function api_url( $relative_url ) {
4769 return trailingslashit( JETPACK__API_BASE . $relative_url ) . JETPACK__API_VERSION . '/';
4770 }
4771
4772 /**
4773 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4774 */
4775 public static function fix_url_for_bad_hosts( $url ) {
4776 if ( 0 !== strpos( $url, 'https://' ) ) {
4777 return $url;
4778 }
4779
4780 switch ( JETPACK_CLIENT__HTTPS ) {
4781 case 'ALWAYS' :
4782 return $url;
4783 case 'NEVER' :
4784 return set_url_scheme( $url, 'http' );
4785 // default : case 'AUTO' :
4786 }
4787
4788 // we now return the unmodified SSL URL by default, as a security precaution
4789 return $url;
4790 }
4791
4792 /**
4793 * Create a random secret for validating onboarding payload
4794 *
4795 * @return string Secret token
4796 */
4797 public static function create_onboarding_token() {
4798 if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4799 $token = wp_generate_password( 32, false );
4800 Jetpack_Options::update_option( 'onboarding', $token );
4801 }
4802
4803 return $token;
4804 }
4805
4806 /**
4807 * Remove the onboarding token
4808 *
4809 * @return bool True on success, false on failure
4810 */
4811 public static function invalidate_onboarding_token() {
4812 return Jetpack_Options::delete_option( 'onboarding' );
4813 }
4814
4815 /**
4816 * Validate an onboarding token for a specific action
4817 *
4818 * @return boolean True if token/action pair is accepted, false if not
4819 */
4820 public static function validate_onboarding_token_action( $token, $action ) {
4821 // Compare tokens, bail if tokens do not match
4822 if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4823 return false;
4824 }
4825
4826 // List of valid actions we can take
4827 $valid_actions = array(
4828 '/jetpack/v4/settings',
4829 );
4830
4831 // Whitelist the action
4832 if ( ! in_array( $action, $valid_actions ) ) {
4833 return false;
4834 }
4835
4836 return true;
4837 }
4838
4839 /**
4840 * Checks to see if the URL is using SSL to connect with Jetpack
4841 *
4842 * @since 2.3.3
4843 * @return boolean
4844 */
4845 public static function permit_ssl( $force_recheck = false ) {
4846 // Do some fancy tests to see if ssl is being supported
4847 if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4848 $message = '';
4849 if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4850 $ssl = 0;
4851 } else {
4852 switch ( JETPACK_CLIENT__HTTPS ) {
4853 case 'NEVER':
4854 $ssl = 0;
4855 $message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4856 break;
4857 case 'ALWAYS':
4858 case 'AUTO':
4859 default:
4860 $ssl = 1;
4861 break;
4862 }
4863
4864 // If it's not 'NEVER', test to see
4865 if ( $ssl ) {
4866 if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4867 $ssl = 0;
4868 $message = __( 'WordPress reports no SSL support', 'jetpack' );
4869 } else {
4870 $response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4871 if ( is_wp_error( $response ) ) {
4872 $ssl = 0;
4873 $message = __( 'WordPress reports no SSL support', 'jetpack' );
4874 } elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4875 $ssl = 0;
4876 $message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4877 }
4878 }
4879 }
4880 }
4881 set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4882 set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4883 }
4884
4885 return (bool) $ssl;
4886 }
4887
4888 /*
4889 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4890 */
4891 public function alert_auto_ssl_fail() {
4892 if ( ! current_user_can( 'manage_options' ) )
4893 return;
4894
4895 $ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4896 ?>
4897
4898 <div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4899 <div class="jp-banner__content">
4900 <h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4901 <p><?php _e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
4902 <p>
4903 <?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4904 <a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4905 <span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4906 </p>
4907 <p>
4908 <?php printf( __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
4909 esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
4910 esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4911 </p>
4912 </div>
4913 </div>
4914 <style>
4915 #jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4916 </style>
4917 <script type="text/javascript">
4918 jQuery( document ).ready( function( $ ) {
4919 $( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4920 var $this = $( this );
4921 $this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4922 $( '#jetpack-recheck-ssl-output' ).html( '' );
4923 e.preventDefault();
4924 var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4925 $.post( ajaxurl, data )
4926 .done( function( response ) {
4927 if ( response.enabled ) {
4928 $( '#jetpack-ssl-warning' ).hide();
4929 } else {
4930 this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4931 $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4932 }
4933 }.bind( $this ) );
4934 } );
4935 } );
4936 </script>
4937
4938 <?php
4939 }
4940
4941 /**
4942 * Returns the Jetpack XML-RPC API
4943 *
4944 * @return string
4945 */
4946 public static function xmlrpc_api_url() {
4947 $base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4948 return untrailingslashit( $base ) . '/xmlrpc.php';
4949 }
4950
4951 public static function connection() {
4952 return self::init()->connection_manager;
4953 }
4954
4955 /**
4956 * Creates two secret tokens and the end of life timestamp for them.
4957 *
4958 * Note these tokens are unique per call, NOT static per site for connecting.
4959 *
4960 * @since 2.6
4961 * @return array
4962 */
4963 public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4964 if ( false === $user_id ) {
4965 $user_id = get_current_user_id();
4966 }
4967
4968 return self::connection()->generate_secrets( $action, $user_id, $exp );
4969 }
4970
4971 public static function get_secrets( $action, $user_id ) {
4972 $secrets = self::connection()->get_secrets( $action, $user_id );
4973
4974 if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4975 return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4976 }
4977
4978 if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4979 return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4980 }
4981
4982 return $secrets;
4983 }
4984
4985 /**
4986 * @deprecated 7.5 Use Connection_Manager instead.
4987 *
4988 * @param $action
4989 * @param $user_id
4990 */
4991 public static function delete_secrets( $action, $user_id ) {
4992 return self::connection()->delete_secrets( $action, $user_id );
4993 }
4994
4995 /**
4996 * Builds the timeout limit for queries talking with the wpcom servers.
4997 *
4998 * Based on local php max_execution_time in php.ini
4999 *
5000 * @since 2.6
5001 * @return int
5002 * @deprecated
5003 **/
5004 public function get_remote_query_timeout_limit() {
5005 _deprecated_function( __METHOD__, 'jetpack-5.4' );
5006 return Jetpack::get_max_execution_time();
5007 }
5008
5009 /**
5010 * Builds the timeout limit for queries talking with the wpcom servers.
5011 *
5012 * Based on local php max_execution_time in php.ini
5013 *
5014 * @since 5.4
5015 * @return int
5016 **/
5017 public static function get_max_execution_time() {
5018 $timeout = (int) ini_get( 'max_execution_time' );
5019
5020 // Ensure exec time set in php.ini
5021 if ( ! $timeout ) {
5022 $timeout = 30;
5023 }
5024 return $timeout;
5025 }
5026
5027 /**
5028 * Sets a minimum request timeout, and returns the current timeout
5029 *
5030 * @since 5.4
5031 **/
5032 public static function set_min_time_limit( $min_timeout ) {
5033 $timeout = self::get_max_execution_time();
5034 if ( $timeout < $min_timeout ) {
5035 $timeout = $min_timeout;
5036 set_time_limit( $timeout );
5037 }
5038 return $timeout;
5039 }
5040
5041
5042 /**
5043 * Takes the response from the Jetpack register new site endpoint and
5044 * verifies it worked properly.
5045 *
5046 * @since 2.6
5047 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5048 **/
5049 public function validate_remote_register_response( $response ) {
5050 if ( is_wp_error( $response ) ) {
5051 return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5052 }
5053
5054 $code = wp_remote_retrieve_response_code( $response );
5055 $entity = wp_remote_retrieve_body( $response );
5056 if ( $entity )
5057 $registration_response = json_decode( $entity );
5058 else
5059 $registration_response = false;
5060
5061 $code_type = intval( $code / 100 );
5062 if ( 5 == $code_type ) {
5063 return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5064 } elseif ( 408 == $code ) {
5065 return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5066 } elseif ( ! empty( $registration_response->error ) ) {
5067 if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5068 $error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5069 } else {
5070 $error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5071 }
5072
5073 return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5074 } elseif ( 200 != $code ) {
5075 return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5076 }
5077
5078 // Jetpack ID error block
5079 if ( empty( $registration_response->jetpack_id ) ) {
5080 return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5081 } elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5082 return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5083 } elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5084 return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5085 }
5086
5087 return $registration_response;
5088 }
5089 /**
5090 * @return bool|WP_Error
5091 */
5092 public static function register() {
5093 $tracking = new Tracking();
5094 $tracking->record_user_event( 'jpc_register_begin' );
5095 add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5096 $secrets = Jetpack::generate_secrets( 'register' );
5097
5098 if (
5099 empty( $secrets['secret_1'] ) ||
5100 empty( $secrets['secret_2'] ) ||
5101 empty( $secrets['exp'] )
5102 ) {
5103 return new Jetpack_Error( 'missing_secrets' );
5104 }
5105
5106 // better to try (and fail) to set a higher timeout than this system
5107 // supports than to have register fail for more users than it should
5108 $timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5109
5110 $gmt_offset = get_option( 'gmt_offset' );
5111 if ( ! $gmt_offset ) {
5112 $gmt_offset = 0;
5113 }
5114
5115 $stats_options = get_option( 'stats_options' );
5116 $stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5117
5118 $tracks = new Tracking();
5119 $tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5120
5121 $args = array(
5122 'method' => 'POST',
5123 'body' => array(
5124 'siteurl' => site_url(),
5125 'home' => home_url(),
5126 'gmt_offset' => $gmt_offset,
5127 'timezone_string' => (string) get_option( 'timezone_string' ),
5128 'site_name' => (string) get_option( 'blogname' ),
5129 'secret_1' => $secrets['secret_1'],
5130 'secret_2' => $secrets['secret_2'],
5131 'site_lang' => get_locale(),
5132 'timeout' => $timeout,
5133 'stats_id' => $stats_id,
5134 'state' => get_current_user_id(),
5135 '_ui' => $tracks_identity['_ui'],
5136 '_ut' => $tracks_identity['_ut'],
5137 'site_created' => Jetpack::get_assumed_site_creation_date(),
5138 'jetpack_version' => JETPACK__VERSION,
5139 'ABSPATH' => defined( 'ABSPATH' ) ? ABSPATH : '',
5140 ),
5141 'headers' => array(
5142 'Accept' => 'application/json',
5143 ),
5144 'timeout' => $timeout,
5145 );
5146
5147 self::apply_activation_source_to_args( $args['body'] );
5148
5149 $response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5150
5151 // Make sure the response is valid and does not contain any Jetpack errors
5152 $registration_details = Jetpack::init()->validate_remote_register_response( $response );
5153 if ( is_wp_error( $registration_details ) ) {
5154 return $registration_details;
5155 } elseif ( ! $registration_details ) {
5156 return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5157 }
5158
5159 if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5160 return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5161 }
5162
5163 if ( isset( $registration_details->jetpack_public ) ) {
5164 $jetpack_public = (int) $registration_details->jetpack_public;
5165 } else {
5166 $jetpack_public = false;
5167 }
5168
5169 Jetpack_Options::update_options(
5170 array(
5171 'id' => (int) $registration_details->jetpack_id,
5172 'blog_token' => (string) $registration_details->jetpack_secret,
5173 'public' => $jetpack_public,
5174 )
5175 );
5176
5177 /**
5178 * Fires when a site is registered on WordPress.com.
5179 *
5180 * @since 3.7.0
5181 *
5182 * @param int $json->jetpack_id Jetpack Blog ID.
5183 * @param string $json->jetpack_secret Jetpack Blog Token.
5184 * @param int|bool $jetpack_public Is the site public.
5185 */
5186 do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5187
5188 $jetpack = Jetpack::init();
5189
5190 return true;
5191 }
5192
5193 /**
5194 * If the db version is showing something other that what we've got now, bump it to current.
5195 *
5196 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5197 */
5198 public static function maybe_set_version_option() {
5199 list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5200 if ( JETPACK__VERSION != $version ) {
5201 Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5202
5203 if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5204 /** This action is documented in class.jetpack.php */
5205 do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5206 }
5207
5208 return true;
5209 }
5210 return false;
5211 }
5212
5213 /* Client Server API */
5214
5215 /**
5216 * Loads the Jetpack XML-RPC client
5217 */
5218 public static function load_xml_rpc_client() {
5219 require_once ABSPATH . WPINC . '/class-IXR.php';
5220 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5221 }
5222
5223 /**
5224 * Resets the saved authentication state in between testing requests.
5225 */
5226 public function reset_saved_auth_state() {
5227 $this->xmlrpc_verification = null;
5228 $this->rest_authentication_status = null;
5229 }
5230
5231 /**
5232 * Verifies the signature of the current request.
5233 *
5234 * @return false|array
5235 */
5236 function verify_xml_rpc_signature() {
5237 if ( is_null( $this->xmlrpc_verification ) ) {
5238 $this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
5239
5240 if ( is_wp_error( $this->xmlrpc_verification ) ) {
5241 /**
5242 * Action for logging XMLRPC signature verification errors. This data is sensitive.
5243 *
5244 * Error codes:
5245 * - malformed_token
5246 * - malformed_user_id
5247 * - unknown_token
5248 * - could_not_sign
5249 * - invalid_nonce
5250 * - signature_mismatch
5251 *
5252 * @since 7.5.0
5253 *
5254 * @param WP_Error $signature_verification_error The verification error
5255 */
5256 do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
5257 }
5258 }
5259
5260 return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
5261 }
5262
5263 /**
5264 * Verifies the signature of the current request.
5265 *
5266 * This function has side effects and should not be used. Instead,
5267 * use the memoized version `->verify_xml_rpc_signature()`.
5268 *
5269 * @internal
5270 */
5271 private function internal_verify_xml_rpc_signature() {
5272 // It's not for us
5273 if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5274 return false;
5275 }
5276
5277 $signature_details = array(
5278 'token' => isset( $_GET['token'] ) ? wp_unslash( $_GET['token'] ) : '',
5279 'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
5280 'nonce' => isset( $_GET['nonce'] ) ? wp_unslash( $_GET['nonce'] ) : '',
5281 'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
5282 'method' => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
5283 'url' => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
5284 'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
5285 );
5286
5287 @list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
5288 if (
5289 empty( $token_key )
5290 ||
5291 empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5292 ) {
5293 return new WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
5294 }
5295
5296 if ( '0' === $user_id ) {
5297 $token_type = 'blog';
5298 $user_id = 0;
5299 } else {
5300 $token_type = 'user';
5301 if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5302 return new WP_Error( 'malformed_user_id', 'Malformed user_id in request', compact( 'signature_details' ) );
5303 }
5304 $user_id = (int) $user_id;
5305
5306 $user = new WP_User( $user_id );
5307 if ( ! $user || ! $user->exists() ) {
5308 return new WP_Error( 'unknown_user', sprintf( 'User %d does not exist', $user_id ), compact( 'signature_details' ) );
5309 }
5310 }
5311
5312 $token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
5313 if ( is_wp_error( $token ) ) {
5314 $token->add_data( compact( 'signature_details' ) );
5315 return $token;
5316 } elseif ( ! $token ) {
5317 return new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
5318 }
5319
5320 $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5321 if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5322 $post_data = $_POST;
5323 $file_hashes = array();
5324 foreach ( $post_data as $post_data_key => $post_data_value ) {
5325 if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5326 continue;
5327 }
5328 $post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5329 $file_hashes[$post_data_key] = $post_data_value;
5330 }
5331
5332 foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5333 unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5334 $post_data[$post_data_key] = $post_data_value;
5335 }
5336
5337 ksort( $post_data );
5338
5339 $body = http_build_query( stripslashes_deep( $post_data ) );
5340 } elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5341 $body = file_get_contents( 'php://input' );
5342 } else {
5343 $body = null;
5344 }
5345
5346 $signature = $jetpack_signature->sign_current_request(
5347 array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5348 );
5349
5350 $signature_details['url'] = $jetpack_signature->current_request_url;
5351
5352 if ( ! $signature ) {
5353 return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
5354 } else if ( is_wp_error( $signature ) ) {
5355 return $signature;
5356 }
5357
5358 $timestamp = (int) $_GET['timestamp'];
5359 $nonce = stripslashes( (string) $_GET['nonce'] );
5360
5361 // Use up the nonce regardless of whether the signature matches.
5362 if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5363 return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
5364 }
5365
5366 // Be careful about what you do with this debugging data.
5367 // If a malicious requester has access to the expected signature,
5368 // bad things might be possible.
5369 $signature_details['expected'] = $signature;
5370
5371 if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5372 return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
5373 }
5374
5375 // Let's see if this is onboarding. In such case, use user token type and the provided user id.
5376 if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5377 if ( ! empty( $_GET['onboarding'] ) ) {
5378 $jpo = $_GET;
5379 } else {
5380 $jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5381 }
5382
5383 $jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5384 $jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5385
5386 if (
5387 isset( $jpo_user ) && isset( $jpo_token ) &&
5388 is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5389 isset( $_GET['rest_route'] ) &&
5390 self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5391 ) {
5392 $jpUser = get_user_by( 'email', $jpo_user );
5393 if ( is_a( $jpUser, 'WP_User' ) ) {
5394 wp_set_current_user( $jpUser->ID );
5395 $user_can = is_multisite()
5396 ? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5397 : current_user_can( 'manage_options' );
5398 if ( $user_can ) {
5399 $token_type = 'user';
5400 $token->external_user_id = $jpUser->ID;
5401 }
5402 }
5403 }
5404 }
5405
5406 return array(
5407 'type' => $token_type,
5408 'token_key' => $token_key,
5409 'user_id' => $token->external_user_id,
5410 );
5411 }
5412
5413 /**
5414 * Authenticates XML-RPC and other requests from the Jetpack Server
5415 */
5416 function authenticate_jetpack( $user, $username, $password ) {
5417 if ( is_a( $user, 'WP_User' ) ) {
5418 return $user;
5419 }
5420
5421 $token_details = $this->verify_xml_rpc_signature();
5422
5423 if ( ! $token_details ) {
5424 return $user;
5425 }
5426
5427 if ( 'user' !== $token_details['type'] ) {
5428 return $user;
5429 }
5430
5431 if ( ! $token_details['user_id'] ) {
5432 return $user;
5433 }
5434
5435 nocache_headers();
5436
5437 return new WP_User( $token_details['user_id'] );
5438 }
5439
5440 // Authenticates requests from Jetpack server to WP REST API endpoints.
5441 // Uses the existing XMLRPC request signing implementation.
5442 function wp_rest_authenticate( $user ) {
5443 if ( ! empty( $user ) ) {
5444 // Another authentication method is in effect.
5445 return $user;
5446 }
5447
5448 if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5449 // Nothing to do for this authentication method.
5450 return null;
5451 }
5452
5453 if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5454 // Nothing to do for this authentication method.
5455 return null;
5456 }
5457
5458 // Ensure that we always have the request body available. At this
5459 // point, the WP REST API code to determine the request body has not
5460 // run yet. That code may try to read from 'php://input' later, but
5461 // this can only be done once per request in PHP versions prior to 5.6.
5462 // So we will go ahead and perform this read now if needed, and save
5463 // the request body where both the Jetpack signature verification code
5464 // and the WP REST API code can see it.
5465 if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5466 $GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5467 }
5468 $this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5469
5470 // Only support specific request parameters that have been tested and
5471 // are known to work with signature verification. A different method
5472 // can be passed to the WP REST API via the '?_method=' parameter if
5473 // needed.
5474 if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5475 $this->rest_authentication_status = new WP_Error(
5476 'rest_invalid_request',
5477 __( 'This request method is not supported.', 'jetpack' ),
5478 array( 'status' => 400 )
5479 );
5480 return null;
5481 }
5482 if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5483 $this->rest_authentication_status = new WP_Error(
5484 'rest_invalid_request',
5485 __( 'This request method does not support body parameters.', 'jetpack' ),
5486 array( 'status' => 400 )
5487 );
5488 return null;
5489 }
5490
5491 $verified = $this->verify_xml_rpc_signature();
5492
5493 if (
5494 $verified &&
5495 isset( $verified['type'] ) &&
5496 'user' === $verified['type'] &&
5497 ! empty( $verified['user_id'] )
5498 ) {
5499 // Authentication successful.
5500 $this->rest_authentication_status = true;
5501 return $verified['user_id'];
5502 }
5503
5504 // Something else went wrong. Probably a signature error.
5505 $this->rest_authentication_status = new WP_Error(
5506 'rest_invalid_signature',
5507 __( 'The request is not signed correctly.', 'jetpack' ),
5508 array( 'status' => 400 )
5509 );
5510 return null;
5511 }
5512
5513 /**
5514 * Report authentication status to the WP REST API.
5515 *
5516 * @param WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5517 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5518 */
5519 public function wp_rest_authentication_errors( $value ) {
5520 if ( $value !== null ) {
5521 return $value;
5522 }
5523 return $this->rest_authentication_status;
5524 }
5525
5526 function add_nonce( $timestamp, $nonce ) {
5527 global $wpdb;
5528 static $nonces_used_this_request = array();
5529
5530 if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5531 return $nonces_used_this_request["$timestamp:$nonce"];
5532 }
5533
5534 // This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5535 $timestamp = (int) $timestamp;
5536 $nonce = esc_sql( $nonce );
5537
5538 // Raw query so we can avoid races: add_option will also update
5539 $show_errors = $wpdb->show_errors( false );
5540
5541 $old_nonce = $wpdb->get_row(
5542 $wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5543 );
5544
5545 if ( is_null( $old_nonce ) ) {
5546 $return = $wpdb->query(
5547 $wpdb->prepare(
5548 "INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5549 "jetpack_nonce_{$timestamp}_{$nonce}",
5550 time(),
5551 'no'
5552 )
5553 );
5554 } else {
5555 $return = false;
5556 }
5557
5558 $wpdb->show_errors( $show_errors );
5559
5560 $nonces_used_this_request["$timestamp:$nonce"] = $return;
5561
5562 return $return;
5563 }
5564
5565 /**
5566 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5567 * Capture it here so we can verify the signature later.
5568 */
5569 function xmlrpc_methods( $methods ) {
5570 $this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5571 return $methods;
5572 }
5573
5574 function public_xmlrpc_methods( $methods ) {
5575 if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5576 $methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5577 }
5578 return $methods;
5579 }
5580
5581 function jetpack_getOptions( $args ) {
5582 global $wp_xmlrpc_server;
5583
5584 $wp_xmlrpc_server->escape( $args );
5585
5586 $username = $args[1];
5587 $password = $args[2];
5588
5589 if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5590 return $wp_xmlrpc_server->error;
5591 }
5592
5593 $options = array();
5594 $user_data = $this->get_connected_user_data();
5595 if ( is_array( $user_data ) ) {
5596 $options['jetpack_user_id'] = array(
5597 'desc' => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5598 'readonly' => true,
5599 'value' => $user_data['ID'],
5600 );
5601 $options['jetpack_user_login'] = array(
5602 'desc' => __( 'The WP.com username of the connected user', 'jetpack' ),
5603 'readonly' => true,
5604 'value' => $user_data['login'],
5605 );
5606 $options['jetpack_user_email'] = array(
5607 'desc' => __( 'The WP.com user email of the connected user', 'jetpack' ),
5608 'readonly' => true,
5609 'value' => $user_data['email'],
5610 );
5611 $options['jetpack_user_site_count'] = array(
5612 'desc' => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5613 'readonly' => true,
5614 'value' => $user_data['site_count'],
5615 );
5616 }
5617 $wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5618 $args = stripslashes_deep( $args );
5619 return $wp_xmlrpc_server->wp_getOptions( $args );
5620 }
5621
5622 function xmlrpc_options( $options ) {
5623 $jetpack_client_id = false;
5624 if ( self::is_active() ) {
5625 $jetpack_client_id = Jetpack_Options::get_option( 'id' );
5626 }
5627 $options['jetpack_version'] = array(
5628 'desc' => __( 'Jetpack Plugin Version', 'jetpack' ),
5629 'readonly' => true,
5630 'value' => JETPACK__VERSION,
5631 );
5632
5633 $options['jetpack_client_id'] = array(
5634 'desc' => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5635 'readonly' => true,
5636 'value' => $jetpack_client_id,
5637 );
5638 return $options;
5639 }
5640
5641 public static function clean_nonces( $all = false ) {
5642 global $wpdb;
5643
5644 $sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5645 $sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5646
5647 if ( true !== $all ) {
5648 $sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5649 $sql_args[] = time() - 3600;
5650 }
5651
5652 $sql .= ' ORDER BY `option_id` LIMIT 100';
5653
5654 $sql = $wpdb->prepare( $sql, $sql_args );
5655
5656 for ( $i = 0; $i < 1000; $i++ ) {
5657 if ( ! $wpdb->query( $sql ) ) {
5658 break;
5659 }
5660 }
5661 }
5662
5663 /**
5664 * State is passed via cookies from one request to the next, but never to subsequent requests.
5665 * SET: state( $key, $value );
5666 * GET: $value = state( $key );
5667 *
5668 * @param string $key
5669 * @param string $value
5670 * @param bool $restate private
5671 */
5672 public static function state( $key = null, $value = null, $restate = false ) {
5673 static $state = array();
5674 static $path, $domain;
5675 if ( ! isset( $path ) ) {
5676 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5677 $admin_url = Jetpack::admin_url();
5678 $bits = wp_parse_url( $admin_url );
5679
5680 if ( is_array( $bits ) ) {
5681 $path = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5682 $domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5683 } else {
5684 $path = $domain = null;
5685 }
5686 }
5687
5688 // Extract state from cookies and delete cookies
5689 if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5690 $yum = $_COOKIE[ 'jetpackState' ];
5691 unset( $_COOKIE[ 'jetpackState' ] );
5692 foreach ( $yum as $k => $v ) {
5693 if ( strlen( $v ) )
5694 $state[ $k ] = $v;
5695 setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5696 }
5697 }
5698
5699 if ( $restate ) {
5700 foreach ( $state as $k => $v ) {
5701 setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5702 }
5703 return;
5704 }
5705
5706 // Get a state variable
5707 if ( isset( $key ) && ! isset( $value ) ) {
5708 if ( array_key_exists( $key, $state ) )
5709 return $state[ $key ];
5710 return null;
5711 }
5712
5713 // Set a state variable
5714 if ( isset ( $key ) && isset( $value ) ) {
5715 if( is_array( $value ) && isset( $value[0] ) ) {
5716 $value = $value[0];
5717 }
5718 $state[ $key ] = $value;
5719 setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5720 }
5721 }
5722
5723 public static function restate() {
5724 Jetpack::state( null, null, true );
5725 }
5726
5727 public static function check_privacy( $file ) {
5728 static $is_site_publicly_accessible = null;
5729
5730 if ( is_null( $is_site_publicly_accessible ) ) {
5731 $is_site_publicly_accessible = false;
5732
5733 Jetpack::load_xml_rpc_client();
5734 $rpc = new Jetpack_IXR_Client();
5735
5736 $success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5737 if ( $success ) {
5738 $response = $rpc->getResponse();
5739 if ( $response ) {
5740 $is_site_publicly_accessible = true;
5741 }
5742 }
5743
5744 Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5745 }
5746
5747 if ( $is_site_publicly_accessible ) {
5748 return;
5749 }
5750
5751 $module_slug = self::get_module_slug( $file );
5752
5753 $privacy_checks = Jetpack::state( 'privacy_checks' );
5754 if ( ! $privacy_checks ) {
5755 $privacy_checks = $module_slug;
5756 } else {
5757 $privacy_checks .= ",$module_slug";
5758 }
5759
5760 Jetpack::state( 'privacy_checks', $privacy_checks );
5761 }
5762
5763 /**
5764 * Helper method for multicall XMLRPC.
5765 */
5766 public static function xmlrpc_async_call() {
5767 global $blog_id;
5768 static $clients = array();
5769
5770 $client_blog_id = is_multisite() ? $blog_id : 0;
5771
5772 if ( ! isset( $clients[$client_blog_id] ) ) {
5773 Jetpack::load_xml_rpc_client();
5774 $clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5775 if ( function_exists( 'ignore_user_abort' ) ) {
5776 ignore_user_abort( true );
5777 }
5778 add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5779 }
5780
5781 $args = func_get_args();
5782
5783 if ( ! empty( $args[0] ) ) {
5784 call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5785 } elseif ( is_multisite() ) {
5786 foreach ( $clients as $client_blog_id => $client ) {
5787 if ( ! $client_blog_id || empty( $client->calls ) ) {
5788 continue;
5789 }
5790
5791 $switch_success = switch_to_blog( $client_blog_id, true );
5792 if ( ! $switch_success ) {
5793 continue;
5794 }
5795
5796 flush();
5797 $client->query();
5798
5799 restore_current_blog();
5800 }
5801 } else {
5802 if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5803 flush();
5804 $clients[0]->query();
5805 }
5806 }
5807 }
5808
5809 public static function staticize_subdomain( $url ) {
5810
5811 // Extract hostname from URL
5812 $host = parse_url( $url, PHP_URL_HOST );
5813
5814 // Explode hostname on '.'
5815 $exploded_host = explode( '.', $host );
5816
5817 // Retrieve the name and TLD
5818 if ( count( $exploded_host ) > 1 ) {
5819 $name = $exploded_host[ count( $exploded_host ) - 2 ];
5820 $tld = $exploded_host[ count( $exploded_host ) - 1 ];
5821 // Rebuild domain excluding subdomains
5822 $domain = $name . '.' . $tld;
5823 } else {
5824 $domain = $host;
5825 }
5826 // Array of Automattic domains
5827 $domain_whitelist = array( 'wordpress.com', 'wp.com' );
5828
5829 // Return $url if not an Automattic domain
5830 if ( ! in_array( $domain, $domain_whitelist ) ) {
5831 return $url;
5832 }
5833
5834 if ( is_ssl() ) {
5835 return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5836 }
5837
5838 srand( crc32( basename( $url ) ) );
5839 $static_counter = rand( 0, 2 );
5840 srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5841
5842 return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5843 }
5844
5845 /* JSON API Authorization */
5846
5847 /**
5848 * Handles the login action for Authorizing the JSON API
5849 */
5850 function login_form_json_api_authorization() {
5851 $this->verify_json_api_authorization_request();
5852
5853 add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5854
5855 add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5856 add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5857 add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5858 }
5859
5860 // Make sure the login form is POSTed to the signed URL so we can reverify the request
5861 function post_login_form_to_signed_url( $url, $path, $scheme ) {
5862 if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5863 return $url;
5864 }
5865
5866 $parsed_url = parse_url( $url );
5867 $url = strtok( $url, '?' );
5868 $url = "$url?{$_SERVER['QUERY_STRING']}";
5869 if ( ! empty( $parsed_url['query'] ) )
5870 $url .= "&{$parsed_url['query']}";
5871
5872 return $url;
5873 }
5874
5875 // Make sure the POSTed request is handled by the same action
5876 function preserve_action_in_login_form_for_json_api_authorization() {
5877 echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5878 echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5879 }
5880
5881 // If someone logs in to approve API access, store the Access Code in usermeta
5882 function store_json_api_authorization_token( $user_login, $user ) {
5883 add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5884 add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5885 $token = wp_generate_password( 32, false );
5886 update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5887 }
5888
5889 // Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5890 function allow_wpcom_public_api_domain( $domains ) {
5891 $domains[] = 'public-api.wordpress.com';
5892 return $domains;
5893 }
5894
5895 static function is_redirect_encoded( $redirect_url ) {
5896 return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5897 }
5898
5899 // Add all wordpress.com environments to the safe redirect whitelist
5900 function allow_wpcom_environments( $domains ) {
5901 $domains[] = 'wordpress.com';
5902 $domains[] = 'wpcalypso.wordpress.com';
5903 $domains[] = 'horizon.wordpress.com';
5904 $domains[] = 'calypso.localhost';
5905 return $domains;
5906 }
5907
5908 // Add the Access Code details to the public-api.wordpress.com redirect
5909 function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5910 return add_query_arg(
5911 urlencode_deep(
5912 array(
5913 'jetpack-code' => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5914 'jetpack-user-id' => (int) $user->ID,
5915 'jetpack-state' => $this->json_api_authorization_request['state'],
5916 )
5917 ),
5918 $redirect_to
5919 );
5920 }
5921
5922
5923 /**
5924 * Verifies the request by checking the signature
5925 *
5926 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5927 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5928 *
5929 * @param null|array $environment
5930 */
5931 function verify_json_api_authorization_request( $environment = null ) {
5932 $environment = is_null( $environment )
5933 ? $_REQUEST
5934 : $environment;
5935
5936 list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5937 $token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5938 if ( ! $token || empty( $token->secret ) ) {
5939 wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5940 }
5941
5942 $die_error = __( 'Someone may be trying to trick you into giving them access to your site. Or it could be you just encountered a bug :). Either way, please close this window.', 'jetpack' );
5943
5944 // Host has encoded the request URL, probably as a result of a bad http => https redirect
5945 if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5946 /**
5947 * Jetpack authorisation request Error.
5948 *
5949 * @since 7.5.0
5950 *
5951 */
5952 do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5953 $die_error = sprintf(
5954 /* translators: %s is a URL */
5955 __( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
5956 'https://jetpack.com/support/double-encoding/'
5957 );
5958 }
5959
5960 $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5961
5962 if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5963 $signature = $jetpack_signature->sign_request(
5964 $environment['token'],
5965 $environment['timestamp'],
5966 $environment['nonce'],
5967 '',
5968 'GET',
5969 $environment['jetpack_json_api_original_query'],
5970 null,
5971 true
5972 );
5973 } else {
5974 $signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5975 }
5976
5977 if ( ! $signature ) {
5978 wp_die( $die_error );
5979 } else if ( is_wp_error( $signature ) ) {
5980 wp_die( $die_error );
5981 } else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5982 if ( is_ssl() ) {
5983 // If we signed an HTTP request on the Jetpack Servers, but got redirected to HTTPS by the local blog, check the HTTP signature as well
5984 $signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5985 if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5986 wp_die( $die_error );
5987 }
5988 } else {
5989 wp_die( $die_error );
5990 }
5991 }
5992
5993 $timestamp = (int) $environment['timestamp'];
5994 $nonce = stripslashes( (string) $environment['nonce'] );
5995
5996 if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5997 // De-nonce the nonce, at least for 5 minutes.
5998 // We have to reuse this nonce at least once (used the first time when the initial request is made, used a second time when the login form is POSTed)
5999 $old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6000 if ( $old_nonce_time < time() - 300 ) {
6001 wp_die( __( 'The authorization process expired. Please go back and try again.' , 'jetpack' ) );
6002 }
6003 }
6004
6005 $data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6006 $data_filters = array(
6007 'state' => 'opaque',
6008 'client_id' => 'int',
6009 'client_title' => 'string',
6010 'client_image' => 'url',
6011 );
6012
6013 foreach ( $data_filters as $key => $sanitation ) {
6014 if ( ! isset( $data->$key ) ) {
6015 wp_die( $die_error );
6016 }
6017
6018 switch ( $sanitation ) {
6019 case 'int' :
6020 $this->json_api_authorization_request[$key] = (int) $data->$key;
6021 break;
6022 case 'opaque' :
6023 $this->json_api_authorization_request[$key] = (string) $data->$key;
6024 break;
6025 case 'string' :
6026 $this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
6027 break;
6028 case 'url' :
6029 $this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
6030 break;
6031 }
6032 }
6033
6034 if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6035 wp_die( $die_error );
6036 }
6037 }
6038
6039 function login_message_json_api_authorization( $message ) {
6040 return '<p class="message">' . sprintf(
6041 esc_html__( '%s wants to access your site&#8217;s data. Log in to authorize that access.' , 'jetpack' ),
6042 '<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6043 ) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6044 }
6045
6046 /**
6047 * Get $content_width, but with a <s>twist</s> filter.
6048 */
6049 public static function get_content_width() {
6050 $content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6051 ? $GLOBALS['content_width']
6052 : false;
6053 /**
6054 * Filter the Content Width value.
6055 *
6056 * @since 2.2.3
6057 *
6058 * @param string $content_width Content Width value.
6059 */
6060 return apply_filters( 'jetpack_content_width', $content_width );
6061 }
6062
6063 /**
6064 * Pings the WordPress.com Mirror Site for the specified options.
6065 *
6066 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6067 *
6068 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6069 */
6070 public function get_cloud_site_options( $option_names ) {
6071 $option_names = array_filter( (array) $option_names, 'is_string' );
6072
6073 Jetpack::load_xml_rpc_client();
6074 $xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6075 $xml->query( 'jetpack.fetchSiteOptions', $option_names );
6076 if ( $xml->isError() ) {
6077 return array(
6078 'error_code' => $xml->getErrorCode(),
6079 'error_msg' => $xml->getErrorMessage(),
6080 );
6081 }
6082 $cloud_site_options = $xml->getResponse();
6083
6084 return $cloud_site_options;
6085 }
6086
6087 /**
6088 * Checks if the site is currently in an identity crisis.
6089 *
6090 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6091 */
6092 public static function check_identity_crisis() {
6093 if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6094 return false;
6095 }
6096
6097 return Jetpack_Options::get_option( 'sync_error_idc' );
6098 }
6099
6100 /**
6101 * Checks whether the home and siteurl specifically are whitelisted
6102 * Written so that we don't have re-check $key and $value params every time
6103 * we want to check if this site is whitelisted, for example in footer.php
6104 *
6105 * @since 3.8.0
6106 * @return bool True = already whitelisted False = not whitelisted
6107 */
6108 public static function is_staging_site() {
6109 $is_staging = false;
6110
6111 $known_staging = array(
6112 'urls' => array(
6113 '#\.staging\.wpengine\.com$#i', // WP Engine
6114 '#\.staging\.kinsta\.com$#i', // Kinsta.com
6115 '#\.stage\.site$#i' // DreamPress
6116 ),
6117 'constants' => array(
6118 'IS_WPE_SNAPSHOT', // WP Engine
6119 'KINSTA_DEV_ENV', // Kinsta.com
6120 'WPSTAGECOACH_STAGING', // WP Stagecoach
6121 'JETPACK_STAGING_MODE', // Generic
6122 )
6123 );
6124 /**
6125 * Filters the flags of known staging sites.
6126 *
6127 * @since 3.9.0
6128 *
6129 * @param array $known_staging {
6130 * An array of arrays that each are used to check if the current site is staging.
6131 * @type array $urls URLs of staging sites in regex to check against site_url.
6132 * @type array $constants PHP constants of known staging/developement environments.
6133 * }
6134 */
6135 $known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6136
6137 if ( isset( $known_staging['urls'] ) ) {
6138 foreach ( $known_staging['urls'] as $url ){
6139 if ( preg_match( $url, site_url() ) ) {
6140 $is_staging = true;
6141 break;
6142 }
6143 }
6144 }
6145
6146 if ( isset( $known_staging['constants'] ) ) {
6147 foreach ( $known_staging['constants'] as $constant ) {
6148 if ( defined( $constant ) && constant( $constant ) ) {
6149 $is_staging = true;
6150 }
6151 }
6152 }
6153
6154 // Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6155 if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6156 $is_staging = true;
6157 }
6158
6159 /**
6160 * Filters is_staging_site check.
6161 *
6162 * @since 3.9.0
6163 *
6164 * @param bool $is_staging If the current site is a staging site.
6165 */
6166 return apply_filters( 'jetpack_is_staging_site', $is_staging );
6167 }
6168
6169 /**
6170 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6171 *
6172 * @since 4.4.0
6173 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6174 *
6175 * @return bool
6176 */
6177 public static function validate_sync_error_idc_option() {
6178 $is_valid = false;
6179
6180 $idc_allowed = get_transient( 'jetpack_idc_allowed' );
6181 if ( false === $idc_allowed ) {
6182 $response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6183 if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6184 $json = json_decode( wp_remote_retrieve_body( $response ) );
6185 $idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6186 $transient_duration = HOUR_IN_SECONDS;
6187 } else {
6188 // If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6189 $idc_allowed = '1';
6190 $transient_duration = 5 * MINUTE_IN_SECONDS;
6191 }
6192
6193 set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6194 }
6195
6196 // Is the site opted in and does the stored sync_error_idc option match what we now generate?
6197 $sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6198 if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6199 $local_options = self::get_sync_error_idc_option();
6200 if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6201 $is_valid = true;
6202 }
6203 }
6204
6205 /**
6206 * Filters whether the sync_error_idc option is valid.
6207 *
6208 * @since 4.4.0
6209 *
6210 * @param bool $is_valid If the sync_error_idc is valid or not.
6211 */
6212 $is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6213
6214 if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6215 // Since the option exists, and did not validate, delete it
6216 Jetpack_Options::delete_option( 'sync_error_idc' );
6217 }
6218
6219 return $is_valid;
6220 }
6221
6222 /**
6223 * Normalizes a url by doing three things:
6224 * - Strips protocol
6225 * - Strips www
6226 * - Adds a trailing slash
6227 *
6228 * @since 4.4.0
6229 * @param string $url
6230 * @return WP_Error|string
6231 */
6232 public static function normalize_url_protocol_agnostic( $url ) {
6233 $parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6234 if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6235 return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6236 }
6237
6238 // Strip www and protocols
6239 $url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6240 return $url;
6241 }
6242
6243 /**
6244 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6245 *
6246 * @since 4.4.0
6247 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6248 *
6249 * @param array $response
6250 * @return array Array of the local urls, wpcom urls, and error code
6251 */
6252 public static function get_sync_error_idc_option( $response = array() ) {
6253 // Since the local options will hit the database directly, store the values
6254 // in a transient to allow for autoloading and caching on subsequent views.
6255 $local_options = get_transient( 'jetpack_idc_local' );
6256 if ( false === $local_options ) {
6257 $local_options = array(
6258 'home' => Functions::home_url(),
6259 'siteurl' => Functions::site_url(),
6260 );
6261 set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6262 }
6263
6264 $options = array_merge( $local_options, $response );
6265
6266 $returned_values = array();
6267 foreach( $options as $key => $option ) {
6268 if ( 'error_code' === $key ) {
6269 $returned_values[ $key ] = $option;
6270 continue;
6271 }
6272
6273 if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6274 continue;
6275 }
6276
6277 $returned_values[ $key ] = $normalized_url;
6278 }
6279
6280 set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6281
6282 return $returned_values;
6283 }
6284
6285 /**
6286 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6287 * If set to true, the site will be put into staging mode.
6288 *
6289 * @since 4.3.2
6290 * @return bool
6291 */
6292 public static function sync_idc_optin() {
6293 if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6294 $default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6295 } else {
6296 $default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6297 }
6298
6299 /**
6300 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6301 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6302 * JETPACK_SYNC_IDC_OPTIN constant if set.
6303 *
6304 * @since 4.3.2
6305 *
6306 * @param bool $default Whether the site is opted in to IDC mitigation.
6307 */
6308 return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6309 }
6310
6311 /**
6312 * Maybe Use a .min.css stylesheet, maybe not.
6313 *
6314 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6315 */
6316 public static function maybe_min_asset( $url, $path, $plugin ) {
6317 // Short out on things trying to find actual paths.
6318 if ( ! $path || empty( $plugin ) ) {
6319 return $url;
6320 }
6321
6322 $path = ltrim( $path, '/' );
6323
6324 // Strip out the abspath.
6325 $base = dirname( plugin_basename( $plugin ) );
6326
6327 // Short out on non-Jetpack assets.
6328 if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6329 return $url;
6330 }
6331
6332 // File name parsing.
6333 $file = "{$base}/{$path}";
6334 $full_path = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6335 $file_name = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6336 $file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6337 $extension = array_shift( $file_name_parts_r );
6338
6339 if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6340 // Already pointing at the minified version.
6341 if ( 'min' === $file_name_parts_r[0] ) {
6342 return $url;
6343 }
6344
6345 $min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6346 if ( file_exists( $min_full_path ) ) {
6347 $url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6348 // If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6349 if ( 'css' === $extension ) {
6350 $key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6351 self::$min_assets[ $key ] = $path;
6352 }
6353 }
6354 }
6355
6356 return $url;
6357 }
6358
6359 /**
6360 * If the asset is minified, let's flag .min as the suffix.
6361 *
6362 * Attached to `style_loader_src` filter.
6363 *
6364 * @param string $tag The tag that would link to the external asset.
6365 * @param string $handle The registered handle of the script in question.
6366 * @param string $href The url of the asset in question.
6367 */
6368 public static function set_suffix_on_min( $src, $handle ) {
6369 if ( false === strpos( $src, '.min.css' ) ) {
6370 return $src;
6371 }
6372
6373 if ( ! empty( self::$min_assets ) ) {
6374 foreach ( self::$min_assets as $file => $path ) {
6375 if ( false !== strpos( $src, $file ) ) {
6376 wp_style_add_data( $handle, 'suffix', '.min' );
6377 return $src;
6378 }
6379 }
6380 }
6381
6382 return $src;
6383 }
6384
6385 /**
6386 * Maybe inlines a stylesheet.
6387 *
6388 * If you'd like to inline a stylesheet instead of printing a link to it,
6389 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6390 *
6391 * Attached to `style_loader_tag` filter.
6392 *
6393 * @param string $tag The tag that would link to the external asset.
6394 * @param string $handle The registered handle of the script in question.
6395 *
6396 * @return string
6397 */
6398 public static function maybe_inline_style( $tag, $handle ) {
6399 global $wp_styles;
6400 $item = $wp_styles->registered[ $handle ];
6401
6402 if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6403 return $tag;
6404 }
6405
6406 if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6407 $href = $matches[1];
6408 // Strip off query string
6409 if ( $pos = strpos( $href, '?' ) ) {
6410 $href = substr( $href, 0, $pos );
6411 }
6412 // Strip off fragment
6413 if ( $pos = strpos( $href, '#' ) ) {
6414 $href = substr( $href, 0, $pos );
6415 }
6416 } else {
6417 return $tag;
6418 }
6419
6420 $plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6421 if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6422 return $tag;
6423 }
6424
6425 // If this stylesheet has a RTL version, and the RTL version replaces normal...
6426 if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6427 // And this isn't the pass that actually deals with the RTL version...
6428 if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6429 // Short out, as the RTL version will deal with it in a moment.
6430 return $tag;
6431 }
6432 }
6433
6434 $file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6435 $css = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6436 if ( $css ) {
6437 $tag = "<!-- Inline {$item->handle} -->\r\n";
6438 if ( empty( $item->extra['after'] ) ) {
6439 wp_add_inline_style( $handle, $css );
6440 } else {
6441 array_unshift( $item->extra['after'], $css );
6442 wp_style_add_data( $handle, 'after', $item->extra['after'] );
6443 }
6444 }
6445
6446 return $tag;
6447 }
6448
6449 /**
6450 * Loads a view file from the views
6451 *
6452 * Data passed in with the $data parameter will be available in the
6453 * template file as $data['value']
6454 *
6455 * @param string $template - Template file to load
6456 * @param array $data - Any data to pass along to the template
6457 * @return boolean - If template file was found
6458 **/
6459 public function load_view( $template, $data = array() ) {
6460 $views_dir = JETPACK__PLUGIN_DIR . 'views/';
6461
6462 if( file_exists( $views_dir . $template ) ) {
6463 require_once( $views_dir . $template );
6464 return true;
6465 }
6466
6467 error_log( "Jetpack: Unable to find view file $views_dir$template" );
6468 return false;
6469 }
6470
6471 /**
6472 * Throws warnings for deprecated hooks to be removed from Jetpack
6473 */
6474 public function deprecated_hooks() {
6475 global $wp_filter;
6476
6477 /*
6478 * Format:
6479 * deprecated_filter_name => replacement_name
6480 *
6481 * If there is no replacement, use null for replacement_name
6482 */
6483 $deprecated_list = array(
6484 'jetpack_bail_on_shortcode' => 'jetpack_shortcodes_to_include',
6485 'wpl_sharing_2014_1' => null,
6486 'jetpack-tools-to-include' => 'jetpack_tools_to_include',
6487 'jetpack_identity_crisis_options_to_check' => null,
6488 'update_option_jetpack_single_user_site' => null,
6489 'audio_player_default_colors' => null,
6490 'add_option_jetpack_featured_images_enabled' => null,
6491 'add_option_jetpack_update_details' => null,
6492 'add_option_jetpack_updates' => null,
6493 'add_option_jetpack_network_name' => null,
6494 'add_option_jetpack_network_allow_new_registrations' => null,
6495 'add_option_jetpack_network_add_new_users' => null,
6496 'add_option_jetpack_network_site_upload_space' => null,
6497 'add_option_jetpack_network_upload_file_types' => null,
6498 'add_option_jetpack_network_enable_administration_menus' => null,
6499 'add_option_jetpack_is_multi_site' => null,
6500 'add_option_jetpack_is_main_network' => null,
6501 'add_option_jetpack_main_network_site' => null,
6502 'jetpack_sync_all_registered_options' => null,
6503 'jetpack_has_identity_crisis' => 'jetpack_sync_error_idc_validation',
6504 'jetpack_is_post_mailable' => null,
6505 'jetpack_seo_site_host' => null,
6506 'jetpack_installed_plugin' => 'jetpack_plugin_installed',
6507 'jetpack_holiday_snow_option_name' => null,
6508 'jetpack_holiday_chance_of_snow' => null,
6509 'jetpack_holiday_snow_js_url' => null,
6510 'jetpack_is_holiday_snow_season' => null,
6511 'jetpack_holiday_snow_option_updated' => null,
6512 'jetpack_holiday_snowing' => null,
6513 'jetpack_sso_auth_cookie_expirtation' => 'jetpack_sso_auth_cookie_expiration',
6514 'jetpack_cache_plans' => null,
6515 'jetpack_updated_theme' => 'jetpack_updated_themes',
6516 'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6517 'jetpack_enable_site_verification' => null,
6518 'can_display_jetpack_manage_notice' => null,
6519 // Removed in Jetpack 7.3.0
6520 'atd_load_scripts' => null,
6521 'atd_http_post_timeout' => null,
6522 'atd_http_post_error' => null,
6523 'atd_service_domain' => null,
6524 );
6525
6526 // This is a silly loop depth. Better way?
6527 foreach( $deprecated_list AS $hook => $hook_alt ) {
6528 if ( has_action( $hook ) ) {
6529 foreach( $wp_filter[ $hook ] AS $func => $values ) {
6530 foreach( $values AS $hooked ) {
6531 if ( is_callable( $hooked['function'] ) ) {
6532 $function_name = 'an anonymous function';
6533 } else {
6534 $function_name = $hooked['function'];
6535 }
6536 _deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6537 }
6538 }
6539 }
6540 }
6541 }
6542
6543 /**
6544 * Converts any url in a stylesheet, to the correct absolute url.
6545 *
6546 * Considerations:
6547 * - Normal, relative URLs `feh.png`
6548 * - Data URLs `data:image/gif;base64,eh129ehiuehjdhsa==`
6549 * - Schema-agnostic URLs `//domain.com/feh.png`
6550 * - Absolute URLs `http://domain.com/feh.png`
6551 * - Domain root relative URLs `/feh.png`
6552 *
6553 * @param $css string: The raw CSS -- should be read in directly from the file.
6554 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6555 *
6556 * @return mixed|string
6557 */
6558 public static function absolutize_css_urls( $css, $css_file_url ) {
6559 $pattern = '#url\((?P<path>[^)]*)\)#i';
6560 $css_dir = dirname( $css_file_url );
6561 $p = parse_url( $css_dir );
6562 $domain = sprintf(
6563 '%1$s//%2$s%3$s%4$s',
6564 isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6565 isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6566 $p['host'],
6567 isset( $p['port'] ) ? ":{$p['port']}" : ''
6568 );
6569
6570 if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6571 $find = $replace = array();
6572 foreach ( $matches as $match ) {
6573 $url = trim( $match['path'], "'\" \t" );
6574
6575 // If this is a data url, we don't want to mess with it.
6576 if ( 'data:' === substr( $url, 0, 5 ) ) {
6577 continue;
6578 }
6579
6580 // If this is an absolute or protocol-agnostic url,
6581 // we don't want to mess with it.
6582 if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6583 continue;
6584 }
6585
6586 switch ( substr( $url, 0, 1 ) ) {
6587 case '/':
6588 $absolute = $domain . $url;
6589 break;
6590 default:
6591 $absolute = $css_dir . '/' . $url;
6592 }
6593
6594 $find[] = $match[0];
6595 $replace[] = sprintf( 'url("%s")', $absolute );
6596 }
6597 $css = str_replace( $find, $replace, $css );
6598 }
6599
6600 return $css;
6601 }
6602
6603 /**
6604 * This methods removes all of the registered css files on the front end
6605 * from Jetpack in favor of using a single file. In effect "imploding"
6606 * all the files into one file.
6607 *
6608 * Pros:
6609 * - Uses only ONE css asset connection instead of 15
6610 * - Saves a minimum of 56k
6611 * - Reduces server load
6612 * - Reduces time to first painted byte
6613 *
6614 * Cons:
6615 * - Loads css for ALL modules. However all selectors are prefixed so it
6616 * should not cause any issues with themes.
6617 * - Plugins/themes dequeuing styles no longer do anything. See
6618 * jetpack_implode_frontend_css filter for a workaround
6619 *
6620 * For some situations developers may wish to disable css imploding and
6621 * instead operate in legacy mode where each file loads seperately and
6622 * can be edited individually or dequeued. This can be accomplished with
6623 * the following line:
6624 *
6625 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6626 *
6627 * @since 3.2
6628 **/
6629 public function implode_frontend_css( $travis_test = false ) {
6630 $do_implode = true;
6631 if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6632 $do_implode = false;
6633 }
6634
6635 // Do not implode CSS when the page loads via the AMP plugin.
6636 if ( Jetpack_AMP_Support::is_amp_request() ) {
6637 $do_implode = false;
6638 }
6639
6640 /**
6641 * Allow CSS to be concatenated into a single jetpack.css file.
6642 *
6643 * @since 3.2.0
6644 *
6645 * @param bool $do_implode Should CSS be concatenated? Default to true.
6646 */
6647 $do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6648
6649 // Do not use the imploded file when default behavior was altered through the filter
6650 if ( ! $do_implode ) {
6651 return;
6652 }
6653
6654 // We do not want to use the imploded file in dev mode, or if not connected
6655 if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6656 if ( ! $travis_test ) {
6657 return;
6658 }
6659 }
6660
6661 // Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6662 if ( get_option( 'sharedaddy_disable_resources' ) ) {
6663 return;
6664 }
6665
6666 /*
6667 * Now we assume Jetpack is connected and able to serve the single
6668 * file.
6669 *
6670 * In the future there will be a check here to serve the file locally
6671 * or potentially from the Jetpack CDN
6672 *
6673 * For now:
6674 * - Enqueue a single imploded css file
6675 * - Zero out the style_loader_tag for the bundled ones
6676 * - Be happy, drink scotch
6677 */
6678
6679 add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6680
6681 $version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6682
6683 wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6684 wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6685 }
6686
6687 function concat_remove_style_loader_tag( $tag, $handle ) {
6688 if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6689 $tag = '';
6690 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6691 $tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6692 }
6693 }
6694
6695 return $tag;
6696 }
6697
6698 /*
6699 * Check the heartbeat data
6700 *
6701 * Organizes the heartbeat data by severity. For example, if the site
6702 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6703 *
6704 * Data will be added to "caution" array, if it either:
6705 * - Out of date Jetpack version
6706 * - Out of date WP version
6707 * - Out of date PHP version
6708 *
6709 * $return array $filtered_data
6710 */
6711 public static function jetpack_check_heartbeat_data() {
6712 $raw_data = Jetpack_Heartbeat::generate_stats_array();
6713
6714 $good = array();
6715 $caution = array();
6716 $bad = array();
6717
6718 foreach ( $raw_data as $stat => $value ) {
6719
6720 // Check jetpack version
6721 if ( 'version' == $stat ) {
6722 if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6723 $caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6724 continue;
6725 }
6726 }
6727
6728 // Check WP version
6729 if ( 'wp-version' == $stat ) {
6730 if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6731 $caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6732 continue;
6733 }
6734 }
6735
6736 // Check PHP version
6737 if ( 'php-version' == $stat ) {
6738 if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6739 $caution[ $stat ] = $value . " - min supported is 5.2.4";
6740 continue;
6741 }
6742 }
6743
6744 // Check ID crisis
6745 if ( 'identitycrisis' == $stat ) {
6746 if ( 'yes' == $value ) {
6747 $bad[ $stat ] = $value;
6748 continue;
6749 }
6750 }
6751
6752 // The rest are good :)
6753 $good[ $stat ] = $value;
6754 }
6755
6756 $filtered_data = array(
6757 'good' => $good,
6758 'caution' => $caution,
6759 'bad' => $bad
6760 );
6761
6762 return $filtered_data;
6763 }
6764
6765
6766 /*
6767 * This method is used to organize all options that can be reset
6768 * without disconnecting Jetpack.
6769 *
6770 * It is used in class.jetpack-cli.php to reset options
6771 *
6772 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6773 *
6774 * @return array of options to delete.
6775 */
6776 public static function get_jetpack_options_for_reset() {
6777 return Jetpack_Options::get_options_for_reset();
6778 }
6779
6780 /*
6781 * Strip http:// or https:// from a url, replaces forward slash with ::,
6782 * so we can bring them directly to their site in calypso.
6783 *
6784 * @param string | url
6785 * @return string | url without the guff
6786 */
6787 public static function build_raw_urls( $url ) {
6788 $strip_http = '/.*?:\/\//i';
6789 $url = preg_replace( $strip_http, '', $url );
6790 $url = str_replace( '/', '::', $url );
6791 return $url;
6792 }
6793
6794 /**
6795 * Stores and prints out domains to prefetch for page speed optimization.
6796 *
6797 * @param mixed $new_urls
6798 */
6799 public static function dns_prefetch( $new_urls = null ) {
6800 static $prefetch_urls = array();
6801 if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6802 echo "\r\n";
6803 foreach ( $prefetch_urls as $this_prefetch_url ) {
6804 printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6805 }
6806 } elseif ( ! empty( $new_urls ) ) {
6807 if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6808 add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6809 }
6810 foreach ( (array) $new_urls as $this_new_url ) {
6811 $prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6812 }
6813 $prefetch_urls = array_unique( $prefetch_urls );
6814 }
6815 }
6816
6817 public function wp_dashboard_setup() {
6818 if ( self::is_active() ) {
6819 add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6820 }
6821
6822 if ( has_action( 'jetpack_dashboard_widget' ) ) {
6823 $jetpack_logo = new Jetpack_Logo();
6824 $widget_title = sprintf(
6825 wp_kses(
6826 /* translators: Placeholder is a Jetpack logo. */
6827 __( 'Stats <span>by %s</span>', 'jetpack' ),
6828 array( 'span' => array() )
6829 ),
6830 $jetpack_logo->get_jp_emblem( true )
6831 );
6832
6833 wp_add_dashboard_widget(
6834 'jetpack_summary_widget',
6835 $widget_title,
6836 array( __CLASS__, 'dashboard_widget' )
6837 );
6838 wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6839
6840 // If we're inactive and not in development mode, sort our box to the top.
6841 if ( ! self::is_active() && ! self::is_development_mode() ) {
6842 global $wp_meta_boxes;
6843
6844 $dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6845 $ours = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6846
6847 $wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6848 }
6849 }
6850 }
6851
6852 /**
6853 * @param mixed $result Value for the user's option
6854 * @return mixed
6855 */
6856 function get_user_option_meta_box_order_dashboard( $sorted ) {
6857 if ( ! is_array( $sorted ) ) {
6858 return $sorted;
6859 }
6860
6861 foreach ( $sorted as $box_context => $ids ) {
6862 if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6863 // If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6864 continue;
6865 }
6866
6867 $ids_array = explode( ',', $ids );
6868 $key = array_search( 'dashboard_stats', $ids_array );
6869
6870 if ( false !== $key ) {
6871 // If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6872 $ids_array[ $key ] = 'jetpack_summary_widget';
6873 $sorted[ $box_context ] = implode( ',', $ids_array );
6874 // We've found it, stop searching, and just return.
6875 break;
6876 }
6877 }
6878
6879 return $sorted;
6880 }
6881
6882 public static function dashboard_widget() {
6883 /**
6884 * Fires when the dashboard is loaded.
6885 *
6886 * @since 3.4.0
6887 */
6888 do_action( 'jetpack_dashboard_widget' );
6889 }
6890
6891 public static function dashboard_widget_footer() {
6892 ?>
6893 <footer>
6894
6895 <div class="protect">
6896 <?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6897 <h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6898 <p><?php echo esc_html_x( 'Blocked malicious login attempts', '{#} Blocked malicious login attempts -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6899 <?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6900 <a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( array( 'action' => 'activate', 'module' => 'protect' ) ), 'jetpack_activate-protect' ) ); ?>" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6901 <?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6902 </a>
6903 <?php else : ?>
6904 <?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6905 <?php endif; ?>
6906 </div>
6907
6908 <div class="akismet">
6909 <?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6910 <h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6911 <p><?php echo esc_html_x( 'Spam comments blocked by Akismet.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6912 <?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6913 <a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'activate', 'plugin' => 'akismet/akismet.php' ), admin_url( 'plugins.php' ) ), 'activate-plugin_akismet/akismet.php' ) ); ?>" class="button button-jetpack">
6914 <?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6915 </a>
6916 <?php else : ?>
6917 <p><a href="<?php echo esc_url( 'https://akismet.com/?utm_source=jetpack&utm_medium=link&utm_campaign=Jetpack%20Dashboard%20Widget%20Footer%20Link' ); ?>"><?php esc_html_e( 'Akismet can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
6918 <?php endif; ?>
6919 </div>
6920
6921 </footer>
6922 <?php
6923 }
6924
6925 /*
6926 * Adds a "blank" column in the user admin table to display indication of user connection.
6927 */
6928 function jetpack_icon_user_connected( $columns ) {
6929 $columns['user_jetpack'] = '';
6930 return $columns;
6931 }
6932
6933 /*
6934 * Show Jetpack icon if the user is linked.
6935 */
6936 function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6937 if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6938 $jetpack_logo = new Jetpack_Logo();
6939 $emblem_html = sprintf(
6940 '<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6941 esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6942 $jetpack_logo->get_jp_emblem()
6943 );
6944 return $emblem_html;
6945 }
6946
6947 return $val;
6948 }
6949
6950 /*
6951 * Style the Jetpack user column
6952 */
6953 function jetpack_user_col_style() {
6954 global $current_screen;
6955 if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6956 <style>
6957 .fixed .column-user_jetpack {
6958 width: 21px;
6959 }
6960 .jp-emblem-user-admin svg {
6961 width: 20px;
6962 height: 20px;
6963 }
6964 .jp-emblem-user-admin path {
6965 fill: #00BE28;
6966 }
6967 </style>
6968 <?php }
6969 }
6970
6971 /**
6972 * Checks if Akismet is active and working.
6973 *
6974 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6975 * that implied usage of methods present since more recent version.
6976 * See https://github.com/Automattic/jetpack/pull/9585
6977 *
6978 * @since 5.1.0
6979 *
6980 * @return bool True = Akismet available. False = Aksimet not available.
6981 */
6982 public static function is_akismet_active() {
6983 static $status = null;
6984
6985 if ( ! is_null( $status ) ) {
6986 return $status;
6987 }
6988
6989 // Check if a modern version of Akismet is active.
6990 if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6991 $status = false;
6992 return $status;
6993 }
6994
6995 // Make sure there is a key known to Akismet at all before verifying key.
6996 $akismet_key = Akismet::get_api_key();
6997 if ( ! $akismet_key ) {
6998 $status = false;
6999 return $status;
7000 }
7001
7002 // Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7003 $akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7004
7005 // 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.
7006 $recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7007 // We cache the result of the Akismet key verification for ten minutes.
7008 if ( ! $akismet_key_state || $recheck ) {
7009 $akismet_key_state = Akismet::verify_key( $akismet_key );
7010 set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7011 }
7012
7013 $status = 'valid' === $akismet_key_state;
7014
7015 return $status;
7016 }
7017
7018 /**
7019 * @deprecated
7020 *
7021 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7022 */
7023 public static function is_function_in_backtrace() {
7024 _deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7025 }
7026
7027 /**
7028 * Given a minified path, and a non-minified path, will return
7029 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7030 *
7031 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7032 * root Jetpack directory.
7033 *
7034 * @since 5.6.0
7035 *
7036 * @param string $min_path
7037 * @param string $non_min_path
7038 * @return string The URL to the file
7039 */
7040 public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7041 return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7042 }
7043
7044 /**
7045 * Checks for whether Jetpack Backup & Scan is enabled.
7046 * Will return true if the state of Backup & Scan is anything except "unavailable".
7047 * @return bool|int|mixed
7048 */
7049 public static function is_rewind_enabled() {
7050 if ( ! Jetpack::is_active() ) {
7051 return false;
7052 }
7053
7054 $rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7055 if ( false === $rewind_enabled ) {
7056 jetpack_require_lib( 'class.core-rest-api-endpoints' );
7057 $rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7058 $rewind_enabled = ( ! is_wp_error( $rewind_data )
7059 && ! empty( $rewind_data['state'] )
7060 && 'active' === $rewind_data['state'] )
7061 ? 1
7062 : 0;
7063
7064 set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7065 }
7066 return $rewind_enabled;
7067 }
7068
7069 /**
7070 * Return Calypso environment value; used for developing Jetpack and pairing
7071 * it with different Calypso enrionments, such as localhost.
7072 *
7073 * @since 7.4.0
7074 *
7075 * @return string Calypso environment
7076 */
7077 public static function get_calypso_env() {
7078 if ( isset( $_GET['calypso_env'] ) ) {
7079 return sanitize_key( $_GET['calypso_env'] );
7080 }
7081
7082 if ( getenv( 'CALYPSO_ENV' ) ) {
7083 return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7084 }
7085
7086 if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7087 return sanitize_key( CALYPSO_ENV );
7088 }
7089
7090 return '';
7091 }
7092
7093 /**
7094 * Checks whether or not TOS has been agreed upon.
7095 * Will return true if a user has clicked to register, or is already connected.
7096 */
7097 public static function jetpack_tos_agreed() {
7098 return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7099 }
7100
7101 /**
7102 * Handles activating default modules as well general cleanup for the new connection.
7103 *
7104 * @param boolean $activate_sso Whether to activate the SSO module when activating default modules.
7105 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7106 * @param boolean $send_state_messages Whether to send state messages.
7107 * @return void
7108 */
7109 public static function handle_post_authorization_actions(
7110 $activate_sso = false,
7111 $redirect_on_activation_error = false,
7112 $send_state_messages = true
7113 ) {
7114 $other_modules = $activate_sso
7115 ? array( 'sso' )
7116 : array();
7117
7118 if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7119 Jetpack::delete_active_modules();
7120
7121 Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7122 } else {
7123 Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7124 }
7125
7126 // Since this is a fresh connection, be sure to clear out IDC options
7127 Jetpack_IDC::clear_all_idc_options();
7128 Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7129
7130 // Start nonce cleaner
7131 wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7132 wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7133
7134 if ( $send_state_messages ) {
7135 Jetpack::state( 'message', 'authorized' );
7136 }
7137 }
7138
7139 /**
7140 * Returns a boolean for whether backups UI should be displayed or not.
7141 *
7142 * @return bool Should backups UI be displayed?
7143 */
7144 public static function show_backups_ui() {
7145 /**
7146 * Whether UI for backups should be displayed.
7147 *
7148 * @since 6.5.0
7149 *
7150 * @param bool $show_backups Should UI for backups be displayed? True by default.
7151 */
7152 return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7153 }
7154
7155 /*
7156 * Deprecated manage functions
7157 */
7158 function prepare_manage_jetpack_notice() {
7159 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7160 }
7161 function manage_activate_screen() {
7162 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7163 }
7164 function admin_jetpack_manage_notice() {
7165 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7166 }
7167 function opt_out_jetpack_manage_url() {
7168 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7169 }
7170 function opt_in_jetpack_manage_url() {
7171 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7172 }
7173 function opt_in_jetpack_manage_notice() {
7174 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7175 }
7176 function can_display_jetpack_manage_notice() {
7177 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7178 }
7179
7180 /**
7181 * Clean leftoveruser meta.
7182 *
7183 * Delete Jetpack-related user meta when it is no longer needed.
7184 *
7185 * @since 7.3.0
7186 *
7187 * @param int $user_id User ID being updated.
7188 */
7189 public static function user_meta_cleanup( $user_id ) {
7190 $meta_keys = array(
7191 // AtD removed from Jetpack 7.3
7192 'AtD_options',
7193 'AtD_check_when',
7194 'AtD_guess_lang',
7195 'AtD_ignored_phrases',
7196 );
7197
7198 foreach ( $meta_keys as $meta_key ) {
7199 if ( get_user_meta( $user_id, $meta_key ) ) {
7200 delete_user_meta( $user_id, $meta_key );
7201 }
7202 }
7203 }
7204
7205 function is_active_and_not_development_mode( $maybe ) {
7206 if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7207 return false;
7208 }
7209 return true;
7210 }
7211
7212 }
7213