PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 3.6.4
Jetpack – WP Security, Backup, Speed, & Growth v3.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
6,136 lines 209.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /*
4 Options:
5 jetpack_options (array)
6 An array of options.
7 @see Jetpack_Options::get_option_names()
8
9 jetpack_register (string)
10 Temporary verification secrets.
11
12 jetpack_activated (int)
13 1: the plugin was activated normally
14 2: the plugin was activated on this site because of a network-wide activation
15 3: the plugin was auto-installed
16 4: the plugin was manually disconnected (but is still installed)
17
18 jetpack_active_modules (array)
19 Array of active module slugs.
20
21 jetpack_do_activate (bool)
22 Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23 */
24
25 class Jetpack {
26 var $xmlrpc_server = null;
27
28 private $xmlrpc_verification = null;
29
30 var $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32 /**
33 * @var array The handles of styles that are concatenated into jetpack.css
34 */
35 var $concatenated_style_handles = array(
36 'jetpack-carousel',
37 'grunion.css',
38 'the-neverending-homepage',
39 'jetpack_likes',
40 'jetpack_related-posts',
41 'sharedaddy',
42 'jetpack-slideshow',
43 'presentations',
44 'jetpack-subscriptions',
45 'tiled-gallery',
46 'widget-conditions',
47 'jetpack_display_posts_widget',
48 'gravatar-profile-widget',
49 'widget-grid-and-list',
50 'jetpack-widgets',
51 'goodreads-widget',
52 );
53
54 var $plugins_to_deactivate = array(
55 'stats' => array( 'stats/stats.php', 'WordPress.com Stats' ),
56 'shortlinks' => array( 'stats/stats.php', 'WordPress.com Stats' ),
57 'sharedaddy' => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
58 'twitter-widget' => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
59 'after-the-deadline' => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
60 'contact-form' => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
61 'contact-form' => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
62 'custom-css' => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
63 'random-redirect' => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
64 'videopress' => array( 'video/video.php', 'VideoPress' ),
65 'widget-visibility' => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
66 'widget-visibility' => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
67 'sharedaddy' => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
68 'omnisearch' => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
69 'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
70 'latex' => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
71 );
72
73 var $capability_translations = array(
74 'administrator' => 'manage_options',
75 'editor' => 'edit_others_posts',
76 'author' => 'publish_posts',
77 'contributor' => 'edit_posts',
78 'subscriber' => 'read',
79 );
80
81 /**
82 * Map of modules that have conflicts with plugins and should not be auto-activated
83 * if the plugins are active. Used by filter_default_modules
84 *
85 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
86 * change `module-slug` and add this to your plugin:
87 *
88 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
89 * function my_jetpack_get_default_modules( $modules ) {
90 * return array_diff( $modules, array( 'module-slug' ) );
91 * }
92 *
93 * @var array
94 */
95 private $conflicting_plugins = array(
96 'comments' => array(
97 'Intense Debate' => 'intensedebate/intensedebate.php',
98 'Disqus' => 'disqus-comment-system/disqus.php',
99 'Livefyre' => 'livefyre-comments/livefyre.php',
100 'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
101 'Google+ Comments' => 'google-plus-comments/google-plus-comments.php',
102 'WP-SpamShield Anti-Spam' => 'wp-spamshield/wp-spamshield.php',
103 ),
104 'contact-form' => array(
105 'Contact Form 7' => 'contact-form-7/wp-contact-form-7.php',
106 'Gravity Forms' => 'gravityforms/gravityforms.php',
107 'Contact Form Plugin' => 'contact-form-plugin/contact_form.php',
108 'Easy Contact Forms' => 'easy-contact-forms/easy-contact-forms.php',
109 'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
110 ),
111 'minileven' => array(
112 'WPtouch' => 'wptouch/wptouch.php',
113 ),
114 'latex' => array(
115 'LaTeX for WordPress' => 'latex/latex.php',
116 'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
117 'Easy WP LaTeX' => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
118 'MathJax-LaTeX' => 'mathjax-latex/mathjax-latex.php',
119 'Enable Latex' => 'enable-latex/enable-latex.php',
120 'WP QuickLaTeX' => 'wp-quicklatex/wp-quicklatex.php',
121 ),
122 'protect' => array(
123 'Limit Login Attempts' => 'limit-login-attempts/limit-login-attempts.php',
124 'Captcha' => 'captcha/captcha.php',
125 'Brute Force Login Protection' => 'brute-force-login-protection/brute-force-login-protection.php',
126 'Login Security Solution' => 'login-security-solution/login-security-solution.php',
127 'WPSecureOps Brute Force Protect' => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
128 'BulletProof Security' => 'bulletproof-security/bulletproof-security.php',
129 'SiteGuard WP Plugin' => 'siteguard/siteguard.php',
130 'Security-protection' => 'security-protection/security-protection.php',
131 'Login Security' => 'login-security/login-security.php',
132 'Botnet Attack Blocker' => 'botnet-attack-blocker/botnet-attack-blocker.php',
133 'Wordfence Security' => 'wordfence/wordfence.php',
134 'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
135 'iThemes Security' => 'better-wp-security/better-wp-security.php',
136 ),
137 'random-redirect' => array(
138 'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
139 ),
140 'related-posts' => array(
141 'YARPP' => 'yet-another-related-posts-plugin/yarpp.php',
142 'WordPress Related Posts' => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
143 'nrelate Related Content' => 'nrelate-related-content/nrelate-related.php',
144 'Contextual Related Posts' => 'contextual-related-posts/contextual-related-posts.php',
145 'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
146 'outbrain' => 'outbrain/outbrain.php',
147 'Shareaholic' => 'shareaholic/shareaholic.php',
148 'Sexybookmarks' => 'sexybookmarks/shareaholic.php',
149 ),
150 'sharedaddy' => array(
151 'AddThis' => 'addthis/addthis_social_widget.php',
152 'Add To Any' => 'add-to-any/add-to-any.php',
153 'ShareThis' => 'share-this/sharethis.php',
154 'Shareaholic' => 'shareaholic/shareaholic.php',
155 ),
156 'verification-tools' => array(
157 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
158 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
159 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
160 ),
161 'widget-visibility' => array(
162 'Widget Logic' => 'widget-logic/widget_logic.php',
163 'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
164 ),
165 );
166
167 /**
168 * Plugins for which we turn off our Facebook OG Tags implementation.
169 *
170 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
171 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
172 *
173 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
174 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
175 */
176 private $open_graph_conflicting_plugins = array(
177 '2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
178 // 2 Click Social Media Buttons
179 'add-link-to-facebook/add-link-to-facebook.php', // Add Link to Facebook
180 'add-meta-tags/add-meta-tags.php', // Add Meta Tags
181 'easy-facebook-share-thumbnails/esft.php', // Easy Facebook Share Thumbnail
182 'facebook/facebook.php', // Facebook (official plugin)
183 'facebook-awd/AWD_facebook.php', // Facebook AWD All in one
184 'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
185 // Facebook Featured Image & OG Meta Tags
186 'facebook-meta-tags/facebook-metatags.php', // Facebook Meta Tags
187 'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
188 // Facebook Open Graph Meta Tags for WordPress
189 'facebook-revised-open-graph-meta-tag/index.php', // Facebook Revised Open Graph Meta Tag
190 'facebook-thumb-fixer/_facebook-thumb-fixer.php', // Facebook Thumb Fixer
191 'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
192 // Fedmich's Facebook Open Graph Meta
193 'header-footer/plugin.php', // Header and Footer
194 'network-publisher/networkpub.php', // Network Publisher
195 'nextgen-facebook/nextgen-facebook.php', // NextGEN Facebook OG
196 'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
197 // NextScripts SNAP
198 'opengraph/opengraph.php', // Open Graph
199 'open-graph-protocol-framework/open-graph-protocol-framework.php',
200 // Open Graph Protocol Framework
201 'seo-facebook-comments/seofacebook.php', // SEO Facebook Comments
202 'seo-ultimate/seo-ultimate.php', // SEO Ultimate
203 'sexybookmarks/sexy-bookmarks.php', // Shareaholic
204 'shareaholic/sexy-bookmarks.php', // Shareaholic
205 'sharepress/sharepress.php', // SharePress
206 'simple-facebook-connect/sfc.php', // Simple Facebook Connect
207 'social-discussions/social-discussions.php', // Social Discussions
208 'social-sharing-toolkit/social_sharing_toolkit.php', // Social Sharing Toolkit
209 'socialize/socialize.php', // Socialize
210 'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
211 // Tweet, Like, Google +1 and Share
212 'wordbooker/wordbooker.php', // Wordbooker
213 'wpsso/wpsso.php', // WordPress Social Sharing Optimization
214 'wp-caregiver/wp-caregiver.php', // WP Caregiver
215 'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
216 // WP Facebook Like Send & Open Graph Meta
217 'wp-facebook-open-graph-protocol/wp-facebook-ogp.php', // WP Facebook Open Graph protocol
218 'wp-ogp/wp-ogp.php', // WP-OGP
219 'zoltonorg-social-plugin/zosp.php', // Zolton.org Social Plugin
220 );
221
222 /**
223 * Plugins for which we turn off our Twitter Cards Tags implementation.
224 */
225 private $twitter_cards_conflicting_plugins = array(
226 // 'twitter/twitter.php', // The official one handles this on its own.
227 // // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
228 'eewee-twitter-card/index.php', // Eewee Twitter Card
229 'ig-twitter-cards/ig-twitter-cards.php', // IG:Twitter Cards
230 'jm-twitter-cards/jm-twitter-cards.php', // JM Twitter Cards
231 'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
232 // Pure Web Brilliant's Social Graph Twitter Cards Extension
233 'twitter-cards/twitter-cards.php', // Twitter Cards
234 'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
235 'wp-twitter-cards/twitter_cards.php', // WP Twitter Cards
236 );
237
238 /**
239 * Message to display in admin_notice
240 * @var string
241 */
242 var $message = '';
243
244 /**
245 * Error to display in admin_notice
246 * @var string
247 */
248 var $error = '';
249
250 /**
251 * Modules that need more privacy description.
252 * @var string
253 */
254 var $privacy_checks = '';
255
256 /**
257 * Stats to record once the page loads
258 *
259 * @var array
260 */
261 var $stats = array();
262
263 /**
264 * Allows us to build a temporary security report
265 *
266 * @var array
267 */
268 static $security_report = array();
269
270 /**
271 * Jetpack_Sync object
272 */
273 var $sync;
274
275 /**
276 * Verified data for JSON authorization request
277 */
278 var $json_api_authorization_request = array();
279
280 /**
281 * Holds the singleton instance of this class
282 * @since 2.3.3
283 * @var Jetpack
284 */
285 static $instance = false;
286
287 /**
288 * Singleton
289 * @static
290 */
291 public static function init() {
292 if ( ! self::$instance ) {
293 if ( did_action( 'plugins_loaded' ) )
294 self::plugin_textdomain();
295 else
296 add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ), 99 );
297
298 self::$instance = new Jetpack;
299
300 self::$instance->plugin_upgrade();
301
302 add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
303
304 }
305
306 return self::$instance;
307 }
308
309 /**
310 * Must never be called statically
311 */
312 function plugin_upgrade() {
313 // Upgrade: 1.1 -> 1.2
314 if ( get_option( 'jetpack_id' ) ) {
315 // Move individual jetpack options to single array of options
316 $options = array();
317 foreach ( Jetpack_Options::get_option_names() as $option ) {
318 if ( false !== $value = get_option( "jetpack_$option" ) ) {
319 $options[$option] = $value;
320 }
321 }
322
323 if ( $options ) {
324 Jetpack_Options::update_options( $options );
325
326 foreach ( array_keys( $options ) as $option ) {
327 delete_option( "jetpack_$option" );
328 }
329 }
330
331 // Add missing version and old_version options
332 if ( ! $version = Jetpack_Options::get_option( 'version' ) ) {
333 $version = $old_version = '1.1:' . time();
334 do_action( 'updating_jetpack_version', $version, false );
335 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
336 }
337 }
338
339 // Upgrade from a single user token to a user_id-indexed array and a master_user ID
340 if ( ! Jetpack_Options::get_option( 'user_tokens' ) ) {
341 if ( $user_token = Jetpack_Options::get_option( 'user_token' ) ) {
342 $token_parts = explode( '.', $user_token );
343 if ( isset( $token_parts[2] ) ) {
344 $master_user = $token_parts[2];
345 $user_tokens = array( $master_user => $user_token );
346 Jetpack_Options::update_options( compact( 'master_user', 'user_tokens' ) );
347 Jetpack_Options::delete_option( 'user_token' );
348 } else {
349 // @todo: is this even possible?
350 trigger_error( sprintf( 'Jetpack::plugin_upgrade found no user_id in user_token "%s"', $user_token ), E_USER_WARNING );
351 }
352 }
353 }
354
355 // Clean up legacy G+ Authorship data.
356 if ( get_option( 'gplus_authors' ) ) {
357 delete_option( 'gplus_authors' );
358 delete_option( 'hide_gplus' );
359 delete_metadata( 'post', 0, 'gplus_authorship_disabled', null, true );
360 }
361
362 if ( ! get_option( 'jetpack_private_options' ) ) {
363 $jetpack_options = get_option( 'jetpack_options', array() );
364 foreach( Jetpack_Options::get_option_names( 'private' ) as $option_name ) {
365 if ( isset( $jetpack_options[ $option_name ] ) ) {
366 Jetpack_Options::update_option( $option_name, $jetpack_options[ $option_name ] );
367 unset( $jetpack_options[ $option_name ] );
368 }
369 }
370 update_option( 'jetpack_options', $jetpack_options );
371 }
372
373 if ( Jetpack::is_active() ) {
374 list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
375 if ( JETPACK__VERSION != $version ) {
376 add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
377 do_action( 'jetpack_sync_all_registered_options' );
378 }
379
380 //if Jetpack is connected check if jetpack_unique_connection exists and if not then set it
381 $jetpack_unique_connection = get_option( 'jetpack_unique_connection' );
382 $is_unique_connection = $jetpack_unique_connection && array_key_exists( 'version', $jetpack_unique_connection );
383 if ( ! $is_unique_connection ) {
384 $jetpack_unique_connection = array(
385 'connected' => 1,
386 'disconnected' => -1,
387 'version' => '3.6.1'
388 );
389 update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
390 }
391 }
392
393 if ( get_option( 'jetpack_json_api_full_management' ) ) {
394 delete_option( 'jetpack_json_api_full_management' );
395 self::activate_manage();
396 }
397
398 }
399
400 static function activate_manage( ) {
401
402 if ( did_action( 'init' ) || current_filter() == 'init' ) {
403 self::activate_module( 'manage', false, false );
404 } else if ( ! has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
405 add_action( 'init', array( __CLASS__, 'activate_manage' ) );
406 }
407
408 }
409
410 /**
411 * Constructor. Initializes WordPress hooks
412 */
413 private function __construct() {
414 /*
415 * Check for and alert any deprecated hooks
416 */
417 add_action( 'init', array( $this, 'deprecated_hooks' ) );
418
419 /*
420 * Do things that should run even in the network admin
421 * here, before we potentially fail out.
422 */
423 add_filter( 'jetpack_require_lib_dir', array( $this, 'require_lib_dir' ) );
424
425 /*
426 * Load things that should only be in Network Admin.
427 *
428 * For now blow away everything else until a more full
429 * understanding of what is needed at the network level is
430 * available
431 */
432 if( is_multisite() ) {
433 Jetpack_Network::init();
434
435 if( is_network_admin() )
436 return; // End here to prevent single site actions from firing
437 }
438
439
440 $theme_slug = get_option( 'stylesheet' );
441
442 $this->sync = new Jetpack_Sync;
443
444 // Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
445 // We access the "internal" method here only because the Jetpack object isn't instantiated yet
446 $this->sync->options(
447 JETPACK__PLUGIN_DIR . 'jetpack.php',
448 'home',
449 'siteurl',
450 'blogname',
451 'gmt_offset',
452 'timezone_string',
453 'security_report',
454 'stylesheet',
455 "theme_mods_{$theme_slug}",
456 'jetpack_sync_non_public_post_stati',
457 'jetpack_options',
458 'site_icon' // (int) - ID of core's Site Icon attachment ID
459 );
460
461 foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
462 $this->sync->options( __FILE__, 'jetpack_' . $option );
463 }
464
465 /**
466 * Sometimes you want to sync data to .com without adding options to .org sites.
467 * The mock option allows you to do just that.
468 */
469 $this->sync->mock_option( 'is_main_network', array( $this, 'is_main_network_option' ) );
470 $this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
471 $this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
472 $this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
473
474 /**
475 * Trigger an update to the main_network_site when we update the blogname of a site.
476 *
477 */
478 add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
479
480 add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
481
482 // Update the settings everytime the we register a new user to the site or we delete a user.
483 add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
484 add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
485
486 // Unlink user before deleting the user from .com
487 add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
488 add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
489
490 if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
491 @ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
492
493 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
494 $this->xmlrpc_server = new Jetpack_XMLRPC_Server();
495
496 $this->require_jetpack_authentication();
497
498 if ( Jetpack::is_active() ) {
499 // Hack to preserve $HTTP_RAW_POST_DATA
500 add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
501
502 $signed = $this->verify_xml_rpc_signature();
503 if ( $signed && ! is_wp_error( $signed ) ) {
504 // The actual API methods.
505 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
506 } else {
507 add_filter( 'xmlrpc_methods', '__return_empty_array' );
508 }
509 } else {
510 // The bootstrap API methods.
511 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
512 }
513
514 // Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
515 add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
516 } elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
517 $this->require_jetpack_authentication();
518 $this->add_remote_request_handlers();
519 } else {
520 if ( Jetpack::is_active() ) {
521 add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
522 add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
523 }
524 }
525
526 if ( Jetpack::is_active() ) {
527 Jetpack_Heartbeat::init();
528 }
529
530 add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
531 if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
532 wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
533 }
534
535 add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
536
537 add_action( 'admin_init', array( $this, 'admin_init' ) );
538 add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
539
540 add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
541
542 add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
543 // Filter the dashboard meta box order to swap the new one in in place of the old one.
544 add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
545
546 add_action( 'wp_ajax_jetpack-check-news-subscription', array( $this, 'check_news_subscription' ) );
547 add_action( 'wp_ajax_jetpack-subscribe-to-news', array( $this, 'subscribe_to_news' ) );
548
549 add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
550 add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
551
552 // Jump Start AJAX callback function
553 add_action( 'wp_ajax_jetpack_admin_ajax', array( $this, 'jetpack_jumpstart_ajax_callback' ) );
554 add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
555
556 add_action( 'wp_loaded', array( $this, 'register_assets' ) );
557 add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
558 add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
559 add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
560
561 add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
562
563 add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
564
565 add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
566
567 /**
568 * These actions run checks to load additional files.
569 * They check for external files or plugins, so they need to run as late as possible.
570 */
571 add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
572 add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
573 add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
574
575 add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
576 add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
577
578 add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
579
580 add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
581 add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
582
583 /**
584 * This is the hack to concatinate all css files into one.
585 * For description and reasoning see the implode_frontend_css method
586 *
587 * Super late priority so we catch all the registered styles
588 */
589 if( !is_admin() ) {
590 add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
591 add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
592 }
593
594 // Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
595 add_action( 'add_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
596 add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
597 add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
598 add_action( 'jetpack_heartbeat', array( $this, 'jetpack_sync_core_icon' ) );
599
600 }
601
602 /*
603 * Make sure any site icon added to core can get
604 * synced back to dotcom, so we can display it there.
605 */
606 function jetpack_sync_core_icon() {
607 if ( function_exists( 'get_site_icon_url' ) ) {
608 $url = get_site_icon_url();
609 } else {
610 return;
611 }
612
613 require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
614 // If there's a core icon, maybe update the option. If not, fall back to Jetpack's.
615 if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
616 // This is the option that is synced with dotcom
617 Jetpack_Options::update_option( 'site_icon_url', $url );
618 } else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
619 Jetpack_Options::delete_option( 'site_icon_url' );
620 }
621 }
622
623 /**
624 * The callback for the Jump Start ajax requests.
625 */
626 function jetpack_jumpstart_ajax_callback() {
627 // Check for nonce
628 if ( ! isset( $_REQUEST['jumpstartNonce'] ) || ! wp_verify_nonce( $_REQUEST['jumpstartNonce'], 'jetpack-jumpstart-nonce' ) )
629 wp_die( 'permissions check failed' );
630
631 if ( isset( $_REQUEST['jumpStartActivate'] ) && 'jump-start-activate' == $_REQUEST['jumpStartActivate'] ) {
632 // Update the jumpstart option
633 if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
634 Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
635 }
636
637 // Loops through the requested "Jump Start" modules, and activates them.
638 // Custom 'no_message' state, so that no message will be shown on reload.
639 $modules = $_REQUEST['jumpstartModSlug'];
640 $module_slugs = array();
641 foreach( $modules as $module => $value ) {
642 $module_slugs[] = $value['module_slug'];
643 }
644
645 // Check for possible conflicting plugins
646 $module_slugs_filtered = $this->filter_default_modules( $module_slugs );
647
648 foreach ( $module_slugs_filtered as $module_slug ) {
649 Jetpack::log( 'activate', $module_slug );
650 Jetpack::activate_module( $module_slug, false, false );
651 Jetpack::state( 'message', 'no_message' );
652 }
653
654 // Set the default sharing buttons and set to display on posts if none have been set.
655 $sharing_services = get_option( 'sharing-services' );
656 $sharing_options = get_option( 'sharing-options' );
657 if ( empty( $sharing_services['visible'] ) ) {
658 // Default buttons to set
659 $visible = array(
660 'twitter',
661 'facebook',
662 'google-plus-1',
663 );
664 $hidden = array();
665
666 // Set some sharing settings
667 $sharing = new Sharing_Service();
668 $sharing_options['global'] = array(
669 'button_style' => 'icon',
670 'sharing_label' => $sharing->default_sharing_label,
671 'open_links' => 'same',
672 'show' => array( 'post' ),
673 'custom' => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
674 );
675
676 update_option( 'sharing-options', $sharing_options );
677
678 // Send a success response so that we can display an error message.
679 $success = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
680 echo json_encode( $success );
681 exit;
682 }
683
684 } elseif ( isset( $_REQUEST['disableJumpStart'] ) && true == $_REQUEST['disableJumpStart'] ) {
685 // If dismissed, flag the jumpstart option as such.
686 // Send a success response so that we can display an error message.
687 if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
688 $success = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' );
689 echo json_encode( $success );
690 exit;
691 }
692
693 } elseif ( isset( $_REQUEST['jumpStartDeactivate'] ) && 'jump-start-deactivate' == $_REQUEST['jumpStartDeactivate'] ) {
694
695 // FOR TESTING ONLY
696 // @todo remove
697 $modules = (array) $_REQUEST['jumpstartModSlug'];
698 foreach( $modules as $module => $value ) {
699 if ( !in_array( $value['module_slug'], Jetpack::get_default_modules() ) ) {
700 Jetpack::log( 'deactivate', $value['module_slug'] );
701 Jetpack::deactivate_module( $value['module_slug'] );
702 Jetpack::state( 'message', 'no_message' );
703 } else {
704 Jetpack::log( 'activate', $value['module_slug'] );
705 Jetpack::activate_module( $value['module_slug'], false, false );
706 Jetpack::state( 'message', 'no_message' );
707 }
708 }
709
710 Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
711 echo "reload the page";
712 }
713
714 wp_die();
715 }
716
717 /**
718 * If there are any stats that need to be pushed, but haven't been, push them now.
719 */
720 function __destruct() {
721 if ( ! empty( $this->stats ) ) {
722 $this->do_stats( 'server_side' );
723 }
724 }
725
726 function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
727 switch( $cap ) {
728 case 'jetpack_connect' :
729 case 'jetpack_reconnect' :
730 if ( Jetpack::is_development_mode() ) {
731 $caps = array( 'do_not_allow' );
732 break;
733 }
734 /**
735 * Pass through. If it's not development mode, these should match disconnect.
736 * Let users disconnect if it's development mode, just in case things glitch.
737 */
738 case 'jetpack_disconnect' :
739 /**
740 * In multisite, can individual site admins manage their own connection?
741 *
742 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
743 */
744 if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
745 if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
746 /**
747 * We need to update the option name -- it's terribly unclear which
748 * direction the override goes.
749 *
750 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
751 */
752 $caps = array( 'do_not_allow' );
753 break;
754 }
755 }
756
757 $caps = array( 'manage_options' );
758 break;
759 case 'jetpack_manage_modules' :
760 case 'jetpack_activate_modules' :
761 case 'jetpack_deactivate_modules' :
762 $caps = array( 'manage_options' );
763 break;
764 case 'jetpack_configure_modules' :
765 $caps = array( 'manage_options' );
766 break;
767 case 'jetpack_admin_page' :
768 if ( Jetpack::is_development_mode() ) {
769 $caps = array( 'manage_options' );
770 break;
771 }
772
773 if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
774 $caps = array( 'do_not_allow' );
775 break;
776 }
777 /**
778 * Pass through. If it's not development mode, these should match the admin page.
779 * Let users disconnect if it's development mode, just in case things glitch.
780 */
781 case 'jetpack_connect_user' :
782 if ( Jetpack::is_development_mode() ) {
783 $caps = array( 'do_not_allow' );
784 break;
785 }
786 $caps = array( 'read' );
787 break;
788 }
789 return $caps;
790 }
791
792 function require_jetpack_authentication() {
793 // Don't let anyone authenticate
794 $_COOKIE = array();
795 remove_all_filters( 'authenticate' );
796
797 /**
798 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
799 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
800 * generate false-positives.
801 */
802 remove_filter( 'wp_login_failed', 'limit_login_failed' );
803
804 if ( Jetpack::is_active() ) {
805 // Allow Jetpack authentication
806 add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
807 }
808 }
809
810 /**
811 * Load language files
812 */
813 public static function plugin_textdomain() {
814 // Note to self, the third argument must not be hardcoded, to account for relocated folders.
815 load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
816 }
817
818 /**
819 * Register assets for use in various modules and the Jetpack admin page.
820 *
821 * @uses wp_script_is, wp_register_script, plugins_url
822 * @action wp_loaded
823 * @return null
824 */
825 public function register_assets() {
826 if ( ! wp_script_is( 'spin', 'registered' ) ) {
827 wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
828 }
829
830 if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
831 wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
832 }
833
834 if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
835 wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
836 }
837
838 /**
839 * As jetpack_register_genericons is by default fired off a hook,
840 * the hook may have already fired by this point.
841 * So, let's just trigger it manually.
842 */
843 require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
844 jetpack_register_genericons();
845
846 if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
847 wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
848 }
849
850 /**
851 * Device Pixels support
852 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
853 */
854 function devicepx() {
855 if ( Jetpack::is_active() ) {
856 wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
857 }
858 }
859
860 /*
861 * Returns the location of Jetpack's lib directory. This filter is applied
862 * in require_lib().
863 *
864 * @filter require_lib_dir
865 */
866 function require_lib_dir( $lib_dir ) {
867 return JETPACK__PLUGIN_DIR . '_inc/lib';
868 }
869
870 /**
871 * Return the network_site_url so that .com knows what network this site is a part of.
872 * @param bool $option
873 * @return string
874 */
875 public function jetpack_main_network_site_option( $option ) {
876 return network_site_url();
877 }
878
879 /**
880 * Return whether we are dealing with a multi network setup or not.
881 * The reason we are type casting this is because we want to avoid the situation where
882 * the result is false since when is_main_network_option return false it cases
883 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
884 * database which could be set to anything as opposed to what this function returns.
885 * @param bool $option
886 *
887 * @return boolean
888 */
889 public function is_main_network_option( $option ) {
890 // return '1' or ''
891 return (string) (bool) Jetpack::is_multi_network();
892 }
893
894 /**
895 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
896 *
897 * @param string $option
898 * @return boolean
899 */
900 public function is_multisite( $option ) {
901 return (string) (bool) is_multisite();
902 }
903
904 /**
905 * Implemented since there is no core is multi network function
906 * Right now there is no way to tell if we which network is the dominant network on the system
907 *
908 * @since 3.3
909 * @return boolean
910 */
911 public static function is_multi_network() {
912 global $wpdb;
913
914 // if we don't have a multi site setup no need to do any more
915 if ( ! is_multisite() ) {
916 return false;
917 }
918
919 $num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
920 if ( $num_sites > 1 ) {
921 return true;
922 } else {
923 return false;
924 }
925 }
926
927 /**
928 * Trigger an update to the main_network_site when we update the siteurl of a site.
929 * @return null
930 */
931 function update_jetpack_main_network_site_option() {
932 // do_action( 'add_option_$option', '$option', '$value-of-the-option' );
933 do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
934 do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
935 do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
936 }
937
938 /**
939 * Get back if the current site is single user site.
940 *
941 * @return bool
942 */
943 public static function is_single_user_site() {
944
945 $user_query = new WP_User_Query( array(
946 'blog_id' => get_current_blog_id(),
947 'fields' => 'ID',
948 'number' => 2
949 ) );
950 return 1 === (int) $user_query->get_total();
951 }
952
953 /**
954 * Invalides the transient as well as triggers the update of the mock option.
955 *
956 * @return null
957 */
958 function is_single_user_site_invalidate() {
959 do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
960 }
961
962
963
964 /**
965 * Is Jetpack active?
966 */
967 public static function is_active() {
968 return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
969 }
970
971 /**
972 * Is Jetpack in development (offline) mode?
973 */
974 public static function is_development_mode() {
975 $development_mode = false;
976
977 if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
978 $development_mode = JETPACK_DEV_DEBUG;
979 }
980
981 elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
982 $development_mode = true;
983 }
984 return apply_filters( 'jetpack_development_mode', $development_mode );
985 }
986
987 /**
988 * Get Jetpack development mode notice text and notice class.
989 *
990 * Mirrors the checks made in Jetpack::is_development_mode
991 *
992 */
993 public static function show_development_mode_notice() {
994 if ( Jetpack::is_development_mode() ) {
995 if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
996 $notice = __( 'In Development Mode, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' );
997 } elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
998 $notice = __( 'In Development Mode, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
999 } else {
1000 $notice = __( 'In Development Mode, via the jetpack_development_mode filter.', 'jetpack' );
1001 }
1002
1003 echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1004 }
1005
1006 // Throw up a notice if using a development version and as for feedback.
1007 if ( Jetpack::is_development_version() ) {
1008 $notice = sprintf( _x( 'You are currently running a development version of Jetpack. %1s Submit your feedback. %2s', '%1s & %2s are HTML tags', 'jetpack' ), '<a href="https://jetpack.me/contact-support/beta-group/" target="_blank">', '</a>' );
1009
1010 echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1011 }
1012 }
1013
1014 /**
1015 * Whether Jetpack's version maps to a public release, or a development version.
1016 */
1017 public static function is_development_version() {
1018 return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1019 }
1020
1021 /**
1022 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1023 */
1024 public static function is_user_connected( $user_id = false ) {
1025 $user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1026 if ( ! $user_id ) {
1027 return false;
1028 }
1029 return (bool) Jetpack_Data::get_access_token( $user_id );
1030 }
1031
1032 /**
1033 * Get the wpcom user data of the current|specified connected user.
1034 */
1035 public static function get_connected_user_data( $user_id = null ) {
1036 if ( ! $user_id ) {
1037 $user_id = get_current_user_id();
1038 }
1039 Jetpack::load_xml_rpc_client();
1040 $xml = new Jetpack_IXR_Client( array(
1041 'user_id' => $user_id,
1042 ) );
1043 $xml->query( 'wpcom.getUser' );
1044 if ( ! $xml->isError() ) {
1045 return $xml->getResponse();
1046 }
1047 return false;
1048 }
1049
1050 /**
1051 * Get the wpcom email of the current|specified connected user.
1052 */
1053 public static function get_connected_user_email( $user_id = null ) {
1054 if ( ! $user_id ) {
1055 $user_id = get_current_user_id();
1056 }
1057 Jetpack::load_xml_rpc_client();
1058 $xml = new Jetpack_IXR_Client( array(
1059 'user_id' => $user_id,
1060 ) );
1061 $xml->query( 'wpcom.getUserEmail' );
1062 if ( ! $xml->isError() ) {
1063 return $xml->getResponse();
1064 }
1065 return false;
1066 }
1067
1068 /**
1069 * Get the wpcom email of the master user.
1070 */
1071 public static function get_master_user_email() {
1072 $master_user_id = Jetpack_Options::get_option( 'master_user' );
1073 if ( $master_user_id ) {
1074 return self::get_connected_user_email( $master_user_id );
1075 }
1076 return '';
1077 }
1078
1079 function current_user_is_connection_owner() {
1080 $user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1081 return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1082 }
1083
1084 /**
1085 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1086 */
1087 function extra_oembed_providers() {
1088 // Cloudup: https://dev.cloudup.com/#oembed
1089 wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1090 }
1091
1092 /**
1093 * Synchronize connected user role changes
1094 */
1095 function user_role_change( $user_id ) {
1096 if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1097 $current_user_id = get_current_user_id();
1098 wp_set_current_user( $user_id );
1099 $role = $this->translate_current_user_to_role();
1100 $signed_role = $this->sign_role( $role );
1101 wp_set_current_user( $current_user_id );
1102
1103 $master_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1104 $master_user_id = absint( $master_token->external_user_id );
1105
1106 if ( ! $master_user_id )
1107 return; // this shouldn't happen
1108
1109 Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1110 //@todo retry on failure
1111
1112 //try to choose a new master if we're demoting the current one
1113 if ( $user_id == $master_user_id && 'administrator' != $role ) {
1114 $query = new WP_User_Query(
1115 array(
1116 'fields' => array( 'id' ),
1117 'role' => 'administrator',
1118 'orderby' => 'id',
1119 'exclude' => array( $master_user_id ),
1120 )
1121 );
1122 $new_master = false;
1123 foreach ( $query->results as $result ) {
1124 $uid = absint( $result->id );
1125 if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1126 $new_master = $uid;
1127 break;
1128 }
1129 }
1130
1131 if ( $new_master ) {
1132 Jetpack_Options::update_option( 'master_user', $new_master );
1133 }
1134 // else disconnect..?
1135 }
1136 }
1137 }
1138
1139 /**
1140 * Loads the currently active modules.
1141 */
1142 public static function load_modules() {
1143 if ( ! self::is_active() && !self::is_development_mode() ) {
1144 if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1145 return;
1146 }
1147 }
1148
1149 $version = Jetpack_Options::get_option( 'version' );
1150 if ( ! $version ) {
1151 $version = $old_version = JETPACK__VERSION . ':' . time();
1152 do_action( 'updating_jetpack_version', $version, false );
1153 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1154 }
1155 list( $version ) = explode( ':', $version );
1156
1157 $modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1158
1159 $modules_data = array();
1160
1161 // Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1162 if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1163 $updated_modules = array();
1164 foreach ( $modules as $module ) {
1165 $modules_data[ $module ] = Jetpack::get_module( $module );
1166 if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1167 continue;
1168 }
1169
1170 if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1171 continue;
1172 }
1173
1174 $updated_modules[] = $module;
1175 }
1176
1177 $modules = array_diff( $modules, $updated_modules );
1178 }
1179
1180 $is_development_mode = Jetpack::is_development_mode();
1181
1182 foreach ( $modules as $module ) {
1183 // If we're in dev mode, disable modules requiring a connection
1184 if ( $is_development_mode ) {
1185 // Prime the pump if we need to
1186 if ( empty( $modules_data[ $module ] ) ) {
1187 $modules_data[ $module ] = Jetpack::get_module( $module );
1188 }
1189 // If the module requires a connection, but we're in local mode, don't include it.
1190 if ( $modules_data[ $module ]['requires_connection'] ) {
1191 continue;
1192 }
1193 }
1194
1195 if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1196 continue;
1197 }
1198
1199 require Jetpack::get_module_path( $module );
1200 do_action( 'jetpack_module_loaded_' . $module );
1201 }
1202
1203 do_action( 'jetpack_modules_loaded' );
1204
1205 // 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.
1206 if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1207 require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1208 }
1209
1210 /**
1211 * Check if Jetpack's REST API compat file should be included
1212 * @action plugins_loaded
1213 * @return null
1214 */
1215 public function check_rest_api_compat() {
1216 $_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1217
1218 if ( function_exists( 'bbpress' ) )
1219 $_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1220
1221 foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1222 require_once $_jetpack_rest_api_compat_include;
1223 }
1224
1225 /**
1226 * Gets all plugins currently active in values, regardless of whether they're
1227 * traditionally activated or network activated.
1228 *
1229 * @todo Store the result in core's object cache maybe?
1230 */
1231 public static function get_active_plugins() {
1232 $active_plugins = (array) get_option( 'active_plugins', array() );
1233
1234 if ( is_multisite() ) {
1235 // Due to legacy code, active_sitewide_plugins stores them in the keys,
1236 // whereas active_plugins stores them in the values.
1237 $network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1238 if ( $network_plugins ) {
1239 $active_plugins = array_merge( $active_plugins, $network_plugins );
1240 }
1241 }
1242
1243 sort( $active_plugins );
1244
1245 return $active_plugins;
1246 }
1247
1248 /**
1249 * Checks whether a specific plugin is active.
1250 *
1251 * We don't want to store these in a static variable, in case
1252 * there are switch_to_blog() calls involved.
1253 */
1254 public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1255 return in_array( $plugin, self::get_active_plugins() );
1256 }
1257
1258 /**
1259 * Check if Jetpack's Open Graph tags should be used.
1260 * If certain plugins are active, Jetpack's og tags are suppressed.
1261 *
1262 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1263 * @action plugins_loaded
1264 * @return null
1265 */
1266 public function check_open_graph() {
1267 if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1268 add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1269 }
1270
1271 $active_plugins = self::get_active_plugins();
1272
1273 if ( ! empty( $active_plugins ) ) {
1274 foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1275 if ( in_array( $plugin, $active_plugins ) ) {
1276 add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1277 break;
1278 }
1279 }
1280 }
1281
1282 if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1283 require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1284 }
1285 }
1286
1287 /**
1288 * Check if Jetpack's Twitter tags should be used.
1289 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1290 *
1291 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1292 * @action plugins_loaded
1293 * @return null
1294 */
1295 public function check_twitter_tags() {
1296
1297 $active_plugins = self::get_active_plugins();
1298
1299 if ( ! empty( $active_plugins ) ) {
1300 foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1301 if ( in_array( $plugin, $active_plugins ) ) {
1302 add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1303 break;
1304 }
1305 }
1306 }
1307
1308 if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1309 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1310 }
1311 }
1312
1313
1314
1315
1316 /*
1317 *
1318 * Jetpack Security Reports
1319 *
1320 * Allowed types: login_form, backup, file_scanning, spam
1321 *
1322 * Args for login_form and spam: 'blocked'=>(int)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1323 *
1324 * Args for backup and file_scanning: 'last'=>(timestamp)(optional), 'next'=>(timestamp)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1325 *
1326 *
1327 * Example code to submit a security report:
1328 *
1329 * function akismet_submit_jetpack_security_report() {
1330 * Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1331 * }
1332 * add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1333 *
1334 */
1335
1336
1337 /**
1338 * Calls for security report submissions.
1339 *
1340 * @return null
1341 */
1342 public static function perform_security_reporting() {
1343 $no_check_needed = get_site_transient( 'security_report_performed_recently' );
1344
1345 if ( $no_check_needed ) {
1346 return;
1347 }
1348
1349 do_action( 'jetpack_security_report' );
1350
1351 Jetpack_Options::update_option( 'security_report', self::$security_report );
1352 set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1353 }
1354
1355 /**
1356 * Allows plugins to submit security reports.
1357 *
1358 * @param string $type Report type (login_form, backup, file_scanning, spam)
1359 * @param string $plugin_file Plugin __FILE__, so that we can pull plugin data
1360 * @param array $args See definitions above
1361 */
1362 public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1363
1364 if( !doing_action( 'jetpack_security_report' ) ) {
1365 return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports. Please use the jetpack_security_report hook.' );
1366 }
1367
1368 if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1369 return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1370 }
1371
1372 if( !function_exists( 'get_plugin_data' ) ) {
1373 include( ABSPATH . 'wp-admin/includes/plugin.php' );
1374 }
1375
1376 //Get rid of any non-allowed args
1377 $args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1378
1379 $plugin = get_plugin_data( $plugin_file );
1380
1381 if ( !$plugin['Name'] ) {
1382 return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1383 }
1384
1385 // Sanitize everything to make sure we're not syncing something wonky
1386 $type = sanitize_key( $type );
1387
1388 $args['plugin'] = $plugin;
1389
1390 // Cast blocked, last and next as integers.
1391 // Last and next should be in unix timestamp format
1392 if ( isset( $args['blocked'] ) ) {
1393 $args['blocked'] = (int) $args['blocked'];
1394 }
1395 if ( isset( $args['last'] ) ) {
1396 $args['last'] = (int) $args['last'];
1397 }
1398 if ( isset( $args['next'] ) ) {
1399 $args['next'] = (int) $args['next'];
1400 }
1401 if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1402 $args['status'] = 'ok';
1403 }
1404 if ( isset( $args['message'] ) ) {
1405
1406 if( $args['status'] == 'ok' ) {
1407 unset( $args['message'] );
1408 }
1409
1410 $allowed_html = array(
1411 'a' => array(
1412 'href' => array(),
1413 'title' => array()
1414 ),
1415 'em' => array(),
1416 'strong' => array(),
1417 );
1418
1419 $args['message'] = wp_kses( $args['message'], $allowed_html );
1420 }
1421
1422 $plugin_name = $plugin[ 'Name' ];
1423
1424 self::$security_report[ $type ][ $plugin_name ] = $args;
1425 }
1426
1427 /**
1428 * Collects a new report if needed, then returns it.
1429 */
1430 public function get_security_report() {
1431 self::perform_security_reporting();
1432 return Jetpack_Options::get_option( 'security_report' );
1433 }
1434
1435
1436 /* Jetpack Options API */
1437
1438 public static function get_option_names( $type = 'compact' ) {
1439 return Jetpack_Options::get_option_names( $type );
1440 }
1441
1442 /**
1443 * Returns the requested option. Looks in jetpack_options or jetpack_$name as appropriate.
1444 *
1445 * @param string $name Option name
1446 * @param mixed $default (optional)
1447 */
1448 public static function get_option( $name, $default = false ) {
1449 return Jetpack_Options::get_option( $name, $default );
1450 }
1451
1452 /**
1453 * Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1454 * Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1455 * $name must be a registered option name.
1456 */
1457 public static function create_nonce( $name ) {
1458 $secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1459
1460 Jetpack_Options::update_option( $name, $secret );
1461 @list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1462 if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1463 return new Jetpack_Error( 'missing_secrets' );
1464
1465 return array(
1466 'secret_1' => $secret_1,
1467 'secret_2' => $secret_2,
1468 'eol' => $eol,
1469 );
1470 }
1471
1472 /**
1473 * Updates the single given option. Updates jetpack_options or jetpack_$name as appropriate.
1474 *
1475 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1476 * @param string $name Option name
1477 * @param mixed $value Option value
1478 */
1479 public static function update_option( $name, $value ) {
1480 _deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1481 return Jetpack_Options::update_option( $name, $value );
1482 }
1483
1484 /**
1485 * Updates the multiple given options. Updates jetpack_options and/or jetpack_$name as appropriate.
1486 *
1487 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1488 * @param array $array array( option name => option value, ... )
1489 */
1490 public static function update_options( $array ) {
1491 _deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1492 return Jetpack_Options::update_options( $array );
1493 }
1494
1495 /**
1496 * Deletes the given option. May be passed multiple option names as an array.
1497 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1498 *
1499 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1500 * @param string|array $names
1501 */
1502 public static function delete_option( $names ) {
1503 _deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1504 return Jetpack_Options::delete_option( $names );
1505 }
1506
1507 /**
1508 * Enters a user token into the user_tokens option
1509 *
1510 * @param int $user_id
1511 * @param string $token
1512 * return bool
1513 */
1514 public static function update_user_token( $user_id, $token, $is_master_user ) {
1515 // not designed for concurrent updates
1516 $user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1517 if ( ! is_array( $user_tokens ) )
1518 $user_tokens = array();
1519 $user_tokens[$user_id] = $token;
1520 if ( $is_master_user ) {
1521 $master_user = $user_id;
1522 $options = compact( 'user_tokens', 'master_user' );
1523 } else {
1524 $options = compact( 'user_tokens' );
1525 }
1526 return Jetpack_Options::update_options( $options );
1527 }
1528
1529 /**
1530 * Returns an array of all PHP files in the specified absolute path.
1531 * Equivalent to glob( "$absolute_path/*.php" ).
1532 *
1533 * @param string $absolute_path The absolute path of the directory to search.
1534 * @return array Array of absolute paths to the PHP files.
1535 */
1536 public static function glob_php( $absolute_path ) {
1537 if ( function_exists( 'glob' ) ) {
1538 return glob( "$absolute_path/*.php" );
1539 }
1540
1541 $absolute_path = untrailingslashit( $absolute_path );
1542 $files = array();
1543 if ( ! $dir = @opendir( $absolute_path ) ) {
1544 return $files;
1545 }
1546
1547 while ( false !== $file = readdir( $dir ) ) {
1548 if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1549 continue;
1550 }
1551
1552 $file = "$absolute_path/$file";
1553
1554 if ( ! is_file( $file ) ) {
1555 continue;
1556 }
1557
1558 $files[] = $file;
1559 }
1560
1561 closedir( $dir );
1562
1563 return $files;
1564 }
1565
1566 public static function activate_new_modules( $redirect = false ) {
1567 if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1568 return;
1569 }
1570
1571 $jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1572 if ( ! $jetpack_old_version ) {
1573 $jetpack_old_version = $version = $old_version = '1.1:' . time();
1574 do_action( 'updating_jetpack_version', $version, false );
1575 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1576 }
1577
1578 list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1579
1580 if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1581 return;
1582 }
1583
1584 $active_modules = Jetpack::get_active_modules();
1585 $reactivate_modules = array();
1586 foreach ( $active_modules as $active_module ) {
1587 $module = Jetpack::get_module( $active_module );
1588 if ( ! isset( $module['changed'] ) ) {
1589 continue;
1590 }
1591
1592 if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1593 continue;
1594 }
1595
1596 $reactivate_modules[] = $active_module;
1597 Jetpack::deactivate_module( $active_module );
1598 }
1599
1600 $new_version = JETPACK__VERSION . ':' . time();
1601 do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1602 Jetpack_Options::update_options(
1603 array(
1604 'version' => $new_version,
1605 'old_version' => $jetpack_old_version,
1606 )
1607 );
1608
1609 Jetpack::state( 'message', 'modules_activated' );
1610 Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
1611
1612 if ( $redirect ) {
1613 $page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1614 if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1615 $page = $_GET['page'];
1616 }
1617
1618 wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1619 exit;
1620 }
1621 }
1622
1623 /**
1624 * List available Jetpack modules. Simply lists .php files in /modules/.
1625 * Make sure to tuck away module "library" files in a sub-directory.
1626 */
1627 public static function get_available_modules( $min_version = false, $max_version = false ) {
1628 static $modules = null;
1629
1630 if ( ! isset( $modules ) ) {
1631 $available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1632 // Use the cache if we're on the front-end and it's available...
1633 if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1634 $modules = $available_modules_option[ JETPACK__VERSION ];
1635 } else {
1636 $files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1637
1638 $modules = array();
1639
1640 foreach ( $files as $file ) {
1641 if ( ! $headers = Jetpack::get_module( $file ) ) {
1642 continue;
1643 }
1644
1645 $modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
1646 }
1647
1648 Jetpack_Options::update_option( 'available_modules', array(
1649 JETPACK__VERSION => $modules,
1650 ) );
1651 }
1652 }
1653
1654 $mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
1655
1656 if ( ! $min_version && ! $max_version ) {
1657 return array_keys( $mods );
1658 }
1659
1660 $r = array();
1661 foreach ( $mods as $slug => $introduced ) {
1662 if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
1663 continue;
1664 }
1665
1666 if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
1667 continue;
1668 }
1669
1670 $r[] = $slug;
1671 }
1672
1673 return $r;
1674 }
1675
1676 /**
1677 * Default modules loaded on activation.
1678 */
1679 public static function get_default_modules( $min_version = false, $max_version = false ) {
1680 $return = array();
1681
1682 foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
1683 $module_data = Jetpack::get_module( $module );
1684
1685 switch ( strtolower( $module_data['auto_activate'] ) ) {
1686 case 'yes' :
1687 $return[] = $module;
1688 break;
1689 case 'public' :
1690 if ( Jetpack_Options::get_option( 'public' ) ) {
1691 $return[] = $module;
1692 }
1693 break;
1694 case 'no' :
1695 default :
1696 break;
1697 }
1698 }
1699 return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
1700 }
1701
1702 /**
1703 * Checks activated modules during auto-activation to determine
1704 * if any of those modules are being deprecated. If so, close
1705 * them out, and add any replacement modules.
1706 *
1707 * Runs at priority 99 by default.
1708 *
1709 * This is run late, so that it can still activate a module if
1710 * the new module is a replacement for another that the user
1711 * currently has active, even if something at the normal priority
1712 * would kibosh everything.
1713 *
1714 * @since 2.6
1715 * @uses jetpack_get_default_modules filter
1716 * @param array $modules
1717 * @return array
1718 */
1719 function handle_deprecated_modules( $modules ) {
1720 $deprecated_modules = array(
1721 'debug' => null, // Closed out and moved to ./class.jetpack-debugger.php
1722 'wpcc' => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
1723 'gplus-authorship' => null, // Closed out in 3.2 -- Google dropped support.
1724 );
1725
1726 // Don't activate SSO if they never completed activating WPCC.
1727 if ( Jetpack::is_module_active( 'wpcc' ) ) {
1728 $wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
1729 if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
1730 $deprecated_modules['wpcc'] = null;
1731 }
1732 }
1733
1734 foreach ( $deprecated_modules as $module => $replacement ) {
1735 if ( Jetpack::is_module_active( $module ) ) {
1736 self::deactivate_module( $module );
1737 if ( $replacement ) {
1738 $modules[] = $replacement;
1739 }
1740 }
1741 }
1742
1743 return array_unique( $modules );
1744 }
1745
1746 /**
1747 * Checks activated plugins during auto-activation to determine
1748 * if any of those plugins are in the list with a corresponding module
1749 * that is not compatible with the plugin. The module will not be allowed
1750 * to auto-activate.
1751 *
1752 * @since 2.6
1753 * @uses jetpack_get_default_modules filter
1754 * @param array $modules
1755 * @return array
1756 */
1757 function filter_default_modules( $modules ) {
1758
1759 $active_plugins = self::get_active_plugins();
1760
1761 if ( ! empty( $active_plugins ) ) {
1762
1763 // For each module we'd like to auto-activate...
1764 foreach ( $modules as $key => $module ) {
1765 // If there are potential conflicts for it...
1766 if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
1767 // For each potential conflict...
1768 foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
1769 // If that conflicting plugin is active...
1770 if ( in_array( $plugin, $active_plugins ) ) {
1771 // Remove that item from being auto-activated.
1772 unset( $modules[ $key ] );
1773 }
1774 }
1775 }
1776 }
1777 }
1778
1779 return $modules;
1780 }
1781
1782 /**
1783 * Extract a module's slug from its full path.
1784 */
1785 public static function get_module_slug( $file ) {
1786 return str_replace( '.php', '', basename( $file ) );
1787 }
1788
1789 /**
1790 * Generate a module's path from its slug.
1791 */
1792 public static function get_module_path( $slug ) {
1793 return JETPACK__PLUGIN_DIR . "modules/$slug.php";
1794 }
1795
1796 /**
1797 * Load module data from module file. Headers differ from WordPress
1798 * plugin headers to avoid them being identified as standalone
1799 * plugins on the WordPress plugins page.
1800 */
1801 public static function get_module( $module ) {
1802 $headers = array(
1803 'name' => 'Module Name',
1804 'description' => 'Module Description',
1805 'jumpstart_desc' => 'Jumpstart Description',
1806 'sort' => 'Sort Order',
1807 'recommendation_order' => 'Recommendation Order',
1808 'introduced' => 'First Introduced',
1809 'changed' => 'Major Changes In',
1810 'deactivate' => 'Deactivate',
1811 'free' => 'Free',
1812 'requires_connection' => 'Requires Connection',
1813 'auto_activate' => 'Auto Activate',
1814 'module_tags' => 'Module Tags',
1815 'feature' => 'Feature',
1816 );
1817
1818 $file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
1819
1820 $mod = Jetpack::get_file_data( $file, $headers );
1821 if ( empty( $mod['name'] ) ) {
1822 return false;
1823 }
1824
1825 $mod['jumpstart_desc'] = _x( $mod['jumpstart_desc'], 'Jumpstart Description', 'jetpack' );
1826 $mod['name'] = _x( $mod['name'], 'Module Name', 'jetpack' );
1827 $mod['description'] = _x( $mod['description'], 'Module Description', 'jetpack' );
1828 $mod['sort'] = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
1829 $mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
1830 $mod['deactivate'] = empty( $mod['deactivate'] );
1831 $mod['free'] = empty( $mod['free'] );
1832 $mod['requires_connection'] = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
1833
1834 if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
1835 $mod['auto_activate'] = 'No';
1836 } else {
1837 $mod['auto_activate'] = (string) $mod['auto_activate'];
1838 }
1839
1840 if ( $mod['module_tags'] ) {
1841 $mod['module_tags'] = explode( ',', $mod['module_tags'] );
1842 $mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
1843 $mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
1844 } else {
1845 $mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
1846 }
1847
1848 if ( $mod['feature'] ) {
1849 $mod['feature'] = explode( ',', $mod['feature'] );
1850 $mod['feature'] = array_map( 'trim', $mod['feature'] );
1851 } else {
1852 $mod['feature'] = array( self::translate_module_tag( 'Other' ) );
1853 }
1854
1855 /**
1856 * Filter the feature array on a module
1857 *
1858 * This filter allows you to control where each module is filtered: Recommended,
1859 * Jumpstart, and the default "Other" listing.
1860 *
1861 * @since 3.5
1862 *
1863 * @param array $mod['feature'] The areas to feature this module:
1864 * 'Jumpstart' adds to the "Jumpstart" option to activate many modules at once
1865 * 'Recommended' shows on the main Jetpack admin screen
1866 * 'Other' should be the default if no other value is in the array
1867 * @param string $module The slug of the module, e.g. sharedaddy
1868 * @param array $mod All the currently assembled module data
1869 */
1870 $mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
1871
1872 /**
1873 * Filter the returned data about a module.
1874 *
1875 * This filter allows overriding any info about Jetpack modules. It is dangerous,
1876 * so please be careful.
1877 *
1878 * @since 3.6
1879 *
1880 * @param array $mod The details of the requested module.
1881 * @param string $module The slug of the module, e.g. sharedaddy
1882 * @param string $file The path to the module source file.
1883 */
1884 return apply_filters( 'jetpack_get_module', $mod, $module, $file );
1885 }
1886
1887 /**
1888 * Like core's get_file_data implementation, but caches the result.
1889 */
1890 public static function get_file_data( $file, $headers ) {
1891 //Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
1892 $file_name = basename( $file );
1893 $file_data_option = Jetpack_Options::get_option( 'file_data', array() );
1894 $key = md5( $file_name . serialize( $headers ) );
1895 $refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
1896
1897 // If we don't need to refresh the cache, and already have the value, short-circuit!
1898 if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
1899 return $file_data_option[ JETPACK__VERSION ][ $key ];
1900 }
1901
1902 $data = get_file_data( $file, $headers );
1903
1904 // Strip out any old Jetpack versions that are cluttering the option.
1905 $file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
1906 $file_data_option[ JETPACK__VERSION ][ $key ] = $data;
1907 Jetpack_Options::update_option( 'file_data', $file_data_option );
1908
1909 return $data;
1910 }
1911
1912 public static function translate_module_tag( $untranslated_tag ) {
1913 // Tags are aggregated by tools/build-module-headings-translations.php
1914 // and output in modules/module-headings.php
1915 return _x( $untranslated_tag, 'Module Tag', 'jetpack' );
1916 }
1917
1918 /**
1919 * Get a list of activated modules as an array of module slugs.
1920 */
1921 public static function get_active_modules() {
1922 $active = Jetpack_Options::get_option( 'active_modules' );
1923 if ( ! is_array( $active ) )
1924 $active = array();
1925 if ( is_admin() && ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) ) {
1926 $active[] = 'vaultpress';
1927 } else {
1928 $active = array_diff( $active, array( 'vaultpress' ) );
1929 }
1930
1931 //If protect is active on the main site of a multisite, it should be active on all sites.
1932 if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
1933 $active[] = 'protect';
1934 }
1935
1936 return array_unique( $active );
1937 }
1938
1939 /**
1940 * Check whether or not a Jetpack module is active.
1941 *
1942 * @param string $module The slug of a Jetpack module.
1943 * @return bool
1944 *
1945 * @static
1946 */
1947 public static function is_module_active( $module ) {
1948 return in_array( $module, self::get_active_modules() );
1949 }
1950
1951 public static function is_module( $module ) {
1952 return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
1953 }
1954
1955 /**
1956 * Catches PHP errors. Must be used in conjunction with output buffering.
1957 *
1958 * @param bool $catch True to start catching, False to stop.
1959 *
1960 * @static
1961 */
1962 public static function catch_errors( $catch ) {
1963 static $display_errors, $error_reporting;
1964
1965 if ( $catch ) {
1966 $display_errors = @ini_set( 'display_errors', 1 );
1967 $error_reporting = @error_reporting( E_ALL );
1968 add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
1969 } else {
1970 @ini_set( 'display_errors', $display_errors );
1971 @error_reporting( $error_reporting );
1972 remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
1973 }
1974 }
1975
1976 /**
1977 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
1978 */
1979 public static function catch_errors_on_shutdown() {
1980 Jetpack::state( 'php_errors', ob_get_clean() );
1981 }
1982
1983 public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array() ) {
1984 $jetpack = Jetpack::init();
1985
1986 $modules = Jetpack::get_default_modules( $min_version, $max_version );
1987 $modules = array_merge( $other_modules, $modules );
1988
1989 // Look for standalone plugins and disable if active.
1990
1991 $to_deactivate = array();
1992 foreach ( $modules as $module ) {
1993 if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
1994 $to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
1995 }
1996 }
1997
1998 $deactivated = array();
1999 foreach ( $to_deactivate as $module => $deactivate_me ) {
2000 list( $probable_file, $probable_title ) = $deactivate_me;
2001 if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2002 $deactivated[] = $module;
2003 }
2004 }
2005
2006 if ( $deactivated ) {
2007 Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2008
2009 $url = add_query_arg(
2010 array(
2011 'action' => 'activate_default_modules',
2012 '_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2013 ),
2014 add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2015 );
2016 wp_safe_redirect( $url );
2017 exit;
2018 }
2019
2020 do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2021
2022 // Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2023 Jetpack::restate();
2024 Jetpack::catch_errors( true );
2025
2026 $active = Jetpack::get_active_modules();
2027
2028 foreach ( $modules as $module ) {
2029 if ( did_action( "jetpack_module_loaded_$module" ) ) {
2030 $active[] = $module;
2031 Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2032 continue;
2033 }
2034
2035 if ( in_array( $module, $active ) ) {
2036 $module_info = Jetpack::get_module( $module );
2037 if ( ! $module_info['deactivate'] ) {
2038 $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2039 if ( $active_state = Jetpack::state( $state ) ) {
2040 $active_state = explode( ',', $active_state );
2041 } else {
2042 $active_state = array();
2043 }
2044 $active_state[] = $module;
2045 Jetpack::state( $state, implode( ',', $active_state ) );
2046 }
2047 continue;
2048 }
2049
2050 $file = Jetpack::get_module_path( $module );
2051 if ( ! file_exists( $file ) ) {
2052 continue;
2053 }
2054
2055 // we'll override this later if the plugin can be included without fatal error
2056 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2057 Jetpack::state( 'error', 'module_activation_failed' );
2058 Jetpack::state( 'module', $module );
2059 ob_start();
2060 require $file;
2061 do_action( 'jetpack_activate_module', $module );
2062 $active[] = $module;
2063 $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2064 if ( $active_state = Jetpack::state( $state ) ) {
2065 $active_state = explode( ',', $active_state );
2066 } else {
2067 $active_state = array();
2068 }
2069 $active_state[] = $module;
2070 Jetpack::state( $state, implode( ',', $active_state ) );
2071 Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2072 ob_end_clean();
2073 }
2074 Jetpack::state( 'error', false );
2075 Jetpack::state( 'module', false );
2076 Jetpack::catch_errors( false );
2077 do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2078 }
2079
2080 public static function activate_module( $module, $exit = true, $redirect = true ) {
2081 do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2082
2083 $jetpack = Jetpack::init();
2084
2085 if ( ! strlen( $module ) )
2086 return false;
2087
2088 if ( ! Jetpack::is_module( $module ) )
2089 return false;
2090
2091 // If it's already active, then don't do it again
2092 $active = Jetpack::get_active_modules();
2093 foreach ( $active as $act ) {
2094 if ( $act == $module )
2095 return true;
2096 }
2097
2098 $module_data = Jetpack::get_module( $module );
2099
2100 if ( ! Jetpack::is_active() ) {
2101 if ( !Jetpack::is_development_mode() )
2102 return false;
2103
2104 // If we're not connected but in development mode, make sure the module doesn't require a connection
2105 if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2106 return false;
2107 }
2108
2109 // Check and see if the old plugin is active
2110 if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2111 // Deactivate the old plugin
2112 if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2113 // If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2114 // We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2115 Jetpack::state( 'deactivated_plugins', $module );
2116 wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2117 exit;
2118 }
2119 }
2120
2121 // Check the file for fatal errors, a la wp-admin/plugins.php::activate
2122 Jetpack::state( 'module', $module );
2123 Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2124
2125 Jetpack::catch_errors( true );
2126 ob_start();
2127 require Jetpack::get_module_path( $module );
2128 do_action( 'jetpack_activate_module', $module );
2129 $active[] = $module;
2130 Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2131 Jetpack::state( 'error', false ); // the override
2132 Jetpack::state( 'message', 'module_activated' );
2133 Jetpack::state( 'module', $module );
2134 ob_end_clean();
2135 Jetpack::catch_errors( false );
2136
2137 // A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2138 if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2139 Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2140
2141 //Jump start is being dismissed send data to MC Stats
2142 $jetpack->stat( 'jumpstart', 'manual,'.$module );
2143
2144 $jetpack->do_stats( 'server_side' );
2145 }
2146
2147 if ( $redirect ) {
2148 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2149 }
2150 if ( $exit ) {
2151 exit;
2152 }
2153 }
2154
2155 function activate_module_actions( $module ) {
2156 do_action( "jetpack_activate_module_$module", $module );
2157
2158 $this->sync->sync_all_module_options( $module );
2159 }
2160
2161 public static function deactivate_module( $module ) {
2162 do_action( 'jetpack_pre_deactivate_module', $module );
2163
2164 $jetpack = Jetpack::init();
2165
2166 $active = Jetpack::get_active_modules();
2167 $new = array_filter( array_diff( $active, (array) $module ) );
2168
2169 do_action( "jetpack_deactivate_module_$module", $module );
2170
2171 // A flag for Jump Start so it's not shown again.
2172 if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2173 Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2174
2175 //Jump start is being dismissed send data to MC Stats
2176 $jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2177
2178 $jetpack->do_stats( 'server_side' );
2179 }
2180
2181 return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2182 }
2183
2184 public static function enable_module_configurable( $module ) {
2185 $module = Jetpack::get_module_slug( $module );
2186 add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2187 }
2188
2189 public static function module_configuration_url( $module ) {
2190 $module = Jetpack::get_module_slug( $module );
2191 return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2192 }
2193
2194 public static function module_configuration_load( $module, $method ) {
2195 $module = Jetpack::get_module_slug( $module );
2196 add_action( 'jetpack_module_configuration_load_' . $module, $method );
2197 }
2198
2199 public static function module_configuration_head( $module, $method ) {
2200 $module = Jetpack::get_module_slug( $module );
2201 add_action( 'jetpack_module_configuration_head_' . $module, $method );
2202 }
2203
2204 public static function module_configuration_screen( $module, $method ) {
2205 $module = Jetpack::get_module_slug( $module );
2206 add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2207 }
2208
2209 /* Installation */
2210
2211 public static function bail_on_activation( $message, $deactivate = true ) {
2212 ?>
2213 <!doctype html>
2214 <html>
2215 <head>
2216 <meta charset="<?php bloginfo( 'charset' ); ?>">
2217 <style>
2218 * {
2219 text-align: center;
2220 margin: 0;
2221 padding: 0;
2222 font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2223 }
2224 p {
2225 margin-top: 1em;
2226 font-size: 18px;
2227 }
2228 </style>
2229 <body>
2230 <p><?php echo esc_html( $message ); ?></p>
2231 </body>
2232 </html>
2233 <?php
2234 if ( $deactivate ) {
2235 $plugins = get_option( 'active_plugins' );
2236 $jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2237 $update = false;
2238 foreach ( $plugins as $i => $plugin ) {
2239 if ( $plugin === $jetpack ) {
2240 $plugins[$i] = false;
2241 $update = true;
2242 }
2243 }
2244
2245 if ( $update ) {
2246 update_option( 'active_plugins', array_filter( $plugins ) );
2247 }
2248 }
2249 exit;
2250 }
2251
2252 /**
2253 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2254 * @static
2255 */
2256 public static function plugin_activation( $network_wide ) {
2257 Jetpack_Options::update_option( 'activated', 1 );
2258
2259 if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2260 Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2261 }
2262
2263 if ( $network_wide )
2264 Jetpack::state( 'network_nag', true );
2265
2266 Jetpack::plugin_initialize();
2267 }
2268 /**
2269 * Runs before bumping version numbers up to a new version
2270 * @param (string) $version Version:timestamp
2271 * @param (string) $old_version Old Version:timestamp or false if not set yet.
2272 * @return null [description]
2273 */
2274 public static function do_version_bump( $version, $old_version ) {
2275
2276 if ( ! $old_version ) { // For new sites
2277 // Setting up jetpack manage
2278 Jetpack::activate_manage();
2279 }
2280 }
2281
2282 /**
2283 * Sets the internal version number and activation state.
2284 * @static
2285 */
2286 public static function plugin_initialize() {
2287 if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2288 Jetpack_Options::update_option( 'activated', 2 );
2289 }
2290
2291 if ( ! Jetpack_Options::get_option( 'version' ) ) {
2292 $version = $old_version = JETPACK__VERSION . ':' . time();
2293 do_action( 'updating_jetpack_version', $version, false );
2294 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2295 }
2296
2297 Jetpack::load_modules();
2298
2299 Jetpack_Options::delete_option( 'do_activate' );
2300 }
2301
2302 /**
2303 * Removes all connection options
2304 * @static
2305 */
2306 public static function plugin_deactivation( ) {
2307 require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2308 if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2309 Jetpack_Network::init()->deactivate();
2310 } else {
2311 Jetpack::disconnect( false );
2312 //Jetpack_Heartbeat::init()->deactivate();
2313 }
2314 }
2315
2316 /**
2317 * Disconnects from the Jetpack servers.
2318 * Forgets all connection details and tells the Jetpack servers to do the same.
2319 * @static
2320 */
2321 public static function disconnect( $update_activated_state = true ) {
2322 wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2323 Jetpack::clean_nonces( true );
2324
2325 Jetpack::load_xml_rpc_client();
2326 $xml = new Jetpack_IXR_Client();
2327 $xml->query( 'jetpack.deregister' );
2328
2329 Jetpack_Options::delete_option(
2330 array(
2331 'register',
2332 'blog_token',
2333 'user_token',
2334 'user_tokens',
2335 'master_user',
2336 'time_diff',
2337 'fallback_no_verify_ssl_certs',
2338 )
2339 );
2340
2341 if ( $update_activated_state ) {
2342 Jetpack_Options::update_option( 'activated', 4 );
2343 }
2344
2345 $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2346 // Check then record unique disconnection if site has never been disconnected previously
2347 if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2348 $jetpack_unique_connection['disconnected'] = 1;
2349 }
2350 else {
2351 if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2352 //track unique disconnect
2353 $jetpack = Jetpack::init();
2354
2355 $jetpack->stat( 'connections', 'unique-disconnect' );
2356 $jetpack->do_stats( 'server_side' );
2357 }
2358 // increment number of times disconnected
2359 $jetpack_unique_connection['disconnected'] += 1;
2360 }
2361
2362 Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2363
2364 // Disable the Heartbeat cron
2365 Jetpack_Heartbeat::init()->deactivate();
2366 }
2367
2368 /**
2369 * Unlinks the current user from the linked WordPress.com user
2370 */
2371 public static function unlink_user( $user_id = null ) {
2372 if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2373 return false;
2374
2375 $user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2376
2377 if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2378 return false;
2379
2380 if ( ! isset( $tokens[ $user_id ] ) )
2381 return false;
2382
2383 Jetpack::load_xml_rpc_client();
2384 $xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2385 $xml->query( 'jetpack.unlink_user', $user_id );
2386
2387 unset( $tokens[ $user_id ] );
2388
2389 Jetpack_Options::update_option( 'user_tokens', $tokens );
2390
2391 return true;
2392 }
2393
2394 /**
2395 * Attempts Jetpack registration. If it fail, a state flag is set: @see ::admin_page_load()
2396 */
2397 public static function try_registration() {
2398 // Let's get some testing in beta versions and such.
2399 if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2400 // Before attempting to connect, let's make sure that the domains are viable.
2401 $domains_to_check = array_unique( array(
2402 'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2403 'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2404 ) );
2405 foreach ( $domains_to_check as $domain ) {
2406 $result = Jetpack_Data::is_usable_domain( $domain );
2407 if ( is_wp_error( $result ) ) {
2408 return $result;
2409 }
2410 }
2411 }
2412
2413 $result = Jetpack::register();
2414
2415 // If there was an error with registration and the site was not registered, record this so we can show a message.
2416 if ( ! $result || is_wp_error( $result ) ) {
2417 return $result;
2418 } else {
2419 return true;
2420 }
2421 }
2422
2423 /**
2424 * Tracking an internal event log. Try not to put too much chaff in here.
2425 *
2426 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2427 */
2428 public static function log( $code, $data = null ) {
2429 $log = Jetpack_Options::get_option( 'log', array() );
2430
2431 // Append our event to the log
2432 $log_entry = array(
2433 'time' => time(),
2434 'user_id' => get_current_user_id(),
2435 'blog_id' => Jetpack_Options::get_option( 'id' ),
2436 'code' => $code,
2437 );
2438 // Don't bother storing it unless we've got some.
2439 if ( ! is_null( $data ) ) {
2440 $log_entry['data'] = $data;
2441 }
2442 $log[] = $log_entry;
2443
2444 // Try add_option first, to make sure it's not autoloaded.
2445 // @todo: Add an add_option method to Jetpack_Options
2446 if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2447 Jetpack_Options::update_option( 'log', $log );
2448 }
2449
2450 do_action( 'jetpack_log_entry', $log_entry );
2451 }
2452
2453 /**
2454 * Get the internal event log.
2455 */
2456 public static function get_log() {
2457 return Jetpack_Options::get_option( 'log', array() );
2458 }
2459
2460 /**
2461 * Log modification of important settings.
2462 */
2463 public static function log_settings_change( $option, $old_value, $value ) {
2464 switch( $option ) {
2465 case 'jetpack_sync_non_public_post_stati':
2466 self::log( $option, $value );
2467 break;
2468 }
2469 }
2470
2471 /* Admin Pages */
2472
2473 function admin_init() {
2474 // If the plugin is not connected, display a connect message.
2475 if (
2476 // the plugin was auto-activated and needs its candy
2477 Jetpack_Options::get_option( 'do_activate' )
2478 ||
2479 // the plugin is active, but was never activated. Probably came from a site-wide network activation
2480 ! Jetpack_Options::get_option( 'activated' )
2481 ) {
2482 Jetpack::plugin_initialize();
2483 }
2484
2485 if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2486 if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
2487 // Show connect notice on dashboard and plugins pages
2488 add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
2489 add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
2490 }
2491 } elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2492 // Upgrade: 1.1 -> 1.1.1
2493 // Check and see if host can verify the Jetpack servers' SSL certificate
2494 $args = array();
2495 Jetpack_Client::_wp_remote_request(
2496 Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2497 $args,
2498 true
2499 );
2500 } else {
2501 // Show the notice on the Dashboard only for now
2502
2503 add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2504 }
2505
2506 // If the plugin has just been disconnected from WP.com, show the survey notice
2507 if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
2508 add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
2509 }
2510
2511 // add_action( 'admin_notices', array( $this, 'alert_identity_crisis' ) );
2512
2513 if ( current_user_can( 'manage_options' ) && 'ALWAYS' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2514 add_action( 'admin_notices', array( $this, 'alert_required_ssl_fail' ) );
2515 }
2516
2517 add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2518 add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2519 add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2520
2521 if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2522 // Artificially throw errors in certain whitelisted cases during plugin activation
2523 add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2524
2525 // Kick off synchronization of user role when it changes
2526 add_action( 'set_user_role', array( $this, 'user_role_change' ) );
2527 }
2528 }
2529
2530 function admin_body_class( $admin_body_class = '' ) {
2531 $classes = explode( ' ', trim( $admin_body_class ) );
2532
2533 $classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2534
2535 $admin_body_class = implode( ' ', array_unique( $classes ) );
2536 return " $admin_body_class ";
2537 }
2538
2539 static function add_jetpack_pagestyles( $admin_body_class = '' ) {
2540 return $admin_body_class . ' jetpack-pagestyles ';
2541 }
2542
2543 function prepare_connect_notice() {
2544 add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2545
2546 add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
2547
2548 if ( Jetpack::state( 'network_nag' ) )
2549 add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
2550 }
2551 /**
2552 * Call this function if you want the Big Jetpack Manage Notice to show up.
2553 *
2554 * @return null
2555 */
2556 function prepare_manage_jetpack_notice() {
2557
2558 add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2559 add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
2560 }
2561
2562 /**
2563 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
2564 * This function artificially throws errors for such cases (whitelisted).
2565 *
2566 * @param string $plugin The activated plugin.
2567 */
2568 function throw_error_on_activate_plugin( $plugin ) {
2569 $active_modules = Jetpack::get_active_modules();
2570
2571 // The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
2572 if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
2573 $throw = false;
2574
2575 // Try and make sure it really was the stats plugin
2576 if ( ! class_exists( 'ReflectionFunction' ) ) {
2577 if ( 'stats.php' == basename( $plugin ) ) {
2578 $throw = true;
2579 }
2580 } else {
2581 $reflection = new ReflectionFunction( 'stats_get_api_key' );
2582 if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
2583 $throw = true;
2584 }
2585 }
2586
2587 if ( $throw ) {
2588 trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
2589 }
2590 }
2591 }
2592
2593 function intercept_plugin_error_scrape_init() {
2594 add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
2595 }
2596
2597 function intercept_plugin_error_scrape( $action, $result ) {
2598 if ( ! $result ) {
2599 return;
2600 }
2601
2602 foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
2603 if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
2604 Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
2605 }
2606 }
2607 }
2608
2609 function add_remote_request_handlers() {
2610 add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
2611 }
2612
2613 function remote_request_handlers() {
2614 switch ( current_filter() ) {
2615 case 'wp_ajax_nopriv_jetpack_upload_file' :
2616 $response = $this->upload_handler();
2617 break;
2618 default :
2619 $response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
2620 break;
2621 }
2622
2623 if ( ! $response ) {
2624 $response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
2625 }
2626
2627 if ( is_wp_error( $response ) ) {
2628 $status_code = $response->get_error_data();
2629 $error = $response->get_error_code();
2630 $error_description = $response->get_error_message();
2631
2632 if ( ! is_int( $status_code ) ) {
2633 $status_code = 400;
2634 }
2635
2636 status_header( $status_code );
2637 die( json_encode( (object) compact( 'error', 'error_description' ) ) );
2638 }
2639
2640 status_header( 200 );
2641 if ( true === $response ) {
2642 exit;
2643 }
2644
2645 die( json_encode( (object) $response ) );
2646 }
2647
2648 function upload_handler() {
2649 if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
2650 return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
2651 }
2652
2653 $user = wp_authenticate( '', '' );
2654 if ( ! $user || is_wp_error( $user ) ) {
2655 return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
2656 }
2657
2658 wp_set_current_user( $user->ID );
2659
2660 if ( ! current_user_can( 'upload_files' ) ) {
2661 return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
2662 }
2663
2664 if ( empty( $_FILES ) ) {
2665 return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
2666 }
2667
2668 foreach ( array_keys( $_FILES ) as $files_key ) {
2669 if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
2670 return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
2671 }
2672 }
2673
2674 $media_keys = array_keys( $_FILES['media'] );
2675
2676 $token = Jetpack_Data::get_access_token( get_current_user_id() );
2677 if ( ! $token || is_wp_error( $token ) ) {
2678 return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
2679 }
2680
2681 $uploaded_files = array();
2682 $global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
2683 unset( $GLOBALS['post'] );
2684 foreach ( $_FILES['media']['name'] as $index => $name ) {
2685 $file = array();
2686 foreach ( $media_keys as $media_key ) {
2687 $file[$media_key] = $_FILES['media'][$media_key][$index];
2688 }
2689
2690 list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
2691
2692 $hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
2693 if ( $hmac_provided !== $hmac_file ) {
2694 $uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
2695 continue;
2696 }
2697
2698 $_FILES['.jetpack.upload.'] = $file;
2699 $post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
2700 if ( ! current_user_can( 'edit_post', $post_id ) ) {
2701 $post_id = 0;
2702 }
2703 $attachment_id = media_handle_upload(
2704 '.jetpack.upload.',
2705 $post_id,
2706 array(),
2707 array(
2708 'action' => 'jetpack_upload_file',
2709 )
2710 );
2711
2712 if ( ! $attachment_id ) {
2713 $uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
2714 } elseif ( is_wp_error( $attachment_id ) ) {
2715 $uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
2716 } else {
2717 $attachment = get_post( $attachment_id );
2718 $uploaded_files[$index] = (object) array(
2719 'id' => (string) $attachment_id,
2720 'file' => $attachment->post_title,
2721 'url' => wp_get_attachment_url( $attachment_id ),
2722 'type' => $attachment->post_mime_type,
2723 'meta' => wp_get_attachment_metadata( $attachment_id ),
2724 );
2725 }
2726 }
2727 if ( ! is_null( $global_post ) ) {
2728 $GLOBALS['post'] = $global_post;
2729 }
2730
2731 return $uploaded_files;
2732 }
2733
2734 /**
2735 * Add help to the Jetpack page
2736 *
2737 * @since Jetpack (1.2.3)
2738 * @return false if not the Jetpack page
2739 */
2740 function admin_help() {
2741 $current_screen = get_current_screen();
2742
2743 // Overview
2744 $current_screen->add_help_tab(
2745 array(
2746 'id' => 'home',
2747 'title' => __( 'Home', 'jetpack' ),
2748 'content' =>
2749 '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
2750 '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
2751 '<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>',
2752 )
2753 );
2754
2755 // Screen Content
2756 if ( current_user_can( 'manage_options' ) ) {
2757 $current_screen->add_help_tab(
2758 array(
2759 'id' => 'settings',
2760 'title' => __( 'Settings', 'jetpack' ),
2761 'content' =>
2762 '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
2763 '<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
2764 '<ol>' .
2765 '<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
2766 '<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>' .
2767 '</ol>' .
2768 '<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>'
2769 )
2770 );
2771 }
2772
2773 // Help Sidebar
2774 $current_screen->set_help_sidebar(
2775 '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
2776 '<p><a href="http://jetpack.me/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
2777 '<p><a href="http://jetpack.me/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
2778 '<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
2779 );
2780 }
2781
2782 function admin_menu_css() {
2783 wp_enqueue_style( 'jetpack-icons' );
2784 }
2785
2786 function admin_menu_order() {
2787 return true;
2788 }
2789
2790 function jetpack_menu_order( $menu_order ) {
2791 $jp_menu_order = array();
2792
2793 foreach ( $menu_order as $index => $item ) {
2794 if ( $item != 'jetpack' ) {
2795 $jp_menu_order[] = $item;
2796 }
2797
2798 if ( $index == 0 ) {
2799 $jp_menu_order[] = 'jetpack';
2800 }
2801 }
2802
2803 return $jp_menu_order;
2804 }
2805
2806 function admin_head() {
2807 if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
2808 do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
2809 }
2810
2811 function admin_banner_styles() {
2812 $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
2813
2814 wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
2815 wp_style_add_data( 'jetpack', 'rtl', 'replace' );
2816 wp_style_add_data( 'jetpack', 'suffix', $min );
2817 }
2818
2819 function admin_scripts() {
2820 wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
2821 wp_localize_script(
2822 'jetpack-js',
2823 'jetpackL10n',
2824 array(
2825 'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
2826 'ays_unlink' => "This will prevent user-specific modules such as Publicize, Notifications and Post By Email from working.\nAre you sure you want to unlink?",
2827 'ays_dismiss' => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
2828 )
2829 );
2830 add_action( 'admin_footer', array( $this, 'do_stats' ) );
2831 }
2832
2833 function plugin_action_links( $actions ) {
2834
2835 $jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
2836
2837 if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
2838 return array_merge(
2839 $jetpack_home,
2840 array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
2841 array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
2842 $actions
2843 );
2844 }
2845
2846 return array_merge( $jetpack_home, $actions );
2847 }
2848
2849 function admin_connect_notice() {
2850 // Don't show the connect notice anywhere but the plugins.php after activating
2851 $current = get_current_screen();
2852 if ( 'plugins' !== $current->parent_base )
2853 return;
2854
2855 if ( ! current_user_can( 'jetpack_connect' ) )
2856 return;
2857
2858 $dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
2859 ?>
2860 <div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
2861 <a class="jp-banner__dismiss" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice and deactivate Jetpack.', 'jetpack' ); ?>"></a>
2862 <?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
2863 <div class="jp-banner__content is-connection">
2864 <h4><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h4>
2865 <p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
2866 </div>
2867 <div class="jp-banner__action-container is-connection">
2868 <a href="<?php echo $this->build_connect_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
2869 </div>
2870 <?php else : ?>
2871 <div class="jp-banner__content">
2872 <h4><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h4>
2873 <p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
2874 </div>
2875 <div class="jp-banner__action-container">
2876 <a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
2877 </div>
2878 <?php endif; ?>
2879 </div>
2880
2881 <?php
2882 }
2883
2884 /**
2885 * This is the first banner
2886 * It should be visible only to user that can update the option
2887 * Are not connected
2888 *
2889 * @return null
2890 */
2891 function admin_jetpack_manage_notice() {
2892 $screen = get_current_screen();
2893
2894 // Don't show the connect notice on the jetpack settings page.
2895 if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
2896 return;
2897
2898 // Only show it if don't have the managment option set.
2899 // And not dismissed it already.
2900 if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
2901 return;
2902 }
2903
2904 $opt_out_url = $this->opt_out_jetpack_manage_url();
2905 $opt_in_url = $this->opt_in_jetpack_manage_url();
2906 /**
2907 * I think it would be great to have different wordsing depending on where you are
2908 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
2909 * etc..
2910 */
2911
2912 ?>
2913 <div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
2914 <a class="jp-banner__dismiss" href="<?php echo esc_url( $opt_out_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice for now.', 'jetpack' ); ?>"></a>
2915 <div class="jp-banner__content">
2916 <h4><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h4>
2917 <p><?php printf( __( 'Manage multiple sites from one dashboard at wordpress.com/sites. Enabling allows all existing, connected Administrators to modify your site from WordPress.com. <a href="%s" target="_blank">Learn More</a>.', 'jetpack' ), 'http://jetpack.me/support/site-management' ); ?></p>
2918 </div>
2919 <div class="jp-banner__action-container is-opt-in">
2920 <a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
2921 </div>
2922 </div>
2923 <?php
2924 }
2925
2926 /**
2927 * Returns the url that the user clicks to remove the notice for the big banner
2928 * @return (string)
2929 */
2930 function opt_out_jetpack_manage_url() {
2931 $referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
2932 return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
2933 }
2934 /**
2935 * Returns the url that the user clicks to opt in to Jetpack Manage
2936 * @return (string)
2937 */
2938 function opt_in_jetpack_manage_url() {
2939 return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
2940 }
2941
2942 function opt_in_jetpack_manage_notice() {
2943 ?>
2944 <div class="wrap">
2945 <div id="message" class="jetpack-message is-opt-in">
2946 <?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'http://jetpack.me/support/site-management' ); ?>
2947 </div>
2948 </div>
2949 <?php
2950
2951 }
2952 /**
2953 * Determines whether to show the notice of not true = display notice
2954 * @return (bool)
2955 */
2956 function can_display_jetpack_manage_notice() {
2957 // never display the notice to users that can't do anything about it anyways
2958 if( ! current_user_can( 'jetpack_manage_modules' ) )
2959 return false;
2960
2961 // don't display if we are in development more
2962 if( Jetpack::is_development_mode() ) {
2963 return false;
2964 }
2965 // don't display if the site is private
2966 if( ! Jetpack_Options::get_option( 'public' ) )
2967 return false;
2968
2969 return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
2970 }
2971
2972 function network_connect_notice() {
2973 ?>
2974 <div id="message" class="updated jetpack-message">
2975 <div class="squeezer">
2976 <h4><?php _e( '<strong>Jetpack is activated!</strong> Each site on your network must be connected individually by an admin on that site.', 'jetpack' ) ?></h4>
2977 </div>
2978 </div>
2979 <?php
2980 }
2981
2982 public static function jetpack_comment_notice() {
2983 if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
2984 return '';
2985 }
2986
2987 $jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
2988 $jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
2989
2990 if ( $jetpack_old_version ) {
2991 if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
2992 return '';
2993 }
2994 }
2995
2996 if ( $jetpack_new_version ) {
2997 if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
2998 return '';
2999 }
3000 }
3001
3002 return '<br /><br />' . sprintf(
3003 __( 'Jetpack now includes Jetpack Comments, which enables your visitors to use their WordPress.com, Twitter, or Facebook accounts when commenting on your site. To activate Jetpack Comments, <a href="%s">%s</a>.', 'jetpack' ),
3004 wp_nonce_url(
3005 Jetpack::admin_url(
3006 array(
3007 'page' => 'jetpack',
3008 'action' => 'activate',
3009 'module' => 'comments',
3010 )
3011 ),
3012 'jetpack_activate-comments'
3013 ),
3014 __( 'click here', 'jetpack' )
3015 );
3016 }
3017
3018 /**
3019 * Show the survey link when the user has just disconnected Jetpack.
3020 */
3021 function disconnect_survey_notice() {
3022 ?>
3023 <div class="wrap">
3024 <div id="message" class="jetpack-message stay-visible">
3025 <div class="squeezer">
3026 <h4>
3027 <?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3028 <br />
3029 <?php echo sprintf(
3030 __( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3031 'https://jetpack.me/survey-disconnected/',
3032 '_blank'
3033 ); ?>
3034 </h4>
3035 </div>
3036 </div>
3037 </div>
3038 <?php
3039 }
3040
3041 /*
3042 * Registration flow:
3043 * 1 - ::admin_page_load() action=register
3044 * 2 - ::try_registration()
3045 * 3 - ::register()
3046 * - Creates jetpack_register option containing two secrets and a timestamp
3047 * - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3048 * siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3049 * - That request to jetpack.wordpress.com does not immediately respond. It first makes a request BACK to this site's
3050 * xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3051 * - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3052 * - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3053 * jetpack_id, jetpack_secret, jetpack_public
3054 * - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3055 * 4 - redirect to https://jetpack.wordpress.com/jetpack.authorize/1/
3056 * 5 - user logs in with WP.com account
3057 * 6 - redirect to this site's wp-admin/index.php?page=jetpack&action=authorize with
3058 * code <-- OAuth2 style authorization code
3059 * 7 - ::admin_page_load() action=authorize
3060 * 8 - Jetpack_Client_Server::authorize()
3061 * 9 - Jetpack_Client_Server::get_token()
3062 * 10- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3063 * client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3064 * 11- which responds with
3065 * access_token, token_type, scope
3066 * 12- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3067 * 13- Jetpack::activate_default_modules()
3068 * Deactivates deprecated plugins
3069 * Activates all default modules
3070 * Catches errors: redirects to wp-admin/index.php?page=jetpack state:error=something
3071 * 14- redirect to this site's wp-admin/index.php?page=jetpack with state:message=authorized
3072 * Done!
3073 */
3074
3075 /**
3076 * Handles the page load events for the Jetpack admin page
3077 */
3078 function admin_page_load() {
3079 $error = false;
3080
3081 // Make sure we have the right body class to hook stylings for subpages off of.
3082 add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3083
3084 if ( ! empty( $_GET['jetpack_restate'] ) ) {
3085 // Should only be used in intermediate redirects to preserve state across redirects
3086 Jetpack::restate();
3087 }
3088
3089 if ( isset( $_GET['connect_url_redirect'] ) ) {
3090 // User clicked in the iframe to link their accounts
3091 if ( ! Jetpack::is_user_connected() ) {
3092 $connect_url = $this->build_connect_url( true );
3093 if ( isset( $_GET['notes_iframe'] ) )
3094 $connect_url .= '&notes_iframe';
3095 wp_redirect( $connect_url );
3096 exit;
3097 } else {
3098 Jetpack::state( 'message', 'already_authorized' );
3099 wp_safe_redirect( Jetpack::admin_url() );
3100 exit;
3101 }
3102 }
3103
3104
3105 if ( isset( $_GET['action'] ) ) {
3106 switch ( $_GET['action'] ) {
3107 case 'authorize' :
3108 if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3109 Jetpack::state( 'message', 'already_authorized' );
3110 wp_safe_redirect( Jetpack::admin_url() );
3111 exit;
3112 }
3113 Jetpack::log( 'authorize' );
3114 $client_server = new Jetpack_Client_Server;
3115 $client_server->authorize();
3116 exit;
3117 case 'register' :
3118 if ( ! current_user_can( 'jetpack_connect' ) ) {
3119 $error = 'cheatin';
3120 break;
3121 }
3122 check_admin_referer( 'jetpack-register' );
3123 Jetpack::log( 'register' );
3124 Jetpack::maybe_set_version_option();
3125 $registered = Jetpack::try_registration();
3126 if ( is_wp_error( $registered ) ) {
3127 $error = $registered->get_error_code();
3128 Jetpack::state( 'error_description', $registered->get_error_message() );
3129 break;
3130 }
3131
3132 wp_redirect( $this->build_connect_url( true ) );
3133 exit;
3134 case 'activate' :
3135 if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3136 $error = 'cheatin';
3137 break;
3138 }
3139
3140 $module = stripslashes( $_GET['module'] );
3141 check_admin_referer( "jetpack_activate-$module" );
3142 Jetpack::log( 'activate', $module );
3143 Jetpack::activate_module( $module );
3144 // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3145 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3146 exit;
3147 case 'activate_default_modules' :
3148 check_admin_referer( 'activate_default_modules' );
3149 Jetpack::log( 'activate_default_modules' );
3150 Jetpack::restate();
3151 $min_version = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3152 $max_version = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3153 $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3154 Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3155 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3156 exit;
3157 case 'disconnect' :
3158 if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3159 $error = 'cheatin';
3160 break;
3161 }
3162
3163 check_admin_referer( 'jetpack-disconnect' );
3164 Jetpack::log( 'disconnect' );
3165 Jetpack::disconnect();
3166 wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3167 exit;
3168 case 'reconnect' :
3169 if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3170 $error = 'cheatin';
3171 break;
3172 }
3173
3174 check_admin_referer( 'jetpack-reconnect' );
3175 Jetpack::log( 'reconnect' );
3176 $this->disconnect();
3177 wp_redirect( $this->build_connect_url( true ) );
3178 exit;
3179 case 'deactivate' :
3180 if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3181 $error = 'cheatin';
3182 break;
3183 }
3184
3185 $modules = stripslashes( $_GET['module'] );
3186 check_admin_referer( "jetpack_deactivate-$modules" );
3187 foreach ( explode( ',', $modules ) as $module ) {
3188 Jetpack::log( 'deactivate', $module );
3189 Jetpack::deactivate_module( $module );
3190 Jetpack::state( 'message', 'module_deactivated' );
3191 }
3192 Jetpack::state( 'module', $modules );
3193 wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3194 exit;
3195 case 'unlink' :
3196 $redirect = isset( $_GET['redirect'] ) ? array( 'page' => $_GET['redirect'] ) : '';
3197 check_admin_referer( 'jetpack-unlink' );
3198 Jetpack::log( 'unlink' );
3199 $this->unlink_user();
3200 Jetpack::state( 'message', 'unlinked' );
3201 wp_safe_redirect( Jetpack::admin_url( $redirect ) );
3202 exit;
3203 default:
3204 do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3205 }
3206 }
3207
3208 if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3209 self::activate_new_modules( true );
3210 }
3211
3212 switch ( $error ) {
3213 case 'cheatin' :
3214 $this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
3215 break;
3216 case 'access_denied' :
3217 $this->error = __( 'You need to authorize the Jetpack connection between your site and WordPress.com to enable the awesome features.', 'jetpack' );
3218 break;
3219 case 'wrong_state' :
3220 $this->error = __( 'Don&#8217;t cross the streams! You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
3221 break;
3222 case 'invalid_client' :
3223 // @todo re-register instead of deactivate/reactivate
3224 $this->error = __( 'Return to sender. Whoops! It looks like you got the wrong Jetpack in the mail; deactivate then reactivate the Jetpack plugin to get a new one.', 'jetpack' );
3225 break;
3226 case 'invalid_grant' :
3227 $this->error = __( 'Wrong size. Hm&#8230; it seems your Jetpack doesn&#8217;t quite fit. Have you lost weight? Click &#8220;Connect to WordPress.com&#8221; again to get your Jetpack adjusted.', 'jetpack' );
3228 break;
3229 case 'site_inaccessible' :
3230 case 'site_requires_authorization' :
3231 $this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
3232 break;
3233 case 'module_activation_failed' :
3234 $module = Jetpack::state( 'module' );
3235 if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3236 $this->error = sprintf( __( '%s could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' ), $mod['name'] );
3237 if ( isset( $this->plugins_to_deactivate[$module] ) ) {
3238 $this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
3239 }
3240 } else {
3241 $this->error = __( 'Module could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' );
3242 }
3243 if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
3244 $this->error .= "<br />\n";
3245 $this->error .= $php_errors;
3246 }
3247 break;
3248 case 'master_user_required' :
3249 $module = Jetpack::state( 'module' );
3250 $module_name = '';
3251 if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3252 $module_name = $mod['name'];
3253 }
3254
3255 $master_user = Jetpack_Options::get_option( 'master_user' );
3256 $master_userdata = get_userdata( $master_user ) ;
3257 if ( $master_userdata ) {
3258 if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
3259 $this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
3260 } else {
3261 $this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
3262 }
3263 $this->error .= ' ' . sprintf( __( 'This module can only be altered by %s, the user who initiated the Jetpack connection on this site.' , 'jetpack' ), esc_html( $master_userdata->display_name ) );
3264
3265 } else {
3266 $this->error = sprintf( __( 'Only the user who initiated the Jetpack connection on this site can toggle %s, but that user no longer exists. This should not happen.', 'jetpack' ), $module_name );
3267 }
3268 break;
3269 case 'not_public' :
3270 $this->error = __( '<strong>Your Jetpack has a glitch.</strong> Connecting this site with WordPress.com is not possible. This usually means your site is not publicly accessible (localhost).', 'jetpack' );
3271 break;
3272 case 'wpcom_408' :
3273 case 'wpcom_5??' :
3274 case 'wpcom_bad_response' :
3275 case 'wpcom_outage' :
3276 $this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack. Please try again later.', 'jetpack' );
3277 break;
3278 case 'register_http_request_failed' :
3279 case 'token_http_request_failed' :
3280 $this->error = sprintf( __( 'Jetpack could not contact WordPress.com: %s. This usually means something is incorrectly configured on your web host.', 'jetpack' ), "<code>$error</code>" );
3281 break;
3282 default :
3283 if ( empty( $error ) ) {
3284 break;
3285 }
3286 $error = trim( substr( strip_tags( $error ), 0, 20 ) );
3287 // no break: fall through
3288 case 'no_role' :
3289 case 'no_cap' :
3290 case 'no_code' :
3291 case 'no_state' :
3292 case 'invalid_state' :
3293 case 'invalid_request' :
3294 case 'invalid_scope' :
3295 case 'unsupported_response_type' :
3296 case 'invalid_token' :
3297 case 'no_token' :
3298 case 'missing_secrets' :
3299 case 'home_missing' :
3300 case 'siteurl_missing' :
3301 case 'gmt_offset_missing' :
3302 case 'site_name_missing' :
3303 case 'secret_1_missing' :
3304 case 'secret_2_missing' :
3305 case 'site_lang_missing' :
3306 case 'home_malformed' :
3307 case 'siteurl_malformed' :
3308 case 'gmt_offset_malformed' :
3309 case 'timezone_string_malformed' :
3310 case 'site_name_malformed' :
3311 case 'secret_1_malformed' :
3312 case 'secret_2_malformed' :
3313 case 'site_lang_malformed' :
3314 case 'secrets_mismatch' :
3315 case 'verify_secret_1_missing' :
3316 case 'verify_secret_1_malformed' :
3317 case 'verify_secrets_missing' :
3318 case 'verify_secrets_mismatch' :
3319 $error = esc_html( $error );
3320 $this->error = sprintf( __( '<strong>Your Jetpack has a glitch.</strong> Something went wrong that&#8217;s never supposed to happen. Guess you&#8217;re just lucky: %s', 'jetpack' ), "<code>$error</code>" );
3321 if ( ! Jetpack::is_active() ) {
3322 $this->error .= '<br />';
3323 $this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
3324 }
3325 break;
3326 }
3327
3328 $message_code = Jetpack::state( 'message' );
3329
3330 $active_state = Jetpack::state( 'activated_modules' );
3331 if ( ! empty( $active_state ) ) {
3332 $available = Jetpack::get_available_modules();
3333 $active_state = explode( ',', $active_state );
3334 $active_state = array_intersect( $active_state, $available );
3335 if ( count( $active_state ) ) {
3336 foreach ( $active_state as $mod ) {
3337 $this->stat( 'module-activated', $mod );
3338 }
3339 } else {
3340 $active_state = false;
3341 }
3342 }
3343 if( Jetpack::state( 'optin-manage' ) ) {
3344 $activated_manage = $message_code;
3345 $message_code = 'jetpack-manage';
3346
3347 }
3348 switch ( $message_code ) {
3349 case 'modules_activated' :
3350 $this->message = sprintf(
3351 __( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
3352 JETPACK__VERSION
3353 );
3354
3355 if ( $active_state ) {
3356 $titles = array();
3357 foreach ( $active_state as $mod ) {
3358 if ( $mod_headers = Jetpack::get_module( $mod ) ) {
3359 $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
3360 }
3361 }
3362 if ( $titles ) {
3363 $this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
3364 }
3365 }
3366
3367 if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
3368 $titles = array();
3369 foreach ( explode( ',', $reactive_state ) as $mod ) {
3370 if ( $mod_headers = Jetpack::get_module( $mod ) ) {
3371 $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
3372 }
3373 }
3374 if ( $titles ) {
3375 $this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
3376 }
3377 }
3378
3379 $this->message .= Jetpack::jetpack_comment_notice();
3380 break;
3381 case 'jetpack-manage':
3382 $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>';
3383 if ( $activated_manage ) {
3384 $this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
3385 }
3386 break;
3387 case 'module_activated' :
3388 if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
3389 $this->message = sprintf( __( '<strong>%s Activated!</strong> You can deactivate at any time by clicking the Deactivate link next to each module.', 'jetpack' ), $module['name'] );
3390 $this->stat( 'module-activated', Jetpack::state( 'module' ) );
3391 }
3392 break;
3393
3394 case 'module_deactivated' :
3395 $modules = Jetpack::state( 'module' );
3396 if ( ! $modules ) {
3397 break;
3398 }
3399
3400 $module_names = array();
3401 foreach ( explode( ',', $modules ) as $module_slug ) {
3402 $module = Jetpack::get_module( $module_slug );
3403 if ( $module ) {
3404 $module_names[] = $module['name'];
3405 }
3406
3407 $this->stat( 'module-deactivated', $module_slug );
3408 }
3409
3410 if ( ! $module_names ) {
3411 break;
3412 }
3413
3414 $this->message = wp_sprintf(
3415 _nx(
3416 '<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
3417 '<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
3418 count( $module_names ),
3419 '%l = list of Jetpack module/feature names',
3420 'jetpack'
3421 ),
3422 $module_names
3423 );
3424 break;
3425
3426 case 'module_configured' :
3427 $this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
3428 break;
3429
3430 case 'already_authorized' :
3431 $this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
3432 break;
3433
3434 case 'authorized' :
3435 $this->message = __( '<strong>You&#8217;re fueled up and ready to go, Jetpack is now active.</strong> ', 'jetpack' );
3436 $this->message .= Jetpack::jetpack_comment_notice();
3437 break;
3438
3439 case 'linked' :
3440 $this->message = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
3441 $this->message .= Jetpack::jetpack_comment_notice();
3442 break;
3443
3444 case 'unlinked' :
3445 $user = wp_get_current_user();
3446 $this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
3447 break;
3448
3449 case 'switch_master' :
3450 global $current_user;
3451 $is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
3452 $master_userdata = get_userdata( Jetpack_Options::get_option( 'master_user' ) );
3453 if ( $is_master_user ) {
3454 $this->message = __( 'You have successfully set yourself as Jetpack’s primary user.', 'jetpack' );
3455 } else {
3456 $this->message = sprintf( _x( 'You have successfully set %s as Jetpack’s primary user.', '%s is a username', 'jetpack' ), $master_userdata->user_login );
3457 }
3458 break;
3459 }
3460
3461 $deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3462
3463 if ( ! empty( $deactivated_plugins ) ) {
3464 $deactivated_plugins = explode( ',', $deactivated_plugins );
3465 $deactivated_titles = array();
3466 foreach ( $deactivated_plugins as $deactivated_plugin ) {
3467 if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3468 continue;
3469 }
3470
3471 $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3472 }
3473
3474 if ( $deactivated_titles ) {
3475 if ( $this->message ) {
3476 $this->message .= "<br /><br />\n";
3477 }
3478
3479 $this->message .= wp_sprintf(
3480 _n(
3481 'Jetpack contains the most recent version of the old %l plugin.',
3482 'Jetpack contains the most recent versions of the old %l plugins.',
3483 count( $deactivated_titles ),
3484 'jetpack'
3485 ),
3486 $deactivated_titles
3487 );
3488
3489 $this->message .= "<br />\n";
3490
3491 $this->message .= _n(
3492 'The old version has been deactivated and can be removed from your site.',
3493 'The old versions have been deactivated and can be removed from your site.',
3494 count( $deactivated_titles ),
3495 'jetpack'
3496 );
3497 }
3498 }
3499
3500 $this->privacy_checks = Jetpack::state( 'privacy_checks' );
3501
3502 if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3503 add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3504 }
3505
3506 if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3507 do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3508 }
3509
3510 add_filter( 'jetpack_short_module_description', 'wptexturize' );
3511 }
3512
3513 function admin_notices() {
3514
3515 if ( $this->error ) {
3516 ?>
3517 <div id="message" class="jetpack-message jetpack-err">
3518 <div class="squeezer">
3519 <h4><?php echo wp_kses( $this->error, array( 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h4>
3520 <?php if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3521 <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3522 <?php endif; ?>
3523 </div>
3524 </div>
3525 <?php
3526 }
3527
3528 if ( $this->message ) {
3529 ?>
3530 <div id="message" class="jetpack-message">
3531 <div class="squeezer">
3532 <h4><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h4>
3533 </div>
3534 </div>
3535 <?php
3536 }
3537
3538 if ( $this->privacy_checks ) :
3539 $module_names = $module_slugs = array();
3540
3541 $privacy_checks = explode( ',', $this->privacy_checks );
3542 $privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3543 foreach ( $privacy_checks as $module_slug ) {
3544 $module = Jetpack::get_module( $module_slug );
3545 if ( ! $module ) {
3546 continue;
3547 }
3548
3549 $module_slugs[] = $module_slug;
3550 $module_names[] = "<strong>{$module['name']}</strong>";
3551 }
3552
3553 $module_slugs = join( ',', $module_slugs );
3554 ?>
3555 <div id="message" class="jetpack-message jetpack-err">
3556 <div class="squeezer">
3557 <h4><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h4><br />
3558 <p><?php
3559 echo wp_kses(
3560 wptexturize(
3561 wp_sprintf(
3562 _nx(
3563 "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3564 "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3565 count( $privacy_checks ),
3566 '%l = list of Jetpack module/feature names',
3567 'jetpack'
3568 ),
3569 $module_names
3570 )
3571 ),
3572 array( 'strong' => true )
3573 );
3574
3575 echo "\n<br />\n";
3576
3577 echo wp_kses(
3578 sprintf(
3579 _nx(
3580 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3581 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3582 count( $privacy_checks ),
3583 '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3584 'jetpack'
3585 ),
3586 wp_nonce_url(
3587 Jetpack::admin_url(
3588 array(
3589 'page' => 'jetpack',
3590 'action' => 'deactivate',
3591 'module' => urlencode( $module_slugs ),
3592 )
3593 ),
3594 "jetpack_deactivate-$module_slugs"
3595 ),
3596 esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3597 ),
3598 array( 'a' => array( 'href' => true, 'title' => true ) )
3599 );
3600 ?></p>
3601 </div>
3602 </div>
3603 <?php endif;
3604 // only display the notice if the other stuff is not there
3605 if( $this->can_display_jetpack_manage_notice() && ! $this->error && ! $this->message && ! $this->privacy_checks ) {
3606 if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3607 $this->opt_in_jetpack_manage_notice();
3608 }
3609 }
3610
3611 /**
3612 * Record a stat for later output. This will only currently output in the admin_footer.
3613 */
3614 function stat( $group, $detail ) {
3615 if ( ! isset( $this->stats[ $group ] ) )
3616 $this->stats[ $group ] = array();
3617 $this->stats[ $group ][] = $detail;
3618 }
3619
3620 /**
3621 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3622 */
3623 function do_stats( $method = '' ) {
3624 if ( is_array( $this->stats ) && count( $this->stats ) ) {
3625 foreach ( $this->stats as $group => $stats ) {
3626 if ( is_array( $stats ) && count( $stats ) ) {
3627 $args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3628 if ( 'server_side' === $method ) {
3629 self::do_server_side_stat( $args );
3630 } else {
3631 echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3632 }
3633 }
3634 unset( $this->stats[ $group ] );
3635 }
3636 }
3637 }
3638
3639 /**
3640 * Runs stats code for a one-off, server-side.
3641 *
3642 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3643 *
3644 * @return bool If it worked.
3645 */
3646 static function do_server_side_stat( $args ) {
3647 $response = wp_remote_get( self::build_stats_url( $args ) );
3648 if ( is_wp_error( $response ) )
3649 return false;
3650
3651 if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3652 return false;
3653
3654 return true;
3655 }
3656
3657 /**
3658 * Builds the stats url.
3659 *
3660 * @param $args array|string The arguments to append to the URL.
3661 *
3662 * @return string The URL to be pinged.
3663 */
3664 static function build_stats_url( $args ) {
3665 $defaults = array(
3666 'v' => 'wpcom2',
3667 'rand' => md5( mt_rand( 0, 999 ) . time() ),
3668 );
3669 $args = wp_parse_args( $args, $defaults );
3670 $base_url = apply_filters(
3671 'jetpack_stats_base_url',
3672 set_url_scheme( 'http://pixel.wp.com/g.gif' )
3673 );
3674 $url = add_query_arg( $args, $base_url );
3675 return $url;
3676 }
3677
3678 function translate_current_user_to_role() {
3679 foreach ( $this->capability_translations as $role => $cap ) {
3680 if ( current_user_can( $role ) || current_user_can( $cap ) ) {
3681 return $role;
3682 }
3683 }
3684
3685 return false;
3686 }
3687
3688 function translate_role_to_cap( $role ) {
3689 if ( ! isset( $this->capability_translations[$role] ) ) {
3690 return false;
3691 }
3692
3693 return $this->capability_translations[$role];
3694 }
3695
3696 function sign_role( $role ) {
3697 if ( ! $user_id = (int) get_current_user_id() ) {
3698 return false;
3699 }
3700
3701 $token = Jetpack_Data::get_access_token();
3702 if ( ! $token || is_wp_error( $token ) ) {
3703 return false;
3704 }
3705
3706 return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
3707 }
3708
3709 function build_connect_url( $raw = false, $redirect = false ) {
3710 if ( ! Jetpack_Options::get_option( 'blog_token' ) ) {
3711 $url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
3712 if( is_network_admin() ) {
3713 $url = add_query_arg( 'is_multisite', network_admin_url(
3714 'admin.php?page=jetpack-settings' ), $url );
3715 }
3716 } else {
3717 $role = $this->translate_current_user_to_role();
3718 $signed_role = $this->sign_role( $role );
3719
3720 $user = wp_get_current_user();
3721
3722 $redirect = $redirect ? esc_url_raw( $redirect ) : '';
3723
3724 if( isset( $_REQUEST['is_multisite'] ) ) {
3725 $redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
3726 }
3727
3728 $args = urlencode_deep(
3729 array(
3730 'response_type' => 'code',
3731 'client_id' => Jetpack_Options::get_option( 'id' ),
3732 'redirect_uri' => add_query_arg(
3733 array(
3734 'action' => 'authorize',
3735 '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3736 'redirect' => $redirect ? urlencode( $redirect ) : false,
3737 ),
3738 menu_page_url( 'jetpack', false )
3739 ),
3740 'state' => $user->ID,
3741 'scope' => $signed_role,
3742 'user_email' => $user->user_email,
3743 'user_login' => $user->user_login,
3744 'is_active' => Jetpack::is_active(),
3745 'jp_version' => JETPACK__VERSION,
3746 )
3747 );
3748
3749 $url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
3750 }
3751
3752 return $raw ? $url : esc_url( $url );
3753 }
3754
3755 function build_reconnect_url( $raw = false ) {
3756 $url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
3757 return $raw ? $url : esc_url( $url );
3758 }
3759
3760 public static function admin_url( $args = null ) {
3761 $args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
3762 $url = add_query_arg( $args, admin_url( 'admin.php' ) );
3763 return $url;
3764 }
3765
3766 public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
3767 $actionurl = str_replace( '&amp;', '&', $actionurl );
3768 return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
3769 }
3770
3771 function dismiss_jetpack_notice() {
3772
3773 if ( ! isset( $_GET['jetpack-notice'] ) ) {
3774 return;
3775 }
3776
3777 switch( $_GET['jetpack-notice'] ) {
3778 case 'dismiss':
3779 if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
3780
3781 require_once ABSPATH . 'wp-admin/includes/plugin.php';
3782 deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
3783 wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
3784 }
3785 break;
3786 case 'jetpack-manage-opt-out':
3787
3788 if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
3789 // Don't show the banner again
3790
3791 Jetpack_Options::update_option( 'dismissed_manage_banner', true );
3792 // redirect back to the page that had the notice
3793 if ( wp_get_referer() ) {
3794 wp_safe_redirect( wp_get_referer() );
3795 } else {
3796 // Take me to Jetpack
3797 wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3798 }
3799 }
3800 break;
3801 case 'jetpack-protect-multisite-opt-out':
3802
3803 if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
3804 // Don't show the banner again
3805
3806 update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
3807 // redirect back to the page that had the notice
3808 if ( wp_get_referer() ) {
3809 wp_safe_redirect( wp_get_referer() );
3810 } else {
3811 // Take me to Jetpack
3812 wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3813 }
3814 }
3815 break;
3816 case 'jetpack-manage-opt-in':
3817 if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
3818 // This makes sure that we are redirect to jetpack home so that we can see the Success Message.
3819
3820 $redirection_url = Jetpack::admin_url();
3821 remove_action( 'jetpack_pre_activate_module', array( Jetpack_Admin::init(), 'fix_redirect' ) );
3822
3823 // Don't redirect form the Jetpack Setting Page
3824 $referer_parsed = parse_url ( wp_get_referer() );
3825 // check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
3826 if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
3827 // Take the user to Jetpack home except when on the setting page
3828 $redirection_url = wp_get_referer();
3829 add_action( 'jetpack_pre_activate_module', array( Jetpack_Admin::init(), 'fix_redirect' ) );
3830 }
3831 // Also update the JSON API FULL MANAGEMENT Option
3832 Jetpack::activate_module( 'manage', false, false );
3833
3834 // Special Message when option in.
3835 Jetpack::state( 'optin-manage', 'true' );
3836 // Activate the Module if not activated already
3837
3838 // Redirect properly
3839 wp_safe_redirect( $redirection_url );
3840
3841 }
3842 break;
3843 }
3844 }
3845
3846 /**
3847 * This is the old pre-3.0 admin page. It is replaced by the Jetpack_Admin class.
3848 * Tentatively left here for comparison purposes.
3849 */
3850 function admin_page() {
3851 global $current_user;
3852
3853 $is_connected = Jetpack::is_active();
3854 $user_token = Jetpack_Data::get_access_token( $current_user->ID );
3855 $is_user_connected = $user_token && ! is_wp_error( $user_token );
3856 $is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
3857
3858 $can_reconnect_jpms = true;
3859 if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3860 $jpms = Jetpack_Network::init();
3861 $can_reconnect_jpms = ( $jpms->get_option( 'sub-site-connection-override' ) ) ? 1: 0;
3862 }
3863
3864
3865
3866 ?>
3867 <div class="wrap" id="jetpack-settings">
3868
3869 <div id="jp-header"<?php if ( $is_connected ) : ?> class="small"<?php endif; ?>>
3870 <div id="jp-clouds">
3871 <?php if ( $is_connected && $can_reconnect_jpms ) : ?>
3872 <div id="jp-disconnectors">
3873 <?php if ( current_user_can( 'jetpack_disconnect' ) ) : ?>
3874 <div id="jp-disconnect" class="jp-disconnect">
3875 <a href="<?php echo wp_nonce_url( Jetpack::admin_url( 'action=disconnect' ), 'jetpack-disconnect' ); ?>" onclick="return confirm('<?php echo htmlspecialchars( __('Are you sure you want to disconnect from WordPress.com?', 'jetpack'), ENT_QUOTES ); ?>');"><div class="deftext"><?php _e( 'Connected to WordPress.com', 'jetpack' ); ?></div><div class="hovertext"><?php _e( 'Disconnect from WordPress.com', 'jetpack' ) ?></div></a>
3876 </div>
3877 <?php endif; ?>
3878 <?php if ( $is_user_connected && ! $is_master_user ) : ?>
3879 <div id="jp-unlink" class="jp-disconnect">
3880 <a href="<?php echo wp_nonce_url( Jetpack::admin_url( 'action=unlink' ), 'jetpack-unlink' ); ?>"><div class="deftext"><?php _e( 'User linked to WordPress.com', 'jetpack' ); ?></div><div class="hovertext"><?php _e( 'Unlink user from WordPress.com', 'jetpack' ) ?></div></a>
3881 </div>
3882 <?php endif; ?>
3883 </div>
3884 <?php endif; ?>
3885 <h3><?php _e( 'Jetpack by WordPress.com', 'jetpack' ) ?></h3>
3886 <?php if ( ! $is_connected ) : ?>
3887 <div id="jp-notice">
3888 <p><?php _e( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ); ?></p>
3889 </div>
3890 <?php endif; ?>
3891 </div>
3892 </div>
3893
3894 <h2 style="display: none"></h2> <!-- For WP JS message relocation -->
3895
3896 <?php Jetpack::init()->load_view( 'admin/network-activated-notice.php' ); ?>
3897
3898 <?php do_action( 'jetpack_notices' ) ?>
3899
3900 <?php
3901 // If the connection has not been made then show the marketing text.
3902 if( !$can_reconnect_jpms && !$is_connected ) {
3903 ?>
3904 <div id="message" class="updated jetpack-message jp-banner jp-multisite" style="display:block !important">
3905 <div class="jp-banner__content">
3906 <h4><?php _e( 'To use Jetpack please contact your WordPress administrator to connect it for you.', 'jetpack' ) ?></h4>
3907 </div>
3908 </div> <?php
3909 }
3910 if ( ! Jetpack::is_development_mode() && $can_reconnect_jpms ) :
3911 ?>
3912 <?php if ( ! $is_connected ) :
3913 $dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3914 ?>
3915 <div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3916 <a class="jp-banner__dismiss" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>"></a>
3917 <div class="jp-banner__content">
3918 <h4><?php _e( 'To enable all of the Jetpack features, you&#8217;ll need to connect your website to WordPress.com.', 'jetpack' ) ?></h4>
3919 <p><?php _e( 'Once you&#8217;ve made the connection you&#8217;ll activate all the delightful features below.', 'jetpack' ) ?></p>
3920 </div>
3921 <div class="jp-banner__action-container">
3922 <a href="<?php echo $this->build_connect_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect', 'jetpack' ); ?></a>
3923 </div>
3924 </div>
3925
3926 <?php else /* blog and user are connected */ : ?>
3927 <?php /* TODO: if not master user, show user disconnect button? */ ?>
3928 <?php endif; ?>
3929 <?php endif; // ! Jetpack::is_development_mode() ?>
3930
3931
3932
3933
3934
3935 <?php if ( Jetpack::is_active() && !Jetpack::is_development_mode() && ! $is_user_connected ) : ?>
3936
3937 <div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3938 <div class="jp-banner__content">
3939 <h4><?php _e( 'To enable all of the Jetpack features you&#8217;ll need to link your account here to your WordPress.com account.', 'jetpack' ) ?></h4>
3940 </div>
3941 <div class="jp-banner__action-container is-full-width">
3942 <a href="<?php echo $this->build_connect_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Link account with WordPress.com', 'jetpack' ); ?></a>
3943 </div>
3944 </div>
3945
3946 <?php endif; ?>
3947
3948
3949
3950
3951 <?php
3952 if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3953 $this->admin_screen_configure_module( $_GET['configure'] );
3954 } else {
3955 $this->admin_screen_list_modules();
3956 }
3957 ?>
3958
3959 <div id="survey" class="jp-survey">
3960 <div class="jp-survey-container">
3961 <div class="jp-survey-text">
3962 <h4><?php _e( 'Have feedback on Jetpack?', 'jetpack' ); ?></h4>
3963 <br />
3964 <?php _e( 'Answer a short survey to let us know how we&#8217;re doing and what to add in the future.', 'jetpack' ); ?>
3965 </div>
3966 <div class="jp-survey-button-container">
3967 <p class="submit"><?php printf( '<a id="jp-survey-button" class="button-primary" target="_blank" href="%1$s">%2$s</a>', 'http://jetpack.me/survey/?rel=' . JETPACK__VERSION, __( 'Take Survey', 'jetpack' ) ); ?></p>
3968 </div>
3969 </div>
3970 </div>
3971
3972 <?php if ( $is_connected && $this->current_user_is_connection_owner() ) : ?>
3973 <p id="news-sub"><?php _e( 'Checking email updates status&hellip;', 'jetpack' ); ?></p>
3974 <script type="text/javascript">
3975 jQuery(document).ready(function($){
3976 $.get( ajaxurl, { action: 'jetpack-check-news-subscription', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
3977 if ( 'subscribed' == data ) {
3978 $( '#news-sub' ).html( '<?php printf(
3979 esc_js( _x( 'You are currently subscribed to email updates. %s', '%s = Unsubscribe link', 'jetpack' ) ),
3980 '<a href="#" class="jp-news-link button">' . esc_js( __( 'Unsubscribe', 'jetpack' ) ) . '</a>'
3981 ); ?>' );
3982 } else {
3983 $( '#news-sub' ).html( '<?php printf(
3984 esc_js( _x( 'Want to receive updates about Jetpack by email? %s', '%s = Subscribe link', 'jetpack' ) ),
3985 '<a href="#" class="jp-news-link button-primary">' . esc_js( __( 'Subscribe', 'jetpack' ) ) . '</a>'
3986 ); ?>' );
3987 }
3988 $( '.jp-news-link' ).click( function() {
3989 $( '#news-sub' ).append( ' <img src="<?php echo esc_js( esc_url( admin_url( 'images/loading.gif' ) ) ); ?>" align="absmiddle" id="jp-news-loading" />' );
3990 $.get( ajaxurl, { action: 'jetpack-subscribe-to-news', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
3991 if ( 'subscribed' == data ) {
3992 $( '#news-sub' ).text( '<?php echo esc_js( __( 'You have been subscribed to receive email updates.', 'jetpack' ) ); ?>' );
3993 } else {
3994 $( '#news-sub' ).text( '<?php echo esc_js( __( 'You will no longer receive email updates about Jetpack.', 'jetpack' ) ); ?>' );
3995 }
3996 $( '#jp-news-loading' ).remove();
3997 } );
3998 return false;
3999 } );
4000 } );
4001 } );
4002 </script>
4003 <?php endif; ?>
4004
4005 <div id="jp-footer">
4006 <p class="automattic"><?php _e( 'An <span>Automattic</span> Airline', 'jetpack' ) ?></p>
4007 <p class="small">
4008 <a href="http://jetpack.me/" target="_blank">Jetpack <?php echo esc_html( JETPACK__VERSION ); ?></a> |
4009 <a href="http://automattic.com/privacy/" target="_blank"><?php _e( 'Privacy Policy', 'jetpack' ); ?></a> |
4010 <a href="http://wordpress.com/tos/" target="_blank"><?php _e( 'Terms of Service', 'jetpack' ); ?></a> |
4011 <?php if ( current_user_can( 'manage_options' ) ) : ?>
4012 <a href="<?php echo Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ); ?>"><?php _e( 'Debug', 'jetpack' ); ?></a> |
4013 <?php endif; ?>
4014 <a href="http://jetpack.me/support/" target="_blank"><?php _e( 'Support', 'jetpack' ); ?></a>
4015 </p>
4016 </div>
4017
4018 <div id="jetpack-configuration" style="display:none;">
4019 <p><img width="16" src="<?php echo esc_url( plugins_url( 'images/wpspin_light-2x.gif', JETPACK__PLUGIN_FILE) ); ?>" alt="Loading ..." /></p>
4020 </div>
4021 </div>
4022 <?php
4023 }
4024
4025 function debugger_page() {
4026 nocache_headers();
4027 if ( ! current_user_can( 'manage_options' ) ) {
4028 die( '-1' );
4029 }
4030 Jetpack_Debugger::jetpack_debug_display_handler();
4031 exit;
4032 }
4033
4034 public static function admin_screen_configure_module( $module_id ) {
4035
4036 // User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4037 if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4038 self::display_activate_module_link( $module_id );
4039 return false;
4040 } ?>
4041
4042 <div id="jp-settings-screen" style="position: relative">
4043 <h3>
4044 <?php
4045 $module = Jetpack::get_module( $module_id );
4046 echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4047 printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4048 ?>
4049 </h3>
4050 <?php do_action( 'jetpack_notices_update_settings', $module_id ); ?>
4051 <?php do_action( 'jetpack_module_configuration_screen_' . $module_id ); ?>
4052 </div><?php
4053 }
4054
4055 /**
4056 * Display link to activate the module to see the settings screen.
4057 * @param string $module_id
4058 * @return null
4059 */
4060 public static function display_activate_module_link( $module_id ) {
4061
4062 $info = Jetpack::get_module( $module_id );
4063 $extra = '';
4064 $activate_url = wp_nonce_url(
4065 Jetpack::admin_url(
4066 array(
4067 'page' => 'jetpack',
4068 'action' => 'activate',
4069 'module' => $module_id,
4070 )
4071 ),
4072 "jetpack_activate-$module_id"
4073 );
4074
4075 ?>
4076
4077 <div class="wrap configure-module">
4078 <div id="jp-settings-screen">
4079 <?php
4080 if ( $module_id == 'json-api' ) {
4081
4082 $info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4083
4084 $activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4085
4086 $info['description'] = sprintf( __( 'Manage your multiple Jetpack sites from our centralized dashboard at wordpress.com/sites. <a href="%s" target="_blank">Learn more</a>.', 'jetpack' ), 'http://jetpack.me/support/site-management' );
4087
4088 // $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4089 } ?>
4090
4091 <h3><?php echo esc_html( $info['name'] ); ?></h3>
4092 <div class="narrow">
4093 <p><?php echo $info['description']; ?></p>
4094 <?php if( $extra ) { ?>
4095 <p><?php echo esc_html( $extra ); ?></p>
4096 <?php } ?>
4097 <p>
4098 <?php
4099 if( wp_get_referer() ) {
4100 printf( __( '<a class="button-primary" href="%s">Activate Now</a> or <a href="%s" >return to previous page</a>.', 'jetpack' ) , $activate_url, wp_get_referer() );
4101 } else {
4102 printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url );
4103 } ?>
4104 </p>
4105 </div>
4106
4107 </div>
4108 </div>
4109
4110 <?php
4111 }
4112
4113 public static function sort_modules( $a, $b ) {
4114 if ( $a['sort'] == $b['sort'] )
4115 return 0;
4116
4117 return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4118 }
4119
4120 function admin_screen_list_modules() {
4121 require_once JETPACK__PLUGIN_DIR . 'modules/module-info.php';
4122 $jetpack_connected = true;
4123 if ( ! Jetpack::is_active() )
4124 $jetpack_connected = false;
4125
4126 ?>
4127 <div class="module-container">
4128 <?php
4129
4130 $avail_raw = Jetpack::get_available_modules();
4131 $available = array();
4132 $active = Jetpack::get_active_modules();
4133 $counter = 0;
4134
4135 foreach ( (array) $avail_raw as $module ) {
4136 if ( $plugin = Jetpack::get_module( $module ) ) {
4137 $plugin['module'] = $module;
4138 $available[] = $plugin;
4139 }
4140 }
4141 unset( $avail_raw );
4142 usort( $available, array( 'Jetpack', 'sort_modules' ) );
4143 $jetpack_version = Jetpack_Options::get_option( 'version' );
4144 if ( $jetpack_version ) {
4145 list( $jetpack_version, $jetpack_version_time ) = explode( ':', $jetpack_version );
4146 } else {
4147 $jetpack_version = 0;
4148 $jetpack_version_time = 0;
4149 }
4150
4151 $jetpack_old_version = Jetpack_Options::get_option( 'old_version' );
4152 if ( $jetpack_old_version ) {
4153 list( $jetpack_old_version ) = explode( ':', $jetpack_old_version );
4154 } else {
4155 $jetpack_old_version = 0;
4156 }
4157 $now = time();
4158
4159 foreach ( (array) $available as $module_data ) {
4160 $module = $module_data['module'];
4161 $activated = in_array( $module, $active );
4162 if ( $activated ) {
4163 $css = 'active';
4164 $toggle = __( 'Deactivate', 'jetpack' );
4165 $toggle_url = wp_nonce_url(
4166 Jetpack::admin_url(
4167 array(
4168 'page' => 'jetpack',
4169 'action' => 'deactivate',
4170 'module' => $module,
4171 )
4172 ),
4173 "jetpack_deactivate-$module"
4174 );
4175 } else {
4176 $css = 'inactive';
4177 $toggle = __( 'Activate', 'jetpack' );
4178 $toggle_url = wp_nonce_url(
4179 Jetpack::admin_url(
4180 array(
4181 'page' => 'jetpack',
4182 'action' => 'activate',
4183 'module' => $module,
4184 )
4185 ),
4186 "jetpack_activate-$module"
4187 );
4188 }
4189
4190 if ( $counter % 4 == 0 ) {
4191 $classes = $css . ' jetpack-newline';
4192 $counter = 0;
4193 } else {
4194 $classes = $css;
4195 }
4196
4197 $free_text = esc_html( $module_data['free'] ? __( 'Free', 'jetpack' ) : __( 'Purchase', 'jetpack' ) );
4198 $free_text = apply_filters( 'jetpack_module_free_text_' . $module, $free_text );
4199 $badge_text = $free_text;
4200
4201 if ( ( ! $jetpack_connected && ! Jetpack::is_development_mode() ) ) {
4202 $classes = 'x disabled';
4203 } elseif ( $jetpack_version_time + 604800 > $now ) { // 1 week
4204 if ( version_compare( $module_data['introduced'], $jetpack_old_version, '>' ) ) {
4205 $badge_text = esc_html__( 'New', 'jetpack' );
4206 $classes .= ' jetpack-new-module';
4207 } elseif ( isset( $module_data['changed'] ) && version_compare( $module_data['changed'], $jetpack_old_version, '>' ) ) {
4208 $badge_text = esc_html__( 'Updated', 'jetpack' );
4209 $classes .= ' jetpack-updated-module';
4210 } else {
4211 $badge_text = $free_text;
4212 }
4213 }
4214
4215 ?>
4216 <div class="jetpack-module jetpack-<?php echo $classes; ?>" id="<?php echo $module ?>">
4217 <h3><?php echo esc_html( $module_data['name'] ); ?></h3>
4218 <div class="jetpack-module-description">
4219 <div class="module-image">
4220 <p><span class="module-image-badge"><?php echo $badge_text; ?></span><span class="module-image-free" style="display: none"><?php echo $free_text; ?></span></p>
4221 </div>
4222
4223 <p><?php echo apply_filters( 'jetpack_short_module_description', $module_data['description'], $module ); ?></p>
4224 </div>
4225
4226 <div class="jetpack-module-actions">
4227 <?php if ( $jetpack_connected || ( Jetpack::is_development_mode() && ! $module_data['requires_connection'] ) ) : ?>
4228 <?php if ( ! $activated && current_user_can( 'manage_options' ) && apply_filters( 'jetpack_can_activate_' . $module, true ) ) : ?>
4229 <a href="<?php echo esc_url( $toggle_url ); ?>" class="<?php echo ( 'inactive' == $css ? ' button-primary' : ' button-secondary' ); ?>"><?php echo $toggle; ?></a>&nbsp;
4230 <?php endif; ?>
4231
4232 <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
4233
4234 <?php
4235 if ( current_user_can( 'manage_options' ) && apply_filters( 'jetpack_module_configurable_' . $module, false ) ) {
4236 echo '<a href="' . esc_url( Jetpack::module_configuration_url( $module ) ) . '" class="jetpack-configure-button button-secondary">' . __( 'Configure', 'jetpack' ) . '</a>';
4237 }
4238 ?><?php if ( $activated && $module_data['deactivate'] && current_user_can( 'manage_options' ) ) : ?><a style="display: none;" href="<?php echo esc_url( $toggle_url ); ?>" class="jetpack-deactivate-button button-secondary"><?php echo $toggle; ?></a>&nbsp;<?php endif; ?>
4239
4240 <?php else : ?>
4241 <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
4242 <?php endif; ?>
4243 </div>
4244 </div>
4245 <?php if ( 'inactive' == $css && $jetpack_connected && current_user_can( 'manage_options' ) && apply_filters( 'jetpack_can_activate_' . $module, true ) ) : ?>
4246 <script type="text/javascript">
4247 jQuery( '#<?php echo esc_js( $module ); ?>' ).bind( 'click', function(e){
4248 if ( ! jQuery(e.target).hasClass('more-info-link') )
4249 document.location.href = '<?php echo str_replace( '&amp;', '&', esc_js( esc_url( $toggle_url ) ) ); ?>';
4250 } );
4251 </script>
4252 <?php else : ?>
4253 <style>
4254 #<?php echo $module; ?> { cursor: default; }
4255 </style>
4256 <?php endif; ?>
4257
4258 <div id="jp-more-info-<?php echo esc_attr( $module ); ?>" style="display:none;">
4259 <?php
4260 if ( $jetpack_connected && has_action( 'jetpack_module_more_info_connected_' . $module ) )
4261 do_action( 'jetpack_module_more_info_connected_' . $module );
4262 else
4263 do_action( 'jetpack_module_more_info_' . $module );
4264 ?>
4265 </div>
4266
4267 <?php
4268 $counter++;
4269 }
4270
4271 // Add in some "Coming soon..." placeholders to fill up the current row and one more
4272 for ( $i = 0; $i < 4; $i++ ) { ?>
4273 <div class="jetpack-module placeholder"<?php if ( $i > 8 - $counter ) echo ' style="display: none;"'; ?>>
4274 <h3><?php _e( 'Coming soon&#8230;', 'jetpack' ) ?></h3>
4275 </div>
4276 <?php
4277 }
4278
4279 echo '</div><!-- .module-container -->';
4280 }
4281
4282 function check_news_subscription() {
4283 if ( ! $this->current_user_is_connection_owner() ) {
4284 exit;
4285 }
4286
4287 Jetpack::load_xml_rpc_client();
4288 $xml = new Jetpack_IXR_Client(
4289 array(
4290 'user_id' => JETPACK_MASTER_USER,
4291 )
4292 );
4293 $xml->query( 'jetpack.checkNewsSubscription' );
4294 if ( $xml->isError() ) {
4295 printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
4296 } else {
4297 print_r( $xml->getResponse() );
4298 }
4299 exit;
4300 }
4301
4302 function subscribe_to_news() {
4303 if ( ! $this->current_user_is_connection_owner() ) {
4304 exit;
4305 }
4306
4307 Jetpack::load_xml_rpc_client();
4308 $xml = new Jetpack_IXR_Client(
4309 array(
4310 'user_id' => JETPACK_MASTER_USER,
4311 )
4312 );
4313 $xml->query( 'jetpack.subscribeToNews' );
4314 if ( $xml->isError() ) {
4315 printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
4316 } else {
4317 print_r( $xml->getResponse() );
4318 }
4319 exit;
4320 }
4321
4322 function sync_reindex_trigger() {
4323 if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4324 echo json_encode( $this->sync->reindex_trigger() );
4325 } else {
4326 echo '{"status":"ERROR"}';
4327 }
4328 exit;
4329 }
4330
4331 function sync_reindex_status(){
4332 if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4333 echo json_encode( $this->sync->reindex_status() );
4334 } else {
4335 echo '{"status":"ERROR"}';
4336 }
4337 exit;
4338 }
4339
4340 /* Client API */
4341
4342 /**
4343 * Returns the requested Jetpack API URL
4344 *
4345 * @return string
4346 */
4347 public static function api_url( $relative_url ) {
4348 return trailingslashit( JETPACK__API_BASE . $relative_url ) . JETPACK__API_VERSION . '/';
4349 }
4350
4351 /**
4352 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4353 */
4354 public static function fix_url_for_bad_hosts( $url ) {
4355 if ( 0 !== strpos( $url, 'https://' ) ) {
4356 return $url;
4357 }
4358
4359 switch ( JETPACK_CLIENT__HTTPS ) {
4360 case 'ALWAYS' :
4361 return $url;
4362 case 'NEVER' :
4363 return set_url_scheme( $url, 'http' );
4364 // default : case 'AUTO' :
4365 }
4366
4367 // Yay! Your host is good!
4368 if ( self::permit_ssl() && wp_http_supports( array( 'ssl' => true ) ) ) {
4369 return $url;
4370 }
4371
4372 // Boo! Your host is bad and makes Jetpack cry!
4373 return set_url_scheme( $url, 'http' );
4374 }
4375
4376 /**
4377 * Checks to see if the URL is using SSL to connect with Jetpack
4378 *
4379 * @since 2.3.3
4380 * @return boolean
4381 */
4382 public static function permit_ssl( $force_recheck = false ) {
4383 // Do some fancy tests to see if ssl is being supported
4384 if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4385 if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4386 $ssl = 0;
4387 } else {
4388 switch ( JETPACK_CLIENT__HTTPS ) {
4389 case 'NEVER':
4390 $ssl = 0;
4391 break;
4392 case 'ALWAYS':
4393 case 'AUTO':
4394 default:
4395 $ssl = 1;
4396 break;
4397 }
4398
4399 // If it's not 'NEVER', test to see
4400 if ( $ssl ) {
4401 $response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4402 if ( is_wp_error( $response ) || ( 'OK' !== wp_remote_retrieve_body( $response ) ) ) {
4403 $ssl = 0;
4404 }
4405 }
4406 }
4407 set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4408 }
4409
4410 return (bool) $ssl;
4411 }
4412
4413 /*
4414 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'ALWAYS' but SSL isn't working.
4415 */
4416 public function alert_required_ssl_fail() {
4417 if ( ! current_user_can( 'manage_options' ) )
4418 return;
4419 ?>
4420
4421 <div id="message" class="error jetpack-message jp-identity-crisis">
4422 <div class="jp-banner__content">
4423 <h4><?php _e( 'Something is being cranky!', 'jetpack' ); ?></h4>
4424 <p><?php _e( 'Your site is configured to only permit SSL connections to Jetpack, but SSL connections don\'t seem to be functional!', 'jetpack' ); ?></p>
4425 </div>
4426 </div>
4427
4428 <?php
4429 }
4430
4431 /**
4432 * Returns the Jetpack XML-RPC API
4433 *
4434 * @return string
4435 */
4436 public static function xmlrpc_api_url() {
4437 $base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4438 return untrailingslashit( $base ) . '/xmlrpc.php';
4439 }
4440
4441 /**
4442 * Creates two secret tokens and the end of life timestamp for them.
4443 *
4444 * Note these tokens are unique per call, NOT static per site for connecting.
4445 *
4446 * @since 2.6
4447 * @return array
4448 */
4449 public function generate_secrets() {
4450 $secrets = array(
4451 wp_generate_password( 32, false ), // secret_1
4452 wp_generate_password( 32, false ), // secret_2
4453 ( time() + 600 ), // eol ( End of Life )
4454 );
4455
4456 return $secrets;
4457 }
4458
4459 /**
4460 * Builds the timeout limit for queries talking with the wpcom servers.
4461 *
4462 * Based on local php max_execution_time in php.ini
4463 *
4464 * @since 2.6
4465 * @return int
4466 **/
4467 public function get_remote_query_timeout_limit() {
4468 $timeout = (int) ini_get( 'max_execution_time' );
4469 if ( ! $timeout ) // Ensure exec time set in php.ini
4470 $timeout = 30;
4471 return intval( $timeout / 2 );
4472 }
4473
4474
4475 /**
4476 * Takes the response from the Jetpack register new site endpoint and
4477 * verifies it worked properly.
4478 *
4479 * @since 2.6
4480 * @return true or Jetpack_Error
4481 **/
4482 public function validate_remote_register_response( $response ) {
4483 if ( is_wp_error( $response ) ) {
4484 return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4485 }
4486
4487 $code = wp_remote_retrieve_response_code( $response );
4488 $entity = wp_remote_retrieve_body( $response );
4489 if ( $entity )
4490 $json = json_decode( $entity );
4491 else
4492 $json = false;
4493
4494 $code_type = intval( $code / 100 );
4495 if ( 5 == $code_type ) {
4496 return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4497 } elseif ( 408 == $code ) {
4498 return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4499 } elseif ( ! empty( $json->error ) ) {
4500 $error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4501 return new Jetpack_Error( (string) $json->error, $error_description, $code );
4502 } elseif ( 200 != $code ) {
4503 return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4504 }
4505
4506 // Jetpack ID error block
4507 if ( empty( $json->jetpack_id ) ) {
4508 return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4509 } elseif ( ! is_scalar( $json->jetpack_id ) ) {
4510 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 );
4511 } elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
4512 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 );
4513 }
4514
4515 return true;
4516 }
4517 /**
4518 * @return bool|WP_Error
4519 */
4520 public static function register() {
4521 add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4522 $secrets = Jetpack::init()->generate_secrets();
4523
4524 Jetpack_Options::update_option( 'register', $secrets[0] . ':' . $secrets[1] . ':' . $secrets[2] );
4525
4526 @list( $secret_1, $secret_2, $secret_eol ) = explode( ':', Jetpack_Options::get_option( 'register' ) );
4527 if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4528 return new Jetpack_Error( 'missing_secrets' );
4529 }
4530
4531 $timeout = Jetpack::init()->get_remote_query_timeout_limit();
4532
4533 $gmt_offset = get_option( 'gmt_offset' );
4534 if ( ! $gmt_offset ) {
4535 $gmt_offset = 0;
4536 }
4537
4538 $stats_options = get_option( 'stats_options' );
4539 $stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4540
4541 $args = array(
4542 'method' => 'POST',
4543 'body' => array(
4544 'siteurl' => site_url(),
4545 'home' => home_url(),
4546 'gmt_offset' => $gmt_offset,
4547 'timezone_string' => (string) get_option( 'timezone_string' ),
4548 'site_name' => (string) get_option( 'blogname' ),
4549 'secret_1' => $secret_1,
4550 'secret_2' => $secret_2,
4551 'site_lang' => get_locale(),
4552 'timeout' => $timeout,
4553 'stats_id' => $stats_id,
4554 ),
4555 'headers' => array(
4556 'Accept' => 'application/json',
4557 ),
4558 'timeout' => $timeout,
4559 );
4560 $response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4561
4562
4563 // Make sure the response is valid and does not contain any Jetpack errors
4564 $valid_response = Jetpack::init()->validate_remote_register_response( $response );
4565 if( is_wp_error( $valid_response ) || !$valid_response ) {
4566 return $valid_response;
4567 }
4568
4569
4570 // Grab the response values to work with
4571 $code = wp_remote_retrieve_response_code( $response );
4572 $entity = wp_remote_retrieve_body( $response );
4573
4574 if ( $entity )
4575 $json = json_decode( $entity );
4576 else
4577 $json = false;
4578
4579 if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
4580 return new Jetpack_Error( 'jetpack_secret', '', $code );
4581
4582 if ( isset( $json->jetpack_public ) ) {
4583 $jetpack_public = (int) $json->jetpack_public;
4584 } else {
4585 $jetpack_public = false;
4586 }
4587
4588 Jetpack_Options::update_options(
4589 array(
4590 'id' => (int) $json->jetpack_id,
4591 'blog_token' => (string) $json->jetpack_secret,
4592 'public' => $jetpack_public,
4593 )
4594 );
4595
4596 // Initialize Jump Start for the first and only time.
4597 if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4598 Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4599
4600 $jetpack = Jetpack::init();
4601
4602 $jetpack->stat( 'jumpstart', 'unique-views' );
4603 $jetpack->do_stats( 'server_side' );
4604 };
4605
4606 return true;
4607 }
4608
4609 /**
4610 * If the db version is showing something other that what we've got now, bump it to current.
4611 *
4612 * @return bool: True if the option was incorrect and updated, false if nothing happened.
4613 */
4614 public static function maybe_set_version_option() {
4615 list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4616 if ( JETPACK__VERSION != $version ) {
4617 Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4618 return true;
4619 }
4620 return false;
4621 }
4622
4623 /* Client Server API */
4624
4625 /**
4626 * Loads the Jetpack XML-RPC client
4627 */
4628 public static function load_xml_rpc_client() {
4629 require_once ABSPATH . WPINC . '/class-IXR.php';
4630 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4631 }
4632
4633 function verify_xml_rpc_signature() {
4634 if ( $this->xmlrpc_verification ) {
4635 return $this->xmlrpc_verification;
4636 }
4637
4638 // It's not for us
4639 if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4640 return false;
4641 }
4642
4643 @list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
4644 if (
4645 empty( $token_key )
4646 ||
4647 empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4648 ) {
4649 return false;
4650 }
4651
4652 if ( '0' === $user_id ) {
4653 $token_type = 'blog';
4654 $user_id = 0;
4655 } else {
4656 $token_type = 'user';
4657 if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4658 return false;
4659 }
4660 $user_id = (int) $user_id;
4661
4662 $user = new WP_User( $user_id );
4663 if ( ! $user || ! $user->exists() ) {
4664 return false;
4665 }
4666 }
4667
4668 $token = Jetpack_Data::get_access_token( $user_id );
4669 if ( ! $token ) {
4670 return false;
4671 }
4672
4673 $token_check = "$token_key.";
4674 if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4675 return false;
4676 }
4677
4678 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4679
4680 $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4681 if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4682 $post_data = $_POST;
4683 $file_hashes = array();
4684 foreach ( $post_data as $post_data_key => $post_data_value ) {
4685 if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4686 continue;
4687 }
4688 $post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4689 $file_hashes[$post_data_key] = $post_data_value;
4690 }
4691
4692 foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4693 unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4694 $post_data[$post_data_key] = $post_data_value;
4695 }
4696
4697 ksort( $post_data );
4698
4699 $body = http_build_query( stripslashes_deep( $post_data ) );
4700 } elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4701 $body = file_get_contents( 'php://input' );
4702 } else {
4703 $body = null;
4704 }
4705 $signature = $jetpack_signature->sign_current_request(
4706 array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4707 );
4708
4709 if ( ! $signature ) {
4710 return false;
4711 } else if ( is_wp_error( $signature ) ) {
4712 return $signature;
4713 } else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4714 return false;
4715 }
4716
4717 $timestamp = (int) $_GET['timestamp'];
4718 $nonce = stripslashes( (string) $_GET['nonce'] );
4719
4720 if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4721 return false;
4722 }
4723
4724 $this->xmlrpc_verification = array(
4725 'type' => $token_type,
4726 'user_id' => $token->external_user_id,
4727 );
4728
4729 return $this->xmlrpc_verification;
4730 }
4731
4732 /**
4733 * Authenticates XML-RPC and other requests from the Jetpack Server
4734 */
4735 function authenticate_jetpack( $user, $username, $password ) {
4736 if ( is_a( $user, 'WP_User' ) ) {
4737 return $user;
4738 }
4739
4740 $token_details = $this->verify_xml_rpc_signature();
4741
4742 if ( ! $token_details || is_wp_error( $token_details ) ) {
4743 return $user;
4744 }
4745
4746 if ( 'user' !== $token_details['type'] ) {
4747 return $user;
4748 }
4749
4750 if ( ! $token_details['user_id'] ) {
4751 return $user;
4752 }
4753
4754 nocache_headers();
4755
4756 return new WP_User( $token_details['user_id'] );
4757 }
4758
4759 function add_nonce( $timestamp, $nonce ) {
4760 global $wpdb;
4761 static $nonces_used_this_request = array();
4762
4763 if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4764 return $nonces_used_this_request["$timestamp:$nonce"];
4765 }
4766
4767 // This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4768 $timestamp = (int) $timestamp;
4769 $nonce = esc_sql( $nonce );
4770
4771 // Raw query so we can avoid races: add_option will also update
4772 $show_errors = $wpdb->show_errors( false );
4773
4774 $old_nonce = $wpdb->get_row(
4775 $wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4776 );
4777
4778 if ( is_null( $old_nonce ) ) {
4779 $return = $wpdb->query(
4780 $wpdb->prepare(
4781 "INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4782 "jetpack_nonce_{$timestamp}_{$nonce}",
4783 time(),
4784 'no'
4785 )
4786 );
4787 } else {
4788 $return = false;
4789 }
4790
4791 $wpdb->show_errors( $show_errors );
4792
4793 $nonces_used_this_request["$timestamp:$nonce"] = $return;
4794
4795 return $return;
4796 }
4797
4798 /**
4799 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
4800 * Capture it here so we can verify the signature later.
4801 */
4802 function xmlrpc_methods( $methods ) {
4803 $this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4804 return $methods;
4805 }
4806
4807 function public_xmlrpc_methods( $methods ) {
4808 if ( array_key_exists( 'wp.getOptions', $methods ) ) {
4809 $methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
4810 }
4811 return $methods;
4812 }
4813
4814 function jetpack_getOptions( $args ) {
4815 global $wp_xmlrpc_server;
4816
4817 $wp_xmlrpc_server->escape( $args );
4818
4819 $username = $args[1];
4820 $password = $args[2];
4821
4822 if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
4823 return $wp_xmlrpc_server->error;
4824 }
4825
4826 $options = array();
4827 $user_data = $this->get_connected_user_data();
4828 if ( is_array( $user_data ) ) {
4829 $options['jetpack_user_id'] = array(
4830 'desc' => __( 'The WP.com user ID of the connected user', 'jetpack' ),
4831 'readonly' => true,
4832 'value' => $user_data['ID'],
4833 );
4834 $options['jetpack_user_login'] = array(
4835 'desc' => __( 'The WP.com username of the connected user', 'jetpack' ),
4836 'readonly' => true,
4837 'value' => $user_data['login'],
4838 );
4839 $options['jetpack_user_email'] = array(
4840 'desc' => __( 'The WP.com user email of the connected user', 'jetpack' ),
4841 'readonly' => true,
4842 'value' => $user_data['email'],
4843 );
4844 $options['jetpack_user_site_count'] = array(
4845 'desc' => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
4846 'readonly' => true,
4847 'value' => $user_data['site_count'],
4848 );
4849 }
4850 $wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4851 $args = stripslashes_deep( $args );
4852 return $wp_xmlrpc_server->wp_getOptions( $args );
4853 }
4854
4855 function xmlrpc_options( $options ) {
4856 $jetpack_client_id = false;
4857 if ( self::is_active() ) {
4858 $jetpack_client_id = Jetpack_Options::get_option( 'id' );
4859 }
4860 $options['jetpack_version'] = array(
4861 'desc' => __( 'Jetpack Plugin Version', 'jetpack' ),
4862 'readonly' => true,
4863 'value' => JETPACK__VERSION,
4864 );
4865
4866 $options['jetpack_client_id'] = array(
4867 'desc' => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
4868 'readonly' => true,
4869 'value' => $jetpack_client_id,
4870 );
4871 return $options;
4872 }
4873
4874 public static function clean_nonces( $all = false ) {
4875 global $wpdb;
4876
4877 $sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
4878 if ( method_exists ( $wpdb , 'esc_like' ) ) {
4879 $sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
4880 } else {
4881 $sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
4882 }
4883
4884 if ( true !== $all ) {
4885 $sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
4886 $sql_args[] = time() - 3600;
4887 }
4888
4889 $sql .= ' ORDER BY `option_id` LIMIT 100';
4890
4891 $sql = $wpdb->prepare( $sql, $sql_args );
4892
4893 for ( $i = 0; $i < 1000; $i++ ) {
4894 if ( ! $wpdb->query( $sql ) ) {
4895 break;
4896 }
4897 }
4898 }
4899
4900 /**
4901 * State is passed via cookies from one request to the next, but never to subsequent requests.
4902 * SET: state( $key, $value );
4903 * GET: $value = state( $key );
4904 *
4905 * @param string $key
4906 * @param string $value
4907 * @param bool $restate private
4908 */
4909 public static function state( $key = null, $value = null, $restate = false ) {
4910 static $state = array();
4911 static $path, $domain;
4912 if ( ! isset( $path ) ) {
4913 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
4914 $admin_url = Jetpack::admin_url();
4915 $bits = parse_url( $admin_url );
4916
4917 if ( is_array( $bits ) ) {
4918 $path = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4919 $domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4920 } else {
4921 $path = $domain = null;
4922 }
4923 }
4924
4925 // Extract state from cookies and delete cookies
4926 if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
4927 $yum = $_COOKIE[ 'jetpackState' ];
4928 unset( $_COOKIE[ 'jetpackState' ] );
4929 foreach ( $yum as $k => $v ) {
4930 if ( strlen( $v ) )
4931 $state[ $k ] = $v;
4932 setcookie( "jetpackState[$k]", false, 0, $path, $domain );
4933 }
4934 }
4935
4936 if ( $restate ) {
4937 foreach ( $state as $k => $v ) {
4938 setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
4939 }
4940 return;
4941 }
4942
4943 // Get a state variable
4944 if ( isset( $key ) && ! isset( $value ) ) {
4945 if ( array_key_exists( $key, $state ) )
4946 return $state[ $key ];
4947 return null;
4948 }
4949
4950 // Set a state variable
4951 if ( isset ( $key ) && isset( $value ) ) {
4952 if( is_array( $value ) && isset( $value[0] ) ) {
4953 $value = $value[0];
4954 }
4955 $state[ $key ] = $value;
4956 setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
4957 }
4958 }
4959
4960 public static function restate() {
4961 Jetpack::state( null, null, true );
4962 }
4963
4964 public static function check_privacy( $file ) {
4965 static $is_site_publicly_accessible = null;
4966
4967 if ( is_null( $is_site_publicly_accessible ) ) {
4968 $is_site_publicly_accessible = false;
4969
4970 Jetpack::load_xml_rpc_client();
4971 $rpc = new Jetpack_IXR_Client();
4972
4973 $success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
4974 if ( $success ) {
4975 $response = $rpc->getResponse();
4976 if ( $response ) {
4977 $is_site_publicly_accessible = true;
4978 }
4979 }
4980
4981 Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
4982 }
4983
4984 if ( $is_site_publicly_accessible ) {
4985 return;
4986 }
4987
4988 $module_slug = self::get_module_slug( $file );
4989
4990 $privacy_checks = Jetpack::state( 'privacy_checks' );
4991 if ( ! $privacy_checks ) {
4992 $privacy_checks = $module_slug;
4993 } else {
4994 $privacy_checks .= ",$module_slug";
4995 }
4996
4997 Jetpack::state( 'privacy_checks', $privacy_checks );
4998 }
4999
5000 /**
5001 * Helper method for multicall XMLRPC.
5002 */
5003 public static function xmlrpc_async_call() {
5004 global $blog_id;
5005 static $clients = array();
5006
5007 $client_blog_id = is_multisite() ? $blog_id : 0;
5008
5009 if ( ! isset( $clients[$client_blog_id] ) ) {
5010 Jetpack::load_xml_rpc_client();
5011 $clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5012 if ( function_exists( 'ignore_user_abort' ) ) {
5013 ignore_user_abort( true );
5014 }
5015 add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5016 }
5017
5018 $args = func_get_args();
5019
5020 if ( ! empty( $args[0] ) ) {
5021 call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5022 } elseif ( is_multisite() ) {
5023 foreach ( $clients as $client_blog_id => $client ) {
5024 if ( ! $client_blog_id || empty( $client->calls ) ) {
5025 continue;
5026 }
5027
5028 $switch_success = switch_to_blog( $client_blog_id, true );
5029 if ( ! $switch_success ) {
5030 continue;
5031 }
5032
5033 flush();
5034 $client->query();
5035
5036 restore_current_blog();
5037 }
5038 } else {
5039 if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5040 flush();
5041 $clients[0]->query();
5042 }
5043 }
5044 }
5045
5046 public static function staticize_subdomain( $url ) {
5047
5048 // Extract hostname from URL
5049 $host = parse_url( $url, PHP_URL_HOST );
5050
5051 // Explode hostname on '.'
5052 $exploded_host = explode( '.', $host );
5053
5054 // Retrieve the name and TLD
5055 if ( count( $exploded_host ) > 1 ) {
5056 $name = $exploded_host[ count( $exploded_host ) - 2 ];
5057 $tld = $exploded_host[ count( $exploded_host ) - 1 ];
5058 // Rebuild domain excluding subdomains
5059 $domain = $name . '.' . $tld;
5060 } else {
5061 $domain = $host;
5062 }
5063 // Array of Automattic domains
5064 $domain_whitelist = array( 'wordpress.com', 'wp.com' );
5065
5066 // Return $url if not an Automattic domain
5067 if ( ! in_array( $domain, $domain_whitelist ) ) {
5068 return $url;
5069 }
5070
5071 if ( is_ssl() ) {
5072 return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5073 }
5074
5075 srand( crc32( basename( $url ) ) );
5076 $static_counter = rand( 0, 2 );
5077 srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5078
5079 return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5080 }
5081
5082 /* JSON API Authorization */
5083
5084 /**
5085 * Handles the login action for Authorizing the JSON API
5086 */
5087 function login_form_json_api_authorization() {
5088 $this->verify_json_api_authorization_request();
5089
5090 add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5091
5092 add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5093 add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5094 add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5095 }
5096
5097 // Make sure the login form is POSTed to the signed URL so we can reverify the request
5098 function post_login_form_to_signed_url( $url, $path, $scheme ) {
5099 if ( 'wp-login.php' !== $path || 'login_post' !== $scheme ) {
5100 return $url;
5101 }
5102
5103 $parsed_url = parse_url( $url );
5104 $url = strtok( $url, '?' );
5105 $url = "$url?{$_SERVER['QUERY_STRING']}";
5106 if ( ! empty( $parsed_url['query'] ) )
5107 $url .= "&{$parsed_url['query']}";
5108
5109 return $url;
5110 }
5111
5112 // Make sure the POSTed request is handled by the same action
5113 function preserve_action_in_login_form_for_json_api_authorization() {
5114 echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5115 echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5116 }
5117
5118 // If someone logs in to approve API access, store the Access Code in usermeta
5119 function store_json_api_authorization_token( $user_login, $user ) {
5120 add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5121 add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5122 $token = wp_generate_password( 32, false );
5123 update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5124 }
5125
5126 // Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5127 function allow_wpcom_public_api_domain( $domains ) {
5128 $domains[] = 'public-api.wordpress.com';
5129 return $domains;
5130 }
5131
5132 // Add the Access Code details to the public-api.wordpress.com redirect
5133 function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5134 return add_query_arg(
5135 urlencode_deep(
5136 array(
5137 'jetpack-code' => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5138 'jetpack-user-id' => (int) $user->ID,
5139 'jetpack-state' => $this->json_api_authorization_request['state'],
5140 )
5141 ),
5142 $redirect_to
5143 );
5144 }
5145
5146 // Verifies the request by checking the signature
5147 function verify_json_api_authorization_request() {
5148 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5149
5150 $token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5151 if ( ! $token || empty( $token->secret ) ) {
5152 wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5153 }
5154
5155 $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' );
5156
5157 $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5158
5159 if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5160 $signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5161 } else {
5162 $signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5163 }
5164
5165 if ( ! $signature ) {
5166 wp_die( $die_error );
5167 } else if ( is_wp_error( $signature ) ) {
5168 wp_die( $die_error );
5169 } else if ( $signature !== $_GET['signature'] ) {
5170 if ( is_ssl() ) {
5171 // 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
5172 $signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5173 if ( ! $signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
5174 wp_die( $die_error );
5175 }
5176 } else {
5177 wp_die( $die_error );
5178 }
5179 }
5180
5181 $timestamp = (int) $_GET['timestamp'];
5182 $nonce = stripslashes( (string) $_GET['nonce'] );
5183
5184 if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5185 // De-nonce the nonce, at least for 5 minutes.
5186 // 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)
5187 $old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5188 if ( $old_nonce_time < time() - 300 ) {
5189 wp_die( __( 'The authorization process expired. Please go back and try again.' , 'jetpack' ) );
5190 }
5191 }
5192
5193 $data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5194 $data_filters = array(
5195 'state' => 'opaque',
5196 'client_id' => 'int',
5197 'client_title' => 'string',
5198 'client_image' => 'url',
5199 );
5200
5201 foreach ( $data_filters as $key => $sanitation ) {
5202 if ( ! isset( $data->$key ) ) {
5203 wp_die( $die_error );
5204 }
5205
5206 switch ( $sanitation ) {
5207 case 'int' :
5208 $this->json_api_authorization_request[$key] = (int) $data->$key;
5209 break;
5210 case 'opaque' :
5211 $this->json_api_authorization_request[$key] = (string) $data->$key;
5212 break;
5213 case 'string' :
5214 $this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5215 break;
5216 case 'url' :
5217 $this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5218 break;
5219 }
5220 }
5221
5222 if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5223 wp_die( $die_error );
5224 }
5225 }
5226
5227 function login_message_json_api_authorization( $message ) {
5228 return '<p class="message">' . sprintf(
5229 esc_html__( '%s wants to access your site&#8217;s data. Log in to authorize that access.' , 'jetpack' ),
5230 '<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5231 ) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5232 }
5233
5234 /**
5235 * Get $content_width, but with a <s>twist</s> filter.
5236 */
5237 public static function get_content_width() {
5238 $content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5239 return apply_filters( 'jetpack_content_width', $content_width );
5240 }
5241
5242 /**
5243 * Centralize the function here until it gets added to core.
5244 *
5245 * @param int|string|object $id_or_email A user ID, email address, or comment object
5246 * @param int $size Size of the avatar image
5247 * @param string $default URL to a default image to use if no avatar is available
5248 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5249 *
5250 * @return array First element is the URL, second is the class.
5251 */
5252 public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5253 // Don't bother adding the __return_true filter if it's already there.
5254 $has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5255
5256 if ( $force_display && ! $has_filter )
5257 add_filter( 'pre_option_show_avatars', '__return_true' );
5258
5259 $avatar = get_avatar( $id_or_email, $size, $default );
5260
5261 if ( $force_display && ! $has_filter )
5262 remove_filter( 'pre_option_show_avatars', '__return_true' );
5263
5264 // If no data, fail out.
5265 if ( is_wp_error( $avatar ) || ! $avatar )
5266 return array( null, null );
5267
5268 // Pull out the URL. If it's not there, fail out.
5269 if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5270 return array( null, null );
5271 $url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5272
5273 // Pull out the class, but it's not a big deal if it's missing.
5274 $class = '';
5275 if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5276 $class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5277
5278 return array( $url, $class );
5279 }
5280
5281 /**
5282 * Pings the WordPress.com Mirror Site for the specified options.
5283 *
5284 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5285 *
5286 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5287 */
5288 public function get_cloud_site_options( $option_names ) {
5289 $option_names = array_filter( (array) $option_names, 'is_string' );
5290
5291 Jetpack::load_xml_rpc_client();
5292 $xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5293 $xml->query( 'jetpack.fetchSiteOptions', $option_names );
5294 if ( $xml->isError() ) {
5295 return array_flip( $option_names );
5296 }
5297 $cloud_site_options = $xml->getResponse();
5298
5299 return $cloud_site_options;
5300 }
5301
5302 /**
5303 * Fetch the filtered array of options that we should compare to determine an identity crisis.
5304 *
5305 * @return array An array of options to check.
5306 */
5307 public static function identity_crisis_options_to_check() {
5308 $options = array(
5309 'siteurl',
5310 'home',
5311 );
5312 return apply_filters( 'jetpack_identity_crisis_options_to_check', $options );
5313 }
5314
5315 /**
5316 * Checks to make sure that local options have the same values as remote options. Will cache the results for up to 24 hours.
5317 *
5318 * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
5319 *
5320 * @return array An array of options that do not match. If everything is good, it will evaluate to false.
5321 */
5322 public static function check_identity_crisis( $force_recheck = false ) {
5323 if ( ! Jetpack::is_active() || Jetpack::is_development_mode() )
5324 return false;
5325
5326 if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
5327 $options_to_check = self::identity_crisis_options_to_check();
5328 $cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5329 $errors = array();
5330 foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5331 // If it's not the same as the local value...
5332 if ( $cloud_value !== get_option( $cloud_key ) ) {
5333 // And it's not been added to the whitelist...
5334 if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
5335 /*
5336 * This should be a temporary hack until a cleaner solution is found.
5337 *
5338 * The siteurl and home can be set to use http in General > Settings
5339 * however some constants can be defined that can force https in wp-admin
5340 * when this happens wpcom can confuse wporg with a fake identity
5341 * crisis with a mismatch of http vs https when it should be allowed.
5342 * we need to check that here.
5343 *
5344 * @see https://github.com/Automattic/jetpack/issues/1006
5345 */
5346 if( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
5347 && ( substr( $cloud_value, 0, 8 ) == "https://" )
5348 && Jetpack::init()->is_ssl_required_to_visit_site() ) {
5349 // Ok, we found a mismatch of http and https because of wp-config, not an invalid url
5350 continue;
5351 }
5352
5353
5354 // Then kick an error!
5355 $errors[ $cloud_key ] = $cloud_value;
5356 }
5357 }
5358 }
5359 }
5360 return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
5361 }
5362
5363 /**
5364 * Adds a value to the whitelist for the specified key.
5365 *
5366 * @param string $key The option name that we're whitelisting the value for.
5367 * @param string $value The value that we're intending to add to the whitelist.
5368 *
5369 * @return bool Whether the value was added to the whitelist, or false if it was already there.
5370 */
5371 public static function whitelist_identity_crisis_value( $key, $value ) {
5372 if ( self::is_identity_crisis_url_whitelisted( $key, $value ) ) {
5373 return false;
5374 }
5375
5376 $whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
5377 if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
5378 $whitelist[ $key ] = array();
5379 }
5380 array_push( $whitelist[ $key ], $value );
5381
5382 Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
5383 return true;
5384 }
5385
5386 /**
5387 * Checks whether a value is already whitelisted.
5388 *
5389 * @param string $key The option name that we're checking the value for.
5390 * @param string $value The value that we're curious to see if it's on the whitelist.
5391 *
5392 * @return bool Whether the value is whitelisted.
5393 */
5394 public static function is_identity_crisis_value_whitelisted( $key, $value ) {
5395 $whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
5396 if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
5397 return true;
5398 }
5399 return false;
5400 }
5401
5402 /**
5403 * Displays an admin_notice, alerting the user to an identity crisis.
5404 */
5405 public function alert_identity_crisis() {
5406 if ( ! current_user_can( 'manage_options' ) )
5407 return;
5408
5409 if ( ! $errors = self::check_identity_crisis() )
5410 return;
5411 ?>
5412
5413 <div id="message" class="updated jetpack-message jp-identity-crisis">
5414 <div class="jp-banner__content">
5415 <h4><?php _e( 'Something has gotten mixed up!', 'jetpack' ); ?></h4>
5416 <?php foreach ( $errors as $key => $value ) : ?>
5417 <p><?php printf( __( 'Your <code>%1$s</code> option is set up as <strong>%2$s</strong>, but your WordPress.com connection lists it as <strong>%3$s</strong>!', 'jetpack' ), $key, (string) get_option( $key ), $value ); ?></p>
5418 <?php endforeach; ?>
5419 <p><a href="<?php echo $this->build_reconnect_url() ?>"><?php _e( 'The data listed above is not for my current site. Please disconnect, and then form a new connection to WordPress.com for this site using my current settings.', 'jetpack' ); ?></a></p>
5420 <p><a href="#"><?php _e( 'Ignore the difference. This is just a staging site for the real site referenced above.', 'jetpack' ); ?></a></p>
5421 <p><a href="#"><?php _e( 'That used to be my URL for this site before I changed it. Update the WordPress.com Cloud\'s data to match my current settings.', 'jetpack' ); ?></a></p>
5422 </div>
5423 </div>
5424
5425 <?php
5426 }
5427
5428 /**
5429 * Maybe Use a .min.css stylesheet, maybe not.
5430 *
5431 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5432 */
5433 public static function maybe_min_asset( $url, $path, $plugin ) {
5434 // Short out on things trying to find actual paths.
5435 if ( ! $path || empty( $plugin ) ) {
5436 return $url;
5437 }
5438
5439 // Strip out the abspath.
5440 $base = dirname( plugin_basename( $plugin ) );
5441
5442 // Short out on non-Jetpack assets.
5443 if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5444 return $url;
5445 }
5446
5447 // File name parsing.
5448 $file = "{$base}/{$path}";
5449 $full_path = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5450 $file_name = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5451 $file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5452 $extension = array_shift( $file_name_parts_r );
5453
5454 if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5455 // Already pointing at the minified version.
5456 if ( 'min' === $file_name_parts_r[0] ) {
5457 return $url;
5458 }
5459
5460 $min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5461 if ( file_exists( $min_full_path ) ) {
5462 $url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5463 }
5464 }
5465
5466 return $url;
5467 }
5468
5469 /**
5470 * Maybe inlines a stylesheet.
5471 *
5472 * If you'd like to inline a stylesheet instead of printing a link to it,
5473 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5474 *
5475 * Attached to `style_loader_tag` filter.
5476 *
5477 * @param string $tag The tag that would link to the external asset.
5478 * @param string $handle The registered handle of the script in question.
5479 *
5480 * @return string
5481 */
5482 public static function maybe_inline_style( $tag, $handle ) {
5483 global $wp_styles;
5484 $item = $wp_styles->registered[ $handle ];
5485
5486 if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5487 return $tag;
5488 }
5489
5490 if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5491 $href = $matches[1];
5492 // Strip off query string
5493 if ( $pos = strpos( $href, '?' ) ) {
5494 $href = substr( $href, 0, $pos );
5495 }
5496 // Strip off fragment
5497 if ( $pos = strpos( $href, '#' ) ) {
5498 $href = substr( $href, 0, $pos );
5499 }
5500 } else {
5501 return $tag;
5502 }
5503
5504 $plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5505 if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5506 return $tag;
5507 }
5508
5509 // If this stylesheet has a RTL version, and the RTL version replaces normal...
5510 if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5511 // And this isn't the pass that actually deals with the RTL version...
5512 if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5513 // Short out, as the RTL version will deal with it in a moment.
5514 return $tag;
5515 }
5516 }
5517
5518 $file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5519 $css = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5520 if ( $css ) {
5521 $tag = "<!-- Inline {$item->handle} -->\r\n";
5522 if ( empty( $item->extra['after'] ) ) {
5523 wp_add_inline_style( $handle, $css );
5524 } else {
5525 array_unshift( $item->extra['after'], $css );
5526 wp_style_add_data( $handle, 'after', $item->extra['after'] );
5527 }
5528 }
5529
5530 return $tag;
5531 }
5532
5533 /**
5534 * Loads a view file from the views
5535 *
5536 * Data passed in with the $data parameter will be available in the
5537 * template file as $data['value']
5538 *
5539 * @param string $template - Template file to load
5540 * @param array $data - Any data to pass along to the template
5541 * @return boolean - If template file was found
5542 **/
5543 public function load_view( $template, $data = array() ) {
5544 $views_dir = JETPACK__PLUGIN_DIR . 'views/';
5545
5546 if( file_exists( $views_dir . $template ) ) {
5547 require_once( $views_dir . $template );
5548 return true;
5549 }
5550
5551 error_log( "Jetpack: Unable to find view file $views_dir$template" );
5552 return false;
5553 }
5554
5555 /**
5556 * Sends a ping to the Jetpack servers to toggle on/off remote portions
5557 * required by some modules.
5558 *
5559 * @param string $module_slug
5560 */
5561 public function toggle_module_on_wpcom( $module_slug ) {
5562 Jetpack::init()->sync->register( 'noop' );
5563
5564 if ( false !== strpos( current_filter(), 'jetpack_activate_module_' ) ) {
5565 self::check_privacy( $module_slug );
5566 }
5567
5568 }
5569
5570 /**
5571 * Throws warnings for deprecated hooks to be removed from Jetpack
5572 */
5573 public function deprecated_hooks() {
5574 global $wp_filter;
5575
5576 /*
5577 * Format:
5578 * deprecated_filter_name => replacement_name
5579 *
5580 * If there is no replacement us null for replacement_name
5581 */
5582 $deprecated_list = array(
5583 'jetpack_bail_on_shortcode' => 'jetpack_shortcodes_to_include',
5584 'wpl_sharing_2014_1' => null,
5585 );
5586
5587 // This is a silly loop depth. Better way?
5588 foreach( $deprecated_list AS $hook => $hook_alt ) {
5589 if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
5590 foreach( $wp_filter[$hook] AS $func => $values ) {
5591 foreach( $values AS $hooked ) {
5592 _deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
5593 }
5594 }
5595 }
5596 }
5597 }
5598
5599 /**
5600 * Converts any url in a stylesheet, to the correct absolute url.
5601 *
5602 * Considerations:
5603 * - Normal, relative URLs `feh.png`
5604 * - Data URLs `data:image/gif;base64,eh129ehiuehjdhsa==`
5605 * - Schema-agnostic URLs `//domain.com/feh.png`
5606 * - Absolute URLs `http://domain.com/feh.png`
5607 * - Domain root relative URLs `/feh.png`
5608 *
5609 * @param $css string: The raw CSS -- should be read in directly from the file.
5610 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
5611 *
5612 * @return mixed|string
5613 */
5614 public static function absolutize_css_urls( $css, $css_file_url ) {
5615 $pattern = '#url\((?P<path>[^)]*)\)#i';
5616 $css_dir = dirname( $css_file_url );
5617 $p = parse_url( $css_dir );
5618 $domain = sprintf(
5619 '%1$s//%2$s%3$s%4$s',
5620 isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
5621 isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5622 $p['host'],
5623 isset( $p['port'] ) ? ":{$p['port']}" : ''
5624 );
5625
5626 if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5627 $find = $replace = array();
5628 foreach ( $matches as $match ) {
5629 $url = trim( $match['path'], "'\" \t" );
5630
5631 // If this is a data url, we don't want to mess with it.
5632 if ( 'data:' === substr( $url, 0, 5 ) ) {
5633 continue;
5634 }
5635
5636 // If this is an absolute or protocol-agnostic url,
5637 // we don't want to mess with it.
5638 if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5639 continue;
5640 }
5641
5642 switch ( substr( $url, 0, 1 ) ) {
5643 case '/':
5644 $absolute = $domain . $url;
5645 break;
5646 default:
5647 $absolute = $css_dir . '/' . $url;
5648 }
5649
5650 $find[] = $match[0];
5651 $replace[] = sprintf( 'url("%s")', $absolute );
5652 }
5653 $css = str_replace( $find, $replace, $css );
5654 }
5655
5656 return $css;
5657 }
5658
5659 /**
5660 * This method checks to see if SSL is required by the site in
5661 * order to visit it in some way other than only setting the
5662 * https value in the home or siteurl values.
5663 *
5664 * @since 3.2
5665 * @return boolean
5666 **/
5667 private function is_ssl_required_to_visit_site() {
5668 $ssl = is_ssl();
5669
5670 if ( force_ssl_login() ) {
5671 $ssl = true;
5672 } else if ( force_ssl_admin() ) {
5673 $ssl = true;
5674 }
5675 return $ssl;
5676 }
5677
5678 /**
5679 * This methods removes all of the registered css files on the frontend
5680 * from Jetpack in favor of using a single file. In effect "imploding"
5681 * all the files into one file.
5682 *
5683 * Pros:
5684 * - Uses only ONE css asset connection instead of 15
5685 * - Saves a minimum of 56k
5686 * - Reduces server load
5687 * - Reduces time to first painted byte
5688 *
5689 * Cons:
5690 * - Loads css for ALL modules. However all selectors are prefixed so it
5691 * should not cause any issues with themes.
5692 * - Plugins/themes dequeuing styles no longer do anything. See
5693 * jetpack_implode_frontend_css filter for a workaround
5694 *
5695 * For some situations developers may wish to disable css imploding and
5696 * instead operate in legacy mode where each file loads seperately and
5697 * can be edited individually or dequeued. This can be accomplished with
5698 * the following line:
5699 *
5700 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5701 *
5702 * @since 3.2
5703 **/
5704 public function implode_frontend_css( $travis_test = false ) {
5705 $do_implode = true;
5706 if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5707 $do_implode = false;
5708 }
5709
5710 $do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5711
5712 // Do not use the imploded file when default behaviour was altered through the filter
5713 if ( ! $do_implode ) {
5714 return;
5715 }
5716
5717 // We do not want to use the imploded file in dev mode, or if not connected
5718 if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5719 if ( ! $travis_test ) {
5720 return;
5721 }
5722 }
5723
5724 // Do not use the imploded file if sharing css was dequeued via the sharing settings screen
5725 if ( get_option( 'sharedaddy_disable_resources' ) ) {
5726 return;
5727 }
5728
5729 /*
5730 * Now we assume Jetpack is connected and able to serve the single
5731 * file.
5732 *
5733 * In the future there will be a check here to serve the file locally
5734 * or potentially from the Jetpack CDN
5735 *
5736 * For now:
5737 * - Enqueue a single imploded css file
5738 * - Zero out the style_loader_tag for the bundled ones
5739 * - Be happy, drink scotch
5740 */
5741
5742 add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
5743
5744 $version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
5745
5746 wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
5747 wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
5748 }
5749
5750 function concat_remove_style_loader_tag( $tag, $handle ) {
5751 if ( in_array( $handle, $this->concatenated_style_handles ) ) {
5752 $tag = '';
5753 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5754 $tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
5755 }
5756 }
5757
5758 return $tag;
5759 }
5760
5761 /*
5762 * Check the heartbeat data
5763 *
5764 * Organizes the heartbeat data by severity. For example, if the site
5765 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
5766 *
5767 * Data will be added to "caution" array, if it either:
5768 * - Out of date Jetpack version
5769 * - Out of date WP version
5770 * - Out of date PHP version
5771 *
5772 * $return array $filtered_data
5773 */
5774 public static function jetpack_check_heartbeat_data() {
5775 $raw_data = Jetpack_Heartbeat::generate_stats_array();
5776
5777 $good = array();
5778 $caution = array();
5779 $bad = array();
5780
5781 foreach ( $raw_data as $stat => $value ) {
5782
5783 // Check jetpack version
5784 if ( 'version' == $stat ) {
5785 if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
5786 $caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
5787 continue;
5788 }
5789 }
5790
5791 // Check WP version
5792 if ( 'wp-version' == $stat ) {
5793 if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
5794 $caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
5795 continue;
5796 }
5797 }
5798
5799 // Check PHP version
5800 if ( 'php-version' == $stat ) {
5801 if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
5802 $caution[ $stat ] = $value . " - min supported is 5.2.4";
5803 continue;
5804 }
5805 }
5806
5807 // Check ID crisis
5808 if ( 'identitycrisis' == $stat ) {
5809 if ( 'yes' == $value ) {
5810 $bad[ $stat ] = $value;
5811 continue;
5812 }
5813 }
5814
5815 // The rest are good :)
5816 $good[ $stat ] = $value;
5817 }
5818
5819 $filtered_data = array(
5820 'good' => $good,
5821 'caution' => $caution,
5822 'bad' => $bad
5823 );
5824
5825 return $filtered_data;
5826 }
5827
5828
5829 /*
5830 * This method is used to organize all options that can be reset
5831 * without disconnecting Jetpack.
5832 *
5833 * It is used in class.jetpack-cli.php to reset options
5834 *
5835 * @return array of options to delete.
5836 */
5837 public static function get_jetapck_options_for_reset() {
5838 $jetpack_options = Jetpack_Options::get_option_names();
5839 $jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
5840
5841 $all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat );
5842
5843 // A manual build of the wp options
5844 $wp_options = array(
5845 'sharing-options',
5846 'disabled_likes',
5847 'disabled_reblogs',
5848 'jetpack_comments_likes_enabled',
5849 'wp_mobile_excerpt',
5850 'wp_mobile_featured_images',
5851 'wp_mobile_app_promos',
5852 'stats_options',
5853 'stats_dashboard_widget',
5854 'safecss_preview_rev',
5855 'safecss_rev',
5856 'safecss_revision_migrated',
5857 'nova_menu_order',
5858 'jetpack_portfolio',
5859 'jetpack_portfolio_posts_per_page',
5860 'jetpack_testimonial',
5861 'jetpack_testimonial_posts_per_page',
5862 'wp_mobile_custom_css',
5863 'sharedaddy_disable_resources',
5864 'sharing-options',
5865 'sharing-services',
5866 'site_icon_temp_data',
5867 'featured-content',
5868 'site_logo',
5869 );
5870
5871 // Whitelist some Jetpack options
5872 $whitelist_terms = array(
5873 'id', // (int) The Client ID/WP.com Blog ID of this site.
5874 'master_user', // (int) The local User ID of the user who connected this site to jetpack.wordpress.com.
5875 'version', // (string) Used during upgrade procedure to auto-activate new modules. version:time
5876 'jumpstart', // (string) A flag for whether or not to show the Jump Start. Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
5877
5878 // non_compact
5879 'activated',
5880 );
5881
5882 // Remove the whitelisted Jetpack options
5883 foreach ( $whitelist_terms as $whitelist_term ) {
5884 if ( false !== ( $key = array_search( $whitelist_term, $all_jp_options ) ) ) {
5885 unset( $all_jp_options[ $key ] );
5886 }
5887 }
5888
5889 $options = array(
5890 'jp_options' => $all_jp_options,
5891 'wp_options' => $wp_options
5892 );
5893
5894 return $options;
5895 }
5896
5897 /*
5898 * Check if an option of a Jetpack module has been updated.
5899 *
5900 * If any module option has been updated before Jump Start has been dismissed,
5901 * update the 'jumpstart' option so we can hide Jump Start.
5902 */
5903 public static function jumpstart_has_updated_module_option( $option_name = '' ) {
5904 // Bail if Jump Start has already been dismissed
5905 if ( 'new_connection' !== Jetpack::get_option( 'jumpstart' ) ) {
5906 return false;
5907 }
5908
5909 $jetpack = Jetpack::init();
5910
5911
5912 // Manual build of module options
5913 $option_names = self::get_jetapck_options_for_reset();
5914
5915 if ( in_array( $option_name, $option_names['wp_options'] ) ) {
5916 Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
5917
5918 //Jump start is being dismissed send data to MC Stats
5919 $jetpack->stat( 'jumpstart', 'manual,'.$option_name );
5920
5921 $jetpack->do_stats( 'server_side' );
5922 }
5923
5924 }
5925
5926 /*
5927 * Strip http:// or https:// from a url, replaces forward slash with ::,
5928 * so we can bring them directly to their site in calypso.
5929 *
5930 * @param string | url
5931 * @return string | url without the guff
5932 */
5933 public static function build_raw_urls( $url ) {
5934 $strip_http = '/.*?:\/\//i';
5935 $url = preg_replace( $strip_http, '', $url );
5936 $url = str_replace( '/', '::', $url );
5937 return $url;
5938 }
5939
5940 /**
5941 * Stores and prints out domains to prefetch for page speed optimization.
5942 *
5943 * @param mixed $new_urls
5944 */
5945 public static function dns_prefetch( $new_urls = null ) {
5946 static $prefetch_urls = array();
5947 if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
5948 echo "\r\n";
5949 foreach ( $prefetch_urls as $this_prefetch_url ) {
5950 printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
5951 }
5952 } elseif ( ! empty( $new_urls ) ) {
5953 if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
5954 add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
5955 }
5956 foreach ( (array) $new_urls as $this_new_url ) {
5957 $prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
5958 }
5959 $prefetch_urls = array_unique( $prefetch_urls );
5960 }
5961 }
5962
5963 public function wp_dashboard_setup() {
5964 if ( self::is_active() ) {
5965 add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
5966 } elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
5967 add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
5968 }
5969
5970 if ( has_action( 'jetpack_dashboard_widget' ) ) {
5971 wp_add_dashboard_widget(
5972 'jetpack_summary_widget',
5973 __( 'Jetpack', 'jetpack' ),
5974 array( __CLASS__, 'dashboard_widget' )
5975 );
5976 wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
5977
5978 // If we're inactive and not in development mode, sort our box to the top.
5979 if ( ! self::is_active() && ! self::is_development_mode() ) {
5980 global $wp_meta_boxes;
5981
5982 $dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
5983 $ours = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
5984
5985 $wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
5986 }
5987 }
5988 }
5989
5990 /**
5991 * @param mixed $result Value for the user's option
5992 * @return mixed
5993 */
5994 function get_user_option_meta_box_order_dashboard( $sorted ) {
5995 if ( ! is_array( $sorted ) ) {
5996 return $sorted;
5997 }
5998
5999 foreach ( $sorted as $box_context => $ids ) {
6000 if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6001 // If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6002 continue;
6003 }
6004
6005 $ids_array = explode( ',', $ids );
6006 $key = array_search( 'dashboard_stats', $ids_array );
6007
6008 if ( false !== $key ) {
6009 // If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6010 $ids_array[ $key ] = 'jetpack_summary_widget';
6011 $sorted[ $box_context ] = implode( ',', $ids_array );
6012 // We've found it, stop searching, and just return.
6013 break;
6014 }
6015 }
6016
6017 return $sorted;
6018 }
6019
6020 public static function dashboard_widget() {
6021 do_action( 'jetpack_dashboard_widget' );
6022 }
6023
6024 public static function dashboard_widget_footer() {
6025 ?>
6026 <footer>
6027
6028 <div class="protect">
6029 <?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6030 <h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6031 <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>
6032 <?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6033 <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( 'Jetpack Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6034 <?php esc_html_e( 'Activate Jetpack Protect', 'jetpack' ); ?>
6035 </a>
6036 <?php else : ?>
6037 <?php esc_html_e( 'Jetpack Protect is inactive.', 'jetpack' ); ?>
6038 <?php endif; ?>
6039 </div>
6040
6041 <div class="akismet">
6042 <?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6043 <h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6044 <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>
6045 <?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6046 <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">
6047 <?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6048 </a>
6049 <?php else : ?>
6050 <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>
6051 <?php endif; ?>
6052 </div>
6053
6054 </footer>
6055 <?php
6056 }
6057
6058 public function dashboard_widget_connect_to_wpcom() {
6059 if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6060 return;
6061 }
6062 ?>
6063 <div class="wpcom-connect">
6064 <div class="jp-emblem">
6065 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0" y="0" viewBox="0 0 172.9 172.9" enable-background="new 0 0 172.9 172.9" xml:space="preserve">
6066 <path d="M86.4 0C38.7 0 0 38.7 0 86.4c0 47.7 38.7 86.4 86.4 86.4s86.4-38.7 86.4-86.4C172.9 38.7 134.2 0 86.4 0zM83.1 106.6l-27.1-6.9C49 98 45.7 90.1 49.3 84l33.8-58.5V106.6zM124.9 88.9l-33.8 58.5V66.3l27.1 6.9C125.1 74.9 128.4 82.8 124.9 88.9z"/>
6067 </svg>
6068 </div>
6069 <h3><?php esc_html_e( 'Boost traffic, enhance security, and improve performance.', 'jetpack' ); ?></h3>
6070 <p><?php esc_html_e( 'Jetpack connects your site to WordPress.com to give you traffic and customization tools, enhanced security, speed boosts, and more.', 'jetpack' ); ?></p>
6071
6072 <div class="actions">
6073 <a href="<?php echo $this->build_connect_url() ?>" class="button button-primary">
6074 <?php esc_html_e( 'Connect to WordPress.com', 'jetpack' ); ?>
6075 </a>
6076 <?php if ( current_user_can( 'activate_plugins' ) ) : ?>
6077 <small><a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=dismiss' ), 'jetpack-deactivate' ) ); ?>" title="Deactivate Jetpack">
6078 <?php esc_html_e( 'or, deactivate Jetpack', 'jetpack' ); ?>
6079 </a></small>
6080 <?php endif; ?>
6081 </div>
6082 </div>
6083 <?php
6084 }
6085
6086 /*
6087 * A graceful transition to using Core's site icon.
6088 *
6089 * All of the hard work has already been done with the image
6090 * in all_done_page(). All that needs to be done now is update
6091 * the option and display proper messaging.
6092 *
6093 * @todo remove when WP 4.3 is minimum
6094 *
6095 * @since 3.6.1
6096 *
6097 * @return bool false = Core's icon not available || true = Core's icon is available
6098 */
6099 public static function jetpack_site_icon_available_in_core() {
6100 global $wp_version;
6101 $core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
6102
6103 if ( ! $core_icon_available ) {
6104 return false;
6105 }
6106
6107 // No need for Jetpack's site icon anymore if core's is already set
6108 if ( has_site_icon() ) {
6109 if ( Jetpack::is_module_active( 'site-icon' ) ) {
6110 Jetpack::log( 'deactivate', 'site-icon' );
6111 Jetpack::deactivate_module( 'site-icon' );
6112 }
6113 return true;
6114 }
6115
6116 // Transfer Jetpack's site icon to use core.
6117 $site_icon_id = Jetpack::get_option( 'site_icon_id' );
6118 if ( $site_icon_id ) {
6119 // Update core's site icon
6120 update_option( 'site_icon', $site_icon_id );
6121
6122 // Delete Jetpack's icon option. We still want the blavatar and attached data though.
6123 delete_option( 'site_icon_id' );
6124 }
6125
6126 // No need for Jetpack's site icon anymore
6127 if ( Jetpack::is_module_active( 'site-icon' ) ) {
6128 Jetpack::log( 'deactivate', 'site-icon' );
6129 Jetpack::deactivate_module( 'site-icon' );
6130 }
6131
6132 return true;
6133 }
6134
6135 }
6136