PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 2.1.7
Jetpack – WP Security, Backup, Speed, & Growth v2.1.7
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 / jetpack.php
jetpack.php
4,531 lines 150.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /*
4 * Plugin Name: Jetpack by WordPress.com
5 * Plugin URI: http://wordpress.org/extend/plugins/jetpack/
6 * Description: Bring the power of the WordPress.com cloud to your self-hosted WordPress. Jetpack enables you to connect your blog to a WordPress.com account to use the powerful features normally only available to WordPress.com users.
7 * Author: Automattic
8 * Version: 2.1.7
9 * Author URI: http://jetpack.me
10 * License: GPL2+
11 * Text Domain: jetpack
12 * Domain Path: /languages/
13 */
14
15 defined( 'JETPACK__API_BASE' ) or define( 'JETPACK__API_BASE', 'https://jetpack.wordpress.com/jetpack.' );
16 define( 'JETPACK__API_VERSION', 1 );
17 define( 'JETPACK__MINIMUM_WP_VERSION', '3.3' );
18 defined( 'JETPACK_CLIENT__AUTH_LOCATION' ) or define( 'JETPACK_CLIENT__AUTH_LOCATION', 'header' );
19 defined( 'JETPACK_CLIENT__HTTPS' ) or define( 'JETPACK_CLIENT__HTTPS', 'AUTO' );
20 define( 'JETPACK__VERSION', '2.1.7' );
21 define( 'JETPACK__PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
22 defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) or define( 'JETPACK__GLOTPRESS_LOCALES_PATH', JETPACK__PLUGIN_DIR . 'locales.php' );
23
24 define( 'JETPACK_MASTER_USER', true );
25
26 /*
27 Options:
28 jetpack_options (array)
29 An array of options.
30 @see Jetpack::get_option_names()
31
32 jetpack_register (string)
33 Temporary verification secrets.
34
35 jetpack_activated (int)
36 1: the plugin was activated normally
37 2: the plugin was activated on this site because of a network-wide activation
38 3: the plugin was auto-installed
39 4: the plugin was manually disconnected (but is still installed)
40
41 jetpack_active_modules (array)
42 Array of active module slugs.
43
44 jetpack_do_activate (bool)
45 Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
46 */
47
48 class Jetpack {
49 var $xmlrpc_server = null;
50
51 private $xmlrpc_verification = null;
52
53 var $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
54
55 var $plugins_to_deactivate = array(
56 'stats' => array( 'stats/stats.php', 'WordPress.com Stats' ),
57 'shortlinks' => array( 'stats/stats.php', 'WordPress.com Stats' ),
58 'sharedaddy' => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
59 'twitter-widget' => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
60 'after-the-deadline' => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
61 'contact-form' => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
62 'custom-css' => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
63 );
64
65 var $capability_translations = array(
66 'administrator' => 'manage_options',
67 'editor' => 'edit_others_posts',
68 'author' => 'publish_posts',
69 'contributor' => 'edit_posts',
70 'subscriber' => 'read',
71 );
72
73 /**
74 * Message to display in admin_notice
75 * @var string
76 */
77 var $message = '';
78
79 /**
80 * Error to display in admin_notice
81 * @var string
82 */
83 var $error = '';
84
85 /**
86 * Modules that need more privacy description.
87 * @var string
88 */
89 var $privacy_checks = '';
90
91 /**
92 * Stats to record once the page loads
93 *
94 * @var array
95 */
96 var $stats = array();
97
98 /**
99 * Jetpack_Sync object
100 */
101 var $sync;
102
103 /**
104 * Verified data for JSON authorization request
105 */
106 var $json_api_authorization_request = array();
107
108 /**
109 * Singleton
110 * @static
111 */
112 public static function init() {
113 static $instance = false;
114
115 if ( !$instance ) {
116 load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
117 $instance = new Jetpack;
118
119 $instance->plugin_upgrade();
120 }
121
122 return $instance;
123 }
124
125 /**
126 * Must never be called statically
127 */
128 function plugin_upgrade() {
129 // Upgrade: 1.1 -> 1.2
130 if ( get_option( 'jetpack_id' ) ) {
131 // Move individual jetpack options to single array of options
132 $options = array();
133 foreach ( Jetpack::get_option_names() as $option ) {
134 if ( false !== $value = get_option( "jetpack_$option" ) ) {
135 $options[$option] = $value;
136 }
137 }
138
139 if ( $options ) {
140 Jetpack::update_options( $options );
141
142 foreach ( array_keys( $options ) as $option ) {
143 delete_option( "jetpack_$option" );
144 }
145 }
146
147 // Add missing version and old_version options
148 if ( !$version = Jetpack::get_option( 'version' ) ) {
149 $version = $old_version = '1.1:' . time();
150 Jetpack::update_options( compact( 'version', 'old_version' ) );
151 }
152 }
153
154 // Upgrade from a single user token to a user_id-indexed array and a master_user ID
155 if ( !Jetpack::get_option( 'user_tokens' ) ) {
156 if ( $user_token = Jetpack::get_option( 'user_token' ) ) {
157 $token_parts = explode( '.', $user_token );
158 if ( isset( $token_parts[2] ) ) {
159 $master_user = $token_parts[2];
160 $user_tokens = array( $master_user => $user_token );
161 Jetpack::update_options( compact( 'master_user', 'user_tokens' ) );
162 Jetpack::delete_option( 'user_token' );
163 } else {
164 // @todo: is this even possible?
165 trigger_error( sprintf( 'Jetpack::plugin_upgrade found no user_id in user_token "%s"', $user_token ), E_USER_WARNING );
166 }
167 }
168 }
169 }
170
171 /**
172 * Constructor. Initializes WordPress hooks
173 */
174 function Jetpack() {
175 $this->sync = new Jetpack_Sync;
176
177 // Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
178 // We access the "internal" method here only because the Jetpack object isn't instantiated yet
179 $this->sync->options( __FILE__,
180 'home',
181 'siteurl',
182 'blogname',
183 'gmt_offset',
184 'timezone_string'
185 );
186
187 if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
188 @ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
189
190 require_once dirname( __FILE__ ) . '/class.jetpack-xmlrpc-server.php';
191 $this->xmlrpc_server = new Jetpack_XMLRPC_Server();
192
193 $this->require_jetpack_authentication();
194
195 if ( Jetpack::is_active() ) {
196 // Hack to preserve $HTTP_RAW_POST_DATA
197 add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
198
199 $signed = $this->verify_xml_rpc_signature();
200 if ( $signed && ! is_wp_error( $signed ) ) {
201 // The actual API methods.
202 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
203 } else {
204 add_filter( 'xmlrpc_methods', '__return_empty_array' );
205 }
206 } else {
207 // The bootstrap API methods.
208 add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
209 }
210
211 // Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
212 add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
213 } elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
214 $this->require_jetpack_authentication();
215 $this->add_remote_request_handlers();
216 } else {
217 if ( Jetpack::is_active() ) {
218 add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
219 }
220 }
221
222 add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
223 if ( !wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
224 wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
225 }
226
227 add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
228
229 add_action( 'admin_menu', array( $this, 'admin_menu' ) );
230 add_action( 'admin_init', array( $this, 'admin_init' ) );
231 add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
232
233 add_action( 'wp_ajax_jetpack-check-news-subscription', array( $this, 'check_news_subscription' ) );
234 add_action( 'wp_ajax_jetpack-subscribe-to-news', array( $this, 'subscribe_to_news' ) );
235
236 add_action( 'wp_loaded', array( $this, 'register_assets' ) );
237 add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
238 add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
239 add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
240
241 add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
242
243 add_action( 'plugins_loaded', array( $this, 'check_open_graph' ), 999 );
244 }
245
246 function require_jetpack_authentication() {
247 // Don't let anyone authenticate
248 $_COOKIE = array();
249 remove_all_filters( 'authenticate' );
250
251 if ( Jetpack::is_active() ) {
252 // Allow Jetpack authentication
253 add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
254 }
255 }
256
257 /**
258 * Register assets for use in various modules and the Jetpack admin page.
259 *
260 * @uses wp_script_is, wp_register_script, plugins_url
261 * @action wp_loaded
262 * @return null
263 */
264 public function register_assets() {
265 if ( ! wp_script_is( 'spin', 'registered' ) )
266 wp_register_script( 'spin', plugins_url( '_inc/spin.js', __FILE__ ), false, '1.2.4' );
267
268 if ( ! wp_script_is( 'jquery.spin', 'registered' ) )
269 wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', __FILE__ ) , array( 'jquery', 'spin' ) );
270
271 if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) )
272 wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', __FILE__ ), array( 'media-views' ), '20121225' );
273 }
274
275 /**
276 * Device Pixels support
277 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
278 */
279 function devicepx() {
280 wp_enqueue_script( 'devicepx', ( is_ssl() ? 'https' : 'http' ) . '://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate('oW'), true );
281 }
282
283 /**
284 * Is Jetpack active?
285 */
286 public static function is_active() {
287 return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
288 }
289
290 /**
291 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
292 */
293 public static function is_user_connected( $user_id = false ) {
294 $user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
295 if ( !$user_id ) {
296 return false;
297 }
298 return (bool) Jetpack_Data::get_access_token( $user_id );
299 }
300
301 function current_user_is_connection_owner() {
302 $user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
303 return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
304 }
305
306 /**
307 * Synchronize connected user role changes
308 */
309 function user_role_change( $user_id ) {
310 if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
311
312 $current_user_id = get_current_user_id();
313 wp_set_current_user( $user_id );
314 $role = $this->translate_current_user_to_role();
315 $signed_role = $this->sign_role( $role );
316 wp_set_current_user( $current_user_id );
317
318 $master_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
319 $master_user_id = absint( $master_token->external_user_id );
320
321 if ( !$master_user_id )
322 return; // this shouldn't happen
323
324 Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
325 //@todo retry on failure
326
327 //try to choose a new master if we're demoting the current one
328 if ( $user_id == $master_user_id && 'administrator' != $role ) {
329 $query = new WP_User_Query( array(
330 'fields' => array( 'id' ),
331 'role' => 'administrator',
332 'orderby' => 'id',
333 'exclude' => array( $master_user_id ),
334 )
335 );
336 $new_master = false;
337 foreach ( $query->results as $result ) {
338 $uid = absint( $result->id );
339 if ( $uid && Jetpack::is_user_connected( $uid ) ) {
340 $new_master = $uid;
341 break;
342 }
343 }
344
345 if ( $new_master ) {
346 Jetpack::update_option( 'master_user', $new_master );
347 }
348 // else disconnect..?
349 }
350 }
351 }
352
353 /**
354 * Loads the currently active modules.
355 */
356 public static function load_modules() {
357 if ( !Jetpack::is_active() ) {
358 return;
359 }
360
361 $version = Jetpack::get_option( 'version' );
362 if ( !$version ) {
363 $version = $old_version = JETPACK__VERSION . ':' . time();
364 Jetpack::update_options( compact( 'version', 'old_version' ) );
365 }
366 list( $version ) = explode( ':', $version );
367
368 $modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
369
370 // Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
371 if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
372 $updated_modules = array();
373 foreach ( $modules as $module ) {
374 $module_data = Jetpack::get_module( $module );
375 if ( !isset( $module_data['changed'] ) ) {
376 continue;
377 }
378
379 if ( version_compare( $module_data['changed'], $version, '<=' ) ) {
380 continue;
381 }
382
383 $updated_modules[] = $module;
384 }
385
386 $modules = array_diff( $modules, $updated_modules );
387 }
388
389 foreach ( $modules as $module ) {
390 if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
391 continue;
392 }
393 require Jetpack::get_module_path( $module );
394 do_action( 'jetpack_module_loaded_' . $module );
395 }
396
397 do_action( 'jetpack_modules_loaded' );
398
399 // 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.
400 require_once( dirname( __FILE__ ) . '/modules/module-extras.php' );
401 }
402
403 /**
404 * Check if Jetpack's Open Graph tags should be used.
405 * If certain plugins are active, Jetpack's og tags are suppressed.
406 *
407 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
408 * @action plugins_loaded
409 * @return null
410 */
411 public function check_open_graph() {
412 if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) )
413 add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
414
415 $active_plugins = get_option( 'active_plugins', array() );
416
417 $conflicting_plugins = array(
418 'facebook/facebook.php', // Official Facebook plugin
419 'wordpress-seo/wp-seo.php', // WordPress SEO by Yoast
420 'add-link-to-facebook/add-link-to-facebook.php', // Add Link to Facebook
421 'facebook-awd/AWD_facebook.php', // Facebook AWD All in one
422 'header-footer/plugin.php', // Header and Footer
423 'nextgen-facebook/nextgen-facebook.php', // NextGEN Facebook OG
424 'seo-facebook-comments/seofacebook.php', // SEO Facebook Comments
425 'seo-ultimate/seo-ultimate.php', // SEO Ultimate
426 'sexybookmarks/sexy-bookmarks.php', // Shareaholic
427 'shareaholic/sexy-bookmarks.php', // Shareaholic
428 'social-discussions/social-discussions.php', // Social Discussions
429 'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php', // NextScripts SNAP
430 'wordbooker/wordbooker.php', // Wordbooker
431 'socialize/socialize.php', // Socialize
432 'simple-facebook-connect/sfc.php', // Simple Facebook Connect
433 'social-sharing-toolkit/social_sharing_toolkit.php', // Social Sharing Toolkit
434 'wp-facebook-open-graph-protocol/wp-facebook-ogp.php', // WP Facebook Open Graph protocol
435 'opengraph/opengraph.php', // Open Graph
436 'sharepress/sharepress.php', // SharePress
437 );
438
439 foreach ( $conflicting_plugins as $plugin ) {
440 if ( in_array( $plugin, $active_plugins ) ) {
441 add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
442 break;
443 }
444 }
445
446 if ( apply_filters( 'jetpack_enable_open_graph', false ) )
447 require_once dirname( __FILE__ ) . '/functions.opengraph.php';
448 }
449
450 /* Jetpack Options API */
451
452 public static function get_option_names( $type = 'compact' ) {
453 switch ( $type ) {
454 case 'non-compact' :
455 case 'non_compact' :
456 return array(
457 'register',
458 'activated',
459 'active_modules',
460 'do_activate',
461 'publicize',
462 );
463 }
464
465 return array(
466 'id', // (int) The Client ID/WP.com Blog ID of this site.
467 'blog_token', // (string) The Client Secret/Blog Token of this site.
468 'user_token', // (string) The User Token of this site. (deprecated)
469 'publicize_connections', // (array) An array of Publicize connections from WordPress.com
470 'master_user', // (int) The local User ID of the user who connected this site to jetpack.wordpress.com.
471 'user_tokens', // (array) User Tokens for each user of this site who has connected to jetpack.wordpress.com.
472 'version', // (string) Used during upgrade procedure to auto-activate new modules. version:time
473 'old_version', // (string) Used to determine which modules are the most recently added. previous_version:time
474 'fallback_no_verify_ssl_certs', // (int) Flag for determining if this host must skip SSL Certificate verification due to misconfigured SSL.
475 'time_diff', // (int) Offset between Jetpack server's clocks and this server's clocks. Jetpack Server Time = time() + (int) Jetpack::get_option( 'time_diff' )
476 'public', // (int|bool) If we think this site is public or not (1, 0), false if we haven't yet tried to figure it out.
477 );
478 }
479
480 /**
481 * Returns the requested option. Looks in jetpack_options or jetpack_$name as appropriate.
482 *
483 * @param string $name Option name
484 * @param mixed $default (optional)
485 */
486 public static function get_option( $name, $default = false ) {
487 if ( in_array( $name, Jetpack::get_option_names( 'non_compact' ) ) ) {
488 return get_option( "jetpack_$name" );
489 } else if ( !in_array( $name, Jetpack::get_option_names() ) ) {
490 trigger_error( sprintf( 'Invalid Jetpack option name: %s', $name ), E_USER_WARNING );
491 return false;
492 }
493
494 $options = get_option( 'jetpack_options' );
495 if ( is_array( $options ) && isset( $options[$name] ) ) {
496 return $options[$name];
497 }
498
499 return $default;
500 }
501
502 /**
503 * Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
504 * Does some extra verification so urls (such as those to public-api, register, etc) cant just be crafted
505 * $name must be a registered option name.
506 */
507 public static function create_nonce( $name ) {
508 $secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
509
510 Jetpack::update_option( $name, $secret );
511 @list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack::get_option( $name ) );
512 if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
513 return new Jetpack_Error( 'missing_secrets' );
514
515 return array(
516 'secret_1' => $secret_1,
517 'secret_2' => $secret_2,
518 'eol' => $eol,
519 );
520 }
521
522 /**
523 * Updates the single given option. Updates jetpack_options or jetpack_$name as appropriate.
524 *
525 * @param string $name Option name
526 * @param mixed $value Option value
527 */
528 public static function update_option( $name, $value ) {
529 if ( in_array( $name, Jetpack::get_option_names( 'non_compact' ) ) ) {
530 return update_option( "jetpack_$name", $value );
531 } else if ( !in_array( $name, Jetpack::get_option_names() ) ) {
532 trigger_error( sprintf( 'Invalid Jetpack option name: %s', $name ), E_USER_WARNING );
533 return false;
534 }
535
536 $options = get_option( 'jetpack_options' );
537 if ( !is_array( $options ) ) {
538 $options = array();
539 }
540
541 $options[$name] = $value;
542
543 return update_option( 'jetpack_options', $options );
544 }
545
546 /**
547 * Updates the multiple given options. Updates jetpack_options and/or jetpack_$name as appropriate.
548 *
549 * @param array $array array( option name => option value, ... )
550 */
551 public static function update_options( $array ) {
552 $names = array_keys( $array );
553
554 foreach ( array_diff( $names, Jetpack::get_option_names(), Jetpack::get_option_names( 'non_compact' ) ) as $unknown_name ) {
555 trigger_error( sprintf( 'Invalid Jetpack option name: %s', $unknown_name ), E_USER_WARNING );
556 unset( $array[$unknown_name] );
557 }
558
559 foreach ( array_intersect( $names, Jetpack::get_option_names( 'non_compact' ) ) as $name ) {
560 update_option( "jetpack_$name", $array[$name] );
561 unset( $array[$name] );
562 }
563
564 $options = get_option( 'jetpack_options' );
565 if ( !is_array( $options ) ) {
566 $options = array();
567 }
568
569 return update_option( 'jetpack_options', array_merge( $options, $array ) );
570 }
571
572 /**
573 * Deletes the given option. May be passed multiple option names as an array.
574 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
575 *
576 * @param string|array $names
577 */
578 public static function delete_option( $names ) {
579 $names = (array) $names;
580
581 foreach ( array_diff( $names, Jetpack::get_option_names(), Jetpack::get_option_names( 'non_compact' ) ) as $unknown_name ) {
582 trigger_error( sprintf( 'Invalid Jetpack option name: %s', $unknown_name ), E_USER_WARNING );
583 }
584
585 foreach ( array_intersect( $names, Jetpack::get_option_names( 'non_compact' ) ) as $name ) {
586 delete_option( "jetpack_$name" );
587 }
588
589 $options = get_option( 'jetpack_options' );
590 if ( !is_array( $options ) ) {
591 $options = array();
592 }
593
594 $to_delete = array_intersect( $names, Jetpack::get_option_names(), array_keys( $options ) );
595 if ( $to_delete ) {
596 foreach ( $to_delete as $name ) {
597 unset( $options[$name] );
598 }
599
600 return update_option( 'jetpack_options', $options );
601 }
602
603 return true;
604 }
605
606 /**
607 * Enters a user token into the user_tokens option
608 *
609 * @param int $user_id
610 * @param string $token
611 * return bool
612 */
613 public static function update_user_token( $user_id, $token, $is_master_user ) {
614 // not designed for concurrent updates
615 $user_tokens = Jetpack::get_option( 'user_tokens' );
616 if ( ! is_array( $user_tokens ) )
617 $user_tokens = array();
618 $user_tokens[$user_id] = $token;
619 if ( $is_master_user ) {
620 $master_user = $user_id;
621 $options = compact('user_tokens', 'master_user');
622 } else {
623 $options = compact('user_tokens');
624 }
625 return Jetpack::update_options( $options );
626 }
627
628 /**
629 * Returns an array of all PHP files in the specified absolute path.
630 * Equivalent to glob( "$absolute_path/*.php" ).
631 *
632 * @param string $absolute_path The absolute path of the directory to search.
633 * @return array Array of absolute paths to the PHP files.
634 */
635 public static function glob_php( $absolute_path ) {
636 $absolute_path = untrailingslashit( $absolute_path );
637 $files = array();
638 if ( !$dir = @opendir( $absolute_path ) ) {
639 return $files;
640 }
641
642 while ( false !== $file = readdir( $dir ) ) {
643 if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
644 continue;
645 }
646
647 $file = "$absolute_path/$file";
648
649 if ( !is_file( $file ) ) {
650 continue;
651 }
652
653 $files[] = $file;
654 }
655
656 closedir( $dir );
657
658 return $files;
659 }
660
661 public function activate_new_modules() {
662 if ( ! Jetpack::is_active() ) {
663 return;
664 }
665
666 $jetpack_old_version = Jetpack::get_option( 'version' ); // [sic]
667 if ( !$jetpack_old_version ) {
668 $jetpack_old_version = $version = $old_version = '1.1:' . time();
669 Jetpack::update_options( compact( 'version', 'old_version' ) );
670 }
671
672 list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
673
674 if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
675 return;
676 }
677
678 $active_modules = Jetpack::get_active_modules();
679 $reactivate_modules = array();
680 foreach ( $active_modules as $active_module ) {
681 $module = Jetpack::get_module( $active_module );
682 if ( !isset( $module['changed'] ) ) {
683 continue;
684 }
685
686 if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
687 continue;
688 }
689
690 $reactivate_modules[] = $active_module;
691 Jetpack::deactivate_module( $active_module );
692 }
693
694 if ( version_compare( $jetpack_version, '1.9.2', '<' ) && version_compare( '1.9-something', JETPACK__VERSION, '<' ) ) {
695 add_action( 'jetpack_activate_default_modules', array( $this->sync, 'sync_all_registered_options' ), 1000 );
696 }
697
698 Jetpack::update_options( array(
699 'version' => JETPACK__VERSION . ':' . time(),
700 'old_version' => $jetpack_old_version,
701 ) );
702
703 Jetpack::state( 'message', 'modules_activated' );
704 Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
705 wp_safe_redirect( Jetpack::admin_url() );
706 exit;
707 }
708
709 /**
710 * List available Jetpack modules. Simply lists .php files in /modules/.
711 * Make sure to tuck away module "library" files in a sub-directory.
712 */
713 public static function get_available_modules( $min_version = false, $max_version = false ) {
714 static $modules = null;
715
716 if ( !isset( $modules ) ) {
717 $files = Jetpack::glob_php( dirname( __FILE__ ) . '/modules' );
718
719 $modules = array();
720
721 foreach ( $files as $file ) {
722 if ( !$headers = Jetpack::get_module( $file ) ) {
723 continue;
724 }
725
726 $modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
727 }
728 }
729
730 if ( !$min_version && !$max_version ) {
731 return array_keys( $modules );
732 }
733
734 $r = array();
735 foreach ( $modules as $slug => $introduced ) {
736 if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
737 continue;
738 }
739
740 if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
741 continue;
742 }
743
744 $r[] = $slug;
745 }
746
747 return $r;
748 }
749
750 /**
751 * Default modules loaded on activation.
752 */
753 public static function get_default_modules( $min_version = false, $max_version = false ) {
754 $return = array();
755
756 foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
757 // Add special cases here for modules to avoid auto-activation
758 switch ( $module ) {
759
760 // These modules are default off: they change things blog-side
761 case 'comments' :
762 case 'carousel' :
763 case 'minileven':
764 case 'infinite-scroll' :
765 case 'photon' :
766 case 'tiled-gallery' :
767 break;
768
769 // These modules are default off if we think the site is a private one
770 case 'enhanced-distribution' :
771 case 'json-api' :
772 if ( !Jetpack::get_option( 'public' ) ) {
773 break;
774 }
775 // else no break
776 // The rest are default on
777 default :
778 $return[] = $module;
779 }
780 }
781
782 return $return;
783 }
784
785 /**
786 * Extract a module's slug from its full path.
787 */
788 public static function get_module_slug( $file ) {
789 return str_replace( '.php', '', basename( $file ) );
790 }
791
792 /**
793 * Generate a module's path from its slug.
794 */
795 public static function get_module_path( $slug ) {
796 return dirname( __FILE__ ) . "/modules/$slug.php";
797 }
798
799 /**
800 * Load module data from module file. Headers differ from WordPress
801 * plugin headers to avoid them being identified as standalone
802 * plugins on the WordPress plugins page.
803 */
804 public static function get_module( $module ) {
805 $headers = array(
806 'name' => 'Module Name',
807 'description' => 'Module Description',
808 'sort' => 'Sort Order',
809 'introduced' => 'First Introduced',
810 'changed' => 'Major Changes In',
811 'deactivate' => 'Deactivate',
812 'free' => 'Free',
813 );
814
815 $file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
816 if ( !file_exists( $file ) )
817 return false;
818
819 $mod = get_file_data( $file, $headers );
820 if ( empty( $mod['name'] ) )
821 return false;
822
823 $mod['name'] = translate( $mod['name'], 'jetpack' );
824 $mod['description'] = translate( $mod['description'], 'jetpack' );
825 if ( empty( $mod['sort'] ) )
826 $mod['sort'] = 10;
827 $mod['deactivate'] = empty( $mod['deactivate'] );
828 $mod['free'] = empty( $mod['free'] );
829 return $mod;
830 }
831
832 /**
833 * Get a list of activated modules as an array of module slugs.
834 */
835 public static function get_active_modules() {
836 $active = Jetpack::get_option( 'active_modules' );
837 if ( !is_array( $active ) )
838 $active = array();
839 if ( is_admin() ) {
840 $active[] = 'vaultpress';
841 } else {
842 $active = array_diff( $active, array( 'vaultpress' ) );
843 }
844 return array_unique( $active );
845 }
846
847 public static function is_module( $module ) {
848 return !empty( $module ) && !validate_file( $module, Jetpack::get_available_modules() );
849 }
850
851 /**
852 * Catches PHP errors. Must be used in conjunction with output buffering.
853 *
854 * @param bool $catch True to start catching, False to stop.
855 *
856 * @static
857 */
858 public static function catch_errors( $catch ) {
859 static $display_errors, $error_reporting;
860
861 if ( $catch ) {
862 $display_errors = @ini_set( 'display_errors', 1 );
863 $error_reporting = @error_reporting( E_ALL );
864 add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
865 } else {
866 @ini_set( 'display_errors', $display_errors );
867 @error_reporting( $error_reporting );
868 remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 1 );
869 }
870 }
871
872 /**
873 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
874 */
875 public static function catch_errors_on_shutdown() {
876 Jetpack::state( 'php_errors', ob_get_clean() );
877 }
878
879 public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array() ) {
880 $jetpack = Jetpack::init();
881
882 $modules = Jetpack::get_default_modules( $min_version, $max_version );
883 $modules = array_merge( $other_modules, $modules );
884
885 // Look for standalone plugins and disable if active.
886
887 $to_deactivate = array();
888 foreach ( $modules as $module ) {
889 if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
890 $to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
891 }
892 }
893
894 $deactivated = array();
895 foreach ( $to_deactivate as $module => $deactivate_me ) {
896 list( $probable_file, $probable_title ) = $deactivate_me;
897 if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
898 $deactivated[] = $module;
899 }
900 }
901
902 if ( $deactivated ) {
903 Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
904
905 $url = add_query_arg( array(
906 'action' => 'activate_default_modules',
907 '_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
908 ), add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url() ) );
909 wp_safe_redirect( $url );
910 exit;
911 }
912
913 do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
914
915 // Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
916 $redirect = menu_page_url( 'jetpack', false );
917 Jetpack::restate();
918 Jetpack::catch_errors( true );
919 foreach ( $modules as $module ) {
920 $active = Jetpack::get_active_modules();
921 if ( in_array( $module, $active ) ) {
922 $module_info = Jetpack::get_module( $module );
923 if ( !$module_info['deactivate'] ) {
924 $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
925 if ( $active_state = Jetpack::state( $state ) ) {
926 $active_state = explode( ',', $active_state );
927 } else {
928 $active_state = array();
929 }
930 $active_state[] = $module;
931 Jetpack::state( $state, implode( ',', $active_state ) );
932 }
933 continue;
934 }
935
936 $file = Jetpack::get_module_path( $module );
937 if ( !file_exists( $file ) ) {
938 continue;
939 }
940
941 // we'll override this later if the plugin can be included without fatal error
942 wp_safe_redirect( Jetpack::admin_url() );
943 Jetpack::state( 'error', 'module_activation_failed' );
944 Jetpack::state( 'module', $module );
945 ob_start();
946 require $file;
947 do_action( 'jetpack_activate_module', $module );
948 $active[] = $module;
949 $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
950 if ( $active_state = Jetpack::state( $state ) ) {
951 $active_state = explode( ',', $active_state );
952 } else {
953 $active_state = array();
954 }
955 $active_state[] = $module;
956 Jetpack::state( $state, implode( ',', $active_state ) );
957 Jetpack::update_option( 'active_modules', array_unique( $active ) );
958 ob_end_clean();
959 }
960 Jetpack::state( 'error', false );
961 Jetpack::state( 'module', false );
962 Jetpack::catch_errors( false );
963 do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
964 }
965
966 public static function activate_module( $module ) {
967 $jetpack = Jetpack::init();
968
969 if ( !Jetpack::is_active() )
970 return false;
971
972 if ( !strlen( $module ) )
973 return false;
974
975 if ( !Jetpack::is_module( $module ) )
976 return false;
977
978 // If it's already active, then don't do it again
979 $active = Jetpack::get_active_modules();
980 foreach ( $active as $act ) {
981 if ( $act == $module )
982 return true;
983 }
984
985 // Check and see if the old plugin is active
986 if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
987 // Deactivate the old plugin
988 if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[$module][0], $jetpack->plugins_to_deactivate[$module][1] ) ) {
989 // If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
990 // We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
991 Jetpack::state( 'deactivated_plugins', $module );
992 wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
993 exit;
994 }
995 }
996
997 // Check the file for fatal errors, a la wp-admin/plugins.php::activate
998 Jetpack::state( 'module', $module );
999 Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
1000 wp_safe_redirect( Jetpack::admin_url() );
1001
1002 Jetpack::catch_errors( true );
1003 ob_start();
1004 require Jetpack::get_module_path( $module );
1005 do_action( 'jetpack_activate_module', $module );
1006 $active[] = $module;
1007 Jetpack::update_option( 'active_modules', array_unique( $active ) );
1008 Jetpack::state( 'error', false ); // the override
1009 Jetpack::state( 'message', 'module_activated' );
1010 Jetpack::state( 'module', $module );
1011 ob_end_clean();
1012 Jetpack::catch_errors( false );
1013 exit;
1014 }
1015
1016 function activate_module_actions( $module ) {
1017 do_action( "jetpack_activate_module_$module" );
1018
1019 $this->sync->sync_all_module_options( $module );
1020 }
1021
1022 public static function deactivate_module( $module ) {
1023 $active = Jetpack::get_active_modules();
1024 $new = array();
1025 foreach ( $active as $check ) {
1026 if ( !empty( $check ) && $module != $check )
1027 $new[] = $check;
1028 }
1029
1030 do_action( "jetpack_deactivate_module_$module" );
1031 return Jetpack::update_option( 'active_modules', array_unique( $new ) );
1032 }
1033
1034 public static function enable_module_configurable( $module ) {
1035 $module = Jetpack::get_module_slug( $module );
1036 add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
1037 }
1038
1039 public static function module_configuration_url( $module ) {
1040 $module = Jetpack::get_module_slug( $module );
1041 return Jetpack::admin_url( array( 'configure' => $module ) );
1042 }
1043
1044 public static function module_configuration_load( $module, $method ) {
1045 $module = Jetpack::get_module_slug( $module );
1046 add_action( 'jetpack_module_configuration_load_' . $module, $method );
1047 }
1048
1049 public static function module_configuration_head( $module, $method ) {
1050 $module = Jetpack::get_module_slug( $module );
1051 add_action( 'jetpack_module_configuration_head_' . $module, $method );
1052 }
1053
1054 public static function module_configuration_screen( $module, $method ) {
1055 $module = Jetpack::get_module_slug( $module );
1056 add_action( 'jetpack_module_configuration_screen_' . $module, $method );
1057 }
1058
1059 /* Installation */
1060
1061 public static function bail_on_activation( $message, $deactivate = true ) {
1062 ?>
1063 <!doctype html>
1064 <html>
1065 <head>
1066 <meta charset="<?php bloginfo( 'charset' ); ?>">
1067 <style>
1068 * {
1069 text-align: center;
1070 margin: 0;
1071 padding: 0;
1072 font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
1073 }
1074 p {
1075 margin-top: 1em;
1076 font-size: 18px;
1077 }
1078 </style>
1079 <body>
1080 <p><?php echo esc_html( $message ); ?></p>
1081 </body>
1082 </html>
1083 <?php
1084 if ( $deactivate ) {
1085 $plugins = get_option( 'active_plugins' );
1086 $jetpack = plugin_basename( __FILE__ );
1087 $update = false;
1088 foreach ( $plugins as $i => $plugin ) {
1089 if ( $plugin === $jetpack ) {
1090 $plugins[$i] = false;
1091 $update = true;
1092 }
1093 }
1094
1095 if ( $update ) {
1096 update_option( 'active_plugins', array_filter( $plugins ) );
1097 }
1098 }
1099 exit;
1100 }
1101
1102 /**
1103 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
1104 * @static
1105 */
1106 public static function plugin_activation( $network_wide ) {
1107 Jetpack::update_option( 'activated', 1 );
1108
1109 if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
1110 Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
1111 }
1112
1113 if ( $network_wide )
1114 Jetpack::state( 'network_nag', true );
1115
1116 Jetpack::plugin_initialize();
1117 }
1118
1119 /**
1120 * Sets the internal version number and activation state.
1121 * @static
1122 */
1123 public static function plugin_initialize() {
1124 if ( !Jetpack::get_option( 'activated' ) ) {
1125 Jetpack::update_option( 'activated', 2 );
1126 }
1127
1128 if ( !Jetpack::get_option( 'version' ) ) {
1129 $version = $old_version = JETPACK__VERSION . ':' . time();
1130 Jetpack::update_options( compact( 'version', 'old_version' ) );
1131 }
1132
1133 Jetpack::load_modules();
1134
1135 Jetpack::delete_option( 'do_activate' );
1136 }
1137
1138 /**
1139 * Removes all connection options
1140 * @static
1141 */
1142 public static function plugin_deactivation( $network_wide ) {
1143 Jetpack::disconnect( false );
1144 }
1145
1146 /**
1147 * Disconnects from the Jetpack servers.
1148 * Forgets all connection details and tells the Jetpack servers to do the same.
1149 * @static
1150 */
1151 public static function disconnect( $update_activated_state = true ) {
1152 wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
1153 Jetpack::clean_nonces( true );
1154
1155 Jetpack::load_xml_rpc_client();
1156 $xml = new Jetpack_IXR_Client();
1157 $xml->query( 'jetpack.deregister' );
1158
1159 Jetpack::delete_option( array(
1160 'register',
1161 'blog_token',
1162 'user_token',
1163 'user_tokens',
1164 'master_user',
1165 'time_diff',
1166 'fallback_no_verify_ssl_certs',
1167 ) );
1168
1169 if ( $update_activated_state ) {
1170 Jetpack::update_option( 'activated', 4 );
1171 }
1172 }
1173
1174 /**
1175 * Unlinks the current user from the linked WordPress.com user
1176 */
1177 function unlink_user() {
1178 if ( !$tokens = Jetpack::get_option( 'user_tokens' ) )
1179 return false;
1180
1181 $user_id = get_current_user_id();
1182
1183 if ( Jetpack::get_option( 'master_user' ) == $user_id )
1184 return false;
1185
1186 if ( !isset( $tokens[$user_id] ) )
1187 return false;
1188
1189 Jetpack::load_xml_rpc_client();
1190 $xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
1191 $xml->query( 'jetpack.unlink_user', $user_id );
1192
1193 unset( $tokens[$user_id] );
1194
1195 Jetpack::update_option( 'user_tokens', $tokens );
1196
1197 return true;
1198 }
1199
1200 /**
1201 * Attempts Jetpack registration. If it fail, a state flag is set: @see ::admin_page_load()
1202 */
1203 public static function try_registration() {
1204 $result = Jetpack::register();
1205
1206 // If there was an error with registration and the site was not registered, record this so we can show a message.
1207 if ( !$result || is_wp_error( $result ) ) {
1208 return $result;
1209 } else {
1210 return true;
1211 }
1212 }
1213
1214 /* Admin Pages */
1215
1216 function admin_init() {
1217 // If the plugin is not connected, display a connect message.
1218 if (
1219 // the plugin was auto-activated and needs its candy
1220 Jetpack::get_option( 'do_activate' )
1221 ||
1222 // the plugin is active, but was never activated. Probably came from a site-wide network activation
1223 !Jetpack::get_option( 'activated' )
1224 ) {
1225 Jetpack::plugin_initialize();
1226 }
1227
1228 if ( !Jetpack::is_active() ) {
1229 if ( 4 != Jetpack::get_option( 'activated' ) ) {
1230 // Show connect notice on dashboard and plugins pages
1231 add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
1232 add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
1233 }
1234 } elseif ( false === Jetpack::get_option( 'fallback_no_verify_ssl_certs' ) ) {
1235 // Upgrade: 1.1 -> 1.1.1
1236 // Check and see if host can verify the Jetpack servers' SSL certificate
1237 $args = array();
1238 Jetpack_Client::_wp_remote_request(
1239 Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ), $args ),
1240 $args,
1241 true
1242 );
1243 }
1244
1245 add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
1246 add_action( 'admin_head', array( $this, 'admin_menu_css' ) );
1247 add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links' ) );
1248
1249 add_action( 'wp_ajax_jetpack_debug', array( $this, 'ajax_debug' ) );
1250
1251 if ( Jetpack::is_active() ) {
1252 // Artificially throw errors in certain whitelisted cases during plugin activation
1253 add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
1254
1255 // Kick off synchronization of user role when it changes
1256 add_action( 'set_user_role', array( $this, 'user_role_change' ) );
1257
1258 // Add retina images hotfix to admin
1259 global $wp_db_version;
1260 if ( $wp_db_version > 19470 ) {
1261 // WP 3.4.x
1262 // TODO will need to add && $wp_db_version < xxxxx when 3.5 comes out.
1263 add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_retina_scripts' ) );
1264 // /wp-admin/customize.php omits the action above.
1265 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_retina_scripts' ) );
1266 }
1267 }
1268 }
1269
1270 function prepare_connect_notice() {
1271 add_action( 'admin_print_styles', array( $this, 'admin_styles' ) );
1272
1273 add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
1274
1275 if ( Jetpack::state( 'network_nag' ) )
1276 add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
1277 }
1278
1279 /**
1280 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
1281 * This function artificially throws errors for such cases (whitelisted).
1282 *
1283 * @param string $plugin The activated plugin.
1284 */
1285 function throw_error_on_activate_plugin( $plugin ) {
1286 $active_modules = Jetpack::get_active_modules();
1287
1288 // The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
1289 if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
1290 $throw = false;
1291
1292 // Try and make sure it really was the stats plugin
1293 if ( !class_exists( 'ReflectionFunction' ) ) {
1294 if ( 'stats.php' == basename( $plugin ) ) {
1295 $throw = true;
1296 }
1297 } else {
1298 $reflection = new ReflectionFunction( 'stats_get_api_key' );
1299 if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
1300 $throw = true;
1301 }
1302 }
1303
1304 if ( $throw ) {
1305 trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
1306 }
1307 }
1308 }
1309
1310 function intercept_plugin_error_scrape_init() {
1311 add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
1312 }
1313
1314 function intercept_plugin_error_scrape( $action, $result ) {
1315 if ( !$result ) {
1316 return;
1317 }
1318
1319 foreach ( $this->plugins_to_deactivate as $module => $deactivate_me ) {
1320 if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
1321 Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
1322 }
1323 }
1324 }
1325
1326 function admin_menu() {
1327 list( $jetpack_version ) = explode( ':', Jetpack::get_option( 'version' ) );
1328 if (
1329 $jetpack_version
1330 &&
1331 $jetpack_version != JETPACK__VERSION
1332 &&
1333 ( $new_modules = Jetpack::get_default_modules( $jetpack_version, JETPACK__VERSION ) )
1334 &&
1335 is_array( $new_modules )
1336 &&
1337 ( $new_modules_count = count( $new_modules ) )
1338 &&
1339 Jetpack::is_active()
1340 ) {
1341 $new_modules_count_i18n = number_format_i18n( $new_modules_count );
1342 $span_title = esc_attr( sprintf( _n( 'One New Jetpack Module', '%s New Jetpack Modules', $new_modules_count, 'jetpack' ), $new_modules_count_i18n ) );
1343 $title = sprintf( 'Jetpack %s', "<span class='update-plugins count-{$new_modules_count}' title='$span_title'><span class='update-count'>$new_modules_count_i18n</span></span>" );
1344 } else {
1345 $title = __( 'Jetpack', 'jetpack' );
1346 }
1347
1348 $hook = add_menu_page( 'Jetpack', $title, 'read', 'jetpack', array( $this, 'admin_page' ), 'div' );
1349
1350 add_action( "load-$hook", array( $this, 'admin_page_load' ) );
1351
1352 if ( version_compare( $GLOBALS['wp_version'], '3.3', '<' ) ) {
1353 if ( isset( $_GET['page'] ) && 'jetpack' == $_GET['page'] ) {
1354 add_contextual_help( $hook, $this->jetpack_help() );
1355 }
1356 } else {
1357 add_action( "load-$hook", array( $this, 'admin_help' ) );
1358 }
1359 add_action( "admin_head-$hook", array( $this, 'admin_head' ) );
1360 add_filter( 'custom_menu_order', array( $this, 'admin_menu_order' ) );
1361 add_filter( 'menu_order', array( $this, 'jetpack_menu_order' ) );
1362
1363 add_action( "admin_print_styles-$hook", array( $this, 'admin_styles' ) );
1364
1365 add_action( "admin_print_scripts-$hook", array( $this, 'admin_scripts' ) );
1366
1367 do_action( 'jetpack_admin_menu' );
1368 }
1369
1370 function add_remote_request_handlers() {
1371 add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
1372 }
1373
1374 function remote_request_handlers() {
1375 switch ( current_filter() ) {
1376 case 'wp_ajax_nopriv_jetpack_upload_file' :
1377 $response = $this->upload_handler();
1378 break;
1379 default :
1380 $response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
1381 break;
1382 }
1383
1384 if ( !$response ) {
1385 $response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
1386 }
1387
1388 if ( is_wp_error( $response ) ) {
1389 $status_code = $response->get_error_data();
1390 $error = $response->get_error_code();
1391 $error_description = $response->get_error_message();
1392
1393 if ( !is_int( $status_code ) ) {
1394 $status_code = 400;
1395 }
1396
1397 status_header( $status_code );
1398 die( json_encode( (object) compact( 'error', 'error_description' ) ) );
1399 }
1400
1401 status_header( 200 );
1402 if ( true === $response ) {
1403 exit;
1404 }
1405
1406 die( json_encode( (object) $response ) );
1407 }
1408
1409 function upload_handler() {
1410 if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
1411 return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
1412 }
1413
1414 $user = wp_authenticate( '', '' );
1415 if ( !$user || is_wp_error( $user ) ) {
1416 return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
1417 }
1418
1419 wp_set_current_user( $user->ID );
1420
1421 if ( !current_user_can( 'upload_files' ) ) {
1422 return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
1423 }
1424
1425 if ( empty( $_FILES ) ) {
1426 return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
1427 }
1428
1429 foreach ( array_keys( $_FILES ) as $files_key ) {
1430 if ( !isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
1431 return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
1432 }
1433 }
1434
1435 $media_keys = array_keys( $_FILES['media'] );
1436
1437 $token = Jetpack_Data::get_access_token( get_current_user_id() );
1438 if ( !$token || is_wp_error( $token ) ) {
1439 return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
1440 }
1441
1442 $uploaded_files = array();
1443 $global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
1444 unset( $GLOBALS['post'] );
1445 foreach ( $_FILES['media']['name'] as $index => $name ) {
1446 $file = array();
1447 foreach ( $media_keys as $media_key ) {
1448 $file[$media_key] = $_FILES['media'][$media_key][$index];
1449 }
1450
1451 list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
1452
1453 $hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
1454 if ( $hmac_provided !== $hmac_file ) {
1455 $uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
1456 continue;
1457 }
1458
1459 $_FILES['.jetpack.upload.'] = $file;
1460 $post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
1461 if ( !current_user_can( 'edit_post', $post_id ) ) {
1462 $post_id = 0;
1463 }
1464 $attachment_id = media_handle_upload( '.jetpack.upload.', $post_id, array(), array(
1465 'action' => 'jetpack_upload_file',
1466 ) );
1467
1468 if ( !$attachment_id ) {
1469 $uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
1470 } elseif ( is_wp_error( $attachment_id ) ) {
1471 $uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
1472 } else {
1473 $attachment = get_post( $attachment_id );
1474 $uploaded_files[$index] = (object) array(
1475 'id' => (string) $attachment_id,
1476 'file' => $attachment->post_title,
1477 'url' => wp_get_attachment_url( $attachment_id ),
1478 'type' => $attachment->post_mime_type,
1479 'meta' => wp_get_attachment_metadata( $attachment_id ),
1480 );
1481 }
1482 }
1483 if ( !is_null( $global_post ) ) {
1484 $GLOBALS['post'] = $global_post;
1485 }
1486
1487 return $uploaded_files;
1488 }
1489
1490 /**
1491 * Add help to the Jetpack page
1492 *
1493 * Deprecated. Remove when Jetpack requires WP 3.3+
1494 */
1495 function jetpack_help() {
1496 return
1497 '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
1498 '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
1499 '<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>' .
1500 '<p><strong>' . __( 'Jetpack Module Options', 'jetpack' ) . '</strong></p>' .
1501 '<p>' . __( '<strong>To Activate/Deactivate a Module</strong> - Click on Learn More. An Activate or Deactivate button will now appear next to the Learn More button. Click the Activate/Deactivate button.', 'jetpack' ) . '</p>' .
1502 '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
1503 '<p><a href="http://jetpack.me/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
1504 '<p><a href="http://jetpack.me/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>';
1505 }
1506
1507 /**
1508 * Add help to the Jetpack page
1509 *
1510 * @since Jetpack (1.2.3)
1511 * @return false if not the Jetpack page
1512 */
1513 function admin_help() {
1514 $current_screen = get_current_screen();
1515
1516 // Overview
1517 $current_screen->add_help_tab( array(
1518 'id' => 'overview',
1519 'title' => __( 'Overview', 'jetpack' ),
1520 'content' =>
1521 '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
1522 '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
1523 '<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>'
1524 ) );
1525
1526 // Screen Content
1527 if ( current_user_can( 'manage_options' ) ) {
1528 $current_screen->add_help_tab( array(
1529 'id' => 'modules',
1530 'title' => __( 'Modules', 'jetpack' ),
1531 'content' =>
1532 '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
1533 '<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
1534 '<ol>' .
1535 '<li>' . __( 'Find the component you want to manage', 'jetpack' ) . '</li>' .
1536 '<li>' . __( 'Click on Learn More', 'jetpack' ) . '</li>' .
1537 '<li>' . __( 'An Activate or Deactivate button will appear', 'jetpack' ) . '</li>' .
1538 '<li>' . __( 'If additional settings are available, a link to them will appear', 'jetpack' ) . '</li>' .
1539 '</ol>'
1540 ) );
1541 }
1542
1543 // Help Sidebar
1544 $current_screen->set_help_sidebar(
1545 '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
1546 '<p><a href="http://jetpack.me/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
1547 '<p><a href="http://jetpack.me/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>'
1548 );
1549 }
1550
1551 function admin_menu_css() { ?>
1552 <style type="text/css" id="jetpack-menu-css">
1553 #toplevel_page_jetpack .wp-menu-image {
1554 background: url( <?php echo plugins_url( basename( dirname( __FILE__ ) ) . '/_inc/images/menuicon-sprite.png' ) ?> ) 0 90% no-repeat;
1555 }
1556 /* Retina Jetpack Menu Icon */
1557 @media only screen and (-moz-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-device-pixel-ratio: 1.5) {
1558 #toplevel_page_jetpack .wp-menu-image {
1559 background: url( <?php echo plugins_url( basename( dirname( __FILE__ ) ) . '/_inc/images/menuicon-sprite-2x.png' ) ?> ) 0 90% no-repeat;
1560 background-size:30px 64px;
1561 }
1562 }
1563 #toplevel_page_jetpack.current .wp-menu-image,
1564 #toplevel_page_jetpack.wp-has-current-submenu .wp-menu-image,
1565 #toplevel_page_jetpack:hover .wp-menu-image {
1566 background-position: top left;
1567 }
1568 </style><?php
1569 }
1570
1571 function admin_menu_order() {
1572 return true;
1573 }
1574
1575 function jetpack_menu_order( $menu_order ) {
1576 $jp_menu_order = array();
1577
1578 foreach ( $menu_order as $index => $item ) {
1579 if ( $item != 'jetpack' )
1580 $jp_menu_order[] = $item;
1581
1582 if ( $index == 0 )
1583 $jp_menu_order[] = 'jetpack';
1584 }
1585
1586 return $jp_menu_order;
1587 }
1588
1589 function admin_head() {
1590 if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
1591 do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
1592 }
1593
1594 function admin_styles() {
1595 global $wp_styles;
1596 wp_enqueue_style( 'jetpack', plugins_url( basename( dirname( __FILE__ ) ) . '/_inc/jetpack.css' ), false, JETPACK__VERSION . '-20121016' );
1597 $wp_styles->add_data( 'jetpack', 'rtl', true );
1598 }
1599
1600 function admin_scripts() {
1601 wp_enqueue_script( 'jetpack-js', plugins_url( basename( dirname( __FILE__ ) ) ) . '/_inc/jetpack.js', array( 'jquery' ), JETPACK__VERSION . '-20121111' );
1602 wp_localize_script( 'jetpack-js', 'jetpackL10n', array(
1603 'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
1604 '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?",
1605 'ays_dismiss' => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
1606 ) );
1607 add_action( 'admin_footer', array( $this, 'do_stats' ) );
1608 }
1609
1610 function enqueue_retina_scripts() {
1611 wp_enqueue_style( 'jetpack-retina', plugins_url( basename( dirname( __FILE__ ) ) . '/_inc/jetpack-retina.css' ), false, JETPACK__VERSION . '-20120730' );
1612 }
1613
1614 function plugin_action_links( $actions ) {
1615 return array_merge(
1616 array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url(), __( 'Settings', 'jetpack' ) ) ),
1617 $actions
1618 );
1619 return $actions;
1620 }
1621
1622 function admin_connect_notice() {
1623 // Don't show the connect notice on the jetpack settings page. @todo: must be a better way?
1624 if ( false !== strpos( $_SERVER['QUERY_STRING'], 'page=jetpack' ) )
1625 return;
1626
1627 if ( !current_user_can( 'manage_options' ) )
1628 return;
1629 ?>
1630
1631 <div id="message" class="updated jetpack-message jp-connect">
1632 <div id="jp-dismiss" class="jetpack-close-button-container">
1633 <a class="jetpack-close-button" href="?page=jetpack&jetpack-notice=dismiss" title="<?php _e( 'Dismiss this notice and deactivate Jetpack.', 'jetpack' ); ?>"><?php _e( 'Dismiss this notice and deactivate Jetpack.', 'jetpack' ); ?></a>
1634 </div>
1635 <div class="jetpack-wrap-container">
1636 <div class="jetpack-text-container">
1637 <h4>
1638 <?php if ( 1 == Jetpack::get_option( 'activated' ) ) : ?>
1639 <p><?php _e( '<strong>Your Jetpack is almost ready</strong> &#8211; A connection to WordPress.com is needed to enable features like Comments, Stats, Contact Forms, and Subscriptions. Connect now to get fueled up!', 'jetpack' ); ?></p>
1640 <?php else : ?>
1641 <p><?php _e( '<strong>Jetpack is installed</strong> and ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
1642 <?php endif; ?>
1643 </h4>
1644 </div>
1645 <div class="jetpack-install-container">
1646 <?php if ( 1 == Jetpack::get_option( 'activated' ) ) : ?>
1647 <p class="submit"><a href="<?php echo $this->build_connect_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a></p>
1648 <?php else : ?>
1649 <p class="submit"><a href="<?php echo Jetpack::admin_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a></p>
1650 <?php endif; ?>
1651 </div>
1652 </div>
1653 </div>
1654
1655 <?php
1656 }
1657
1658 function network_connect_notice() {
1659 ?>
1660 <div id="message" class="updated jetpack-message">
1661 <div class="squeezer">
1662 <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>
1663 </div>
1664 </div>
1665 <?php
1666 }
1667
1668 public static function jetpack_comment_notice() {
1669 if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
1670 return '';
1671 }
1672
1673 $jetpack_old_version = explode( ':', Jetpack::get_option( 'old_version' ) );
1674 $jetpack_new_version = explode( ':', Jetpack::get_option( 'version' ) );
1675
1676 if ( $jetpack_old_version ) {
1677 if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
1678 return '';
1679 }
1680 }
1681
1682 if ( $jetpack_new_version ) {
1683 if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
1684 return '';
1685 }
1686 }
1687
1688 return '<br /><br />' . sprintf(
1689 __( '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' ),
1690 wp_nonce_url(
1691 Jetpack::admin_url( array(
1692 'action' => 'activate',
1693 'module' => 'comments',
1694 ) ),
1695 "jetpack_activate-comments"
1696 ),
1697 __( 'click here', 'jetpack' )
1698 );
1699 }
1700
1701 /*
1702 * Registration flow:
1703 * 1 - ::admin_page_load() action=register
1704 * 2 - ::try_registration()
1705 * 3 - ::register()
1706 * - Creates jetpack_register option containing two secrets and a timestamp
1707 * - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
1708 * siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
1709 * - That request to jetpack.wordpress.com does not immediately respond. It first makes a request BACK to this site's
1710 * xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
1711 * - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
1712 * - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
1713 * jetpack_id, jetpack_secret, jetpack_public
1714 * - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
1715 * 4 - redirect to https://jetpack.wordpress.com/jetpack.authorize/1/
1716 * 5 - user logs in with WP.com account
1717 * 6 - redirect to this site's wp-admin/index.php?page=jetpack&action=authorize with
1718 * code <-- OAuth2 style authorization code
1719 * 7 - ::admin_page_load() action=authorize
1720 * 8 - Jetpack_Client_Server::authorize()
1721 * 9 - Jetpack_Client_Server::get_token()
1722 * 10- GET https://jetpack.wordpress.com/jetpack.token/1/ with
1723 * client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
1724 * 11- which responds with
1725 * access_token, token_type, scope
1726 * 12- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
1727 * 13- Jetpack::activate_default_modules()
1728 * Deactivates deprecated plugins
1729 * Activates all default modules
1730 * Catches errors: redirects to wp-admin/index.php?page=jetpack state:error=something
1731 * 14- redirect to this site's wp-admin/index.php?page=jetpack with state:message=authorized
1732 * Done!
1733 */
1734
1735 /**
1736 * Handles the page load events for the Jetpack admin page
1737 */
1738 function admin_page_load() {
1739 $error = false;
1740
1741 if ( !empty( $_GET['jetpack_restate'] ) ) {
1742 // Should only be used in intermediate redirects to preserve state across redirects
1743 Jetpack::restate();
1744 }
1745
1746 if ( isset( $_GET['connect_url_redirect'] ) ) {
1747 // User clicked in the iframe to link their accounts
1748 if ( ! Jetpack::is_user_connected() ) {
1749 $connect_url = $this->build_connect_url( true );
1750 if ( isset( $_GET['notes_iframe'] ) )
1751 $connect_url .= '&notes_iframe';
1752 wp_redirect( $connect_url );
1753 exit;
1754 } else {
1755 Jetpack::state( 'message', 'already_authorized' );
1756 wp_safe_redirect( Jetpack::admin_url() );
1757 exit;
1758 }
1759 }
1760
1761 if ( isset( $_GET['action'] ) ) {
1762 switch ( $_GET['action'] ) {
1763 case 'authorize' :
1764 if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
1765 Jetpack::state( 'message', 'already_authorized' );
1766 wp_safe_redirect( Jetpack::admin_url() );
1767 exit;
1768 }
1769 $client_server = new Jetpack_Client_Server;
1770 $client_server->authorize();
1771 exit;
1772 case 'register' :
1773 check_admin_referer( 'jetpack-register' );
1774 $registered = Jetpack::try_registration();
1775 if ( is_wp_error( $registered ) ) {
1776 $error = $registered->get_error_code();
1777 Jetpack::state( 'error_description', $registered->get_error_message() );
1778 break;
1779 }
1780
1781 wp_redirect( $this->build_connect_url( true ) );
1782 exit;
1783 case 'activate' :
1784 $module = stripslashes( $_GET['module'] );
1785 check_admin_referer( "jetpack_activate-$module" );
1786 Jetpack::activate_module( $module );
1787 wp_safe_redirect( Jetpack::admin_url() );
1788 exit;
1789 case 'activate_default_modules' :
1790 check_admin_referer( 'activate_default_modules' );
1791 Jetpack::restate();
1792 $min_version = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
1793 $max_version = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
1794 $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
1795 Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
1796 wp_safe_redirect( Jetpack::admin_url() );
1797 exit;
1798 case 'disconnect' :
1799 check_admin_referer( 'jetpack-disconnect' );
1800 Jetpack::disconnect();
1801 wp_safe_redirect( Jetpack::admin_url() );
1802 exit;
1803 case 'deactivate' :
1804 $modules = stripslashes( $_GET['module'] );
1805 check_admin_referer( "jetpack_deactivate-$modules" );
1806 foreach ( explode( ',', $modules ) as $module ) {
1807 Jetpack::deactivate_module( $module );
1808 Jetpack::state( 'message', 'module_deactivated' );
1809 }
1810 Jetpack::state( 'module', $modules );
1811 wp_safe_redirect( Jetpack::admin_url() );
1812 exit;
1813 case 'unlink' :
1814 check_admin_referer( 'jetpack-unlink' );
1815 $this->unlink_user();
1816 Jetpack::state( 'message', 'unlinked' );
1817 wp_safe_redirect( Jetpack::admin_url() );
1818 exit;
1819 }
1820 }
1821
1822 if ( !$error = $error ? $error : Jetpack::state( 'error' ) ) {
1823 $this->activate_new_modules();
1824 }
1825
1826 switch ( $error ) {
1827 case 'access_denied' :
1828 $this->error = __( 'You need to authorize the Jetpack connection between your site and WordPress.com to enable the awesome features.', 'jetpack' );
1829 break;
1830 case 'wrong_state' :
1831 $this->error = __( "Don&#8217;t cross the streams! You need to stay logged in to your WordPress blog while you authorize Jetpack.", 'jetpack' );
1832 break;
1833 case 'invalid_client' :
1834 // @todo re-register instead of deactivate/reactivate
1835 $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' );
1836 break;
1837 case 'invalid_grant' :
1838 $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' );
1839 break;
1840 case 'site_inaccessible' :
1841 case 'site_requires_authorization' :
1842 $this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
1843 break;
1844 case 'module_activation_failed' :
1845 $module = Jetpack::state( 'module' );
1846 if ( !empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
1847 $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'] );
1848 if ( isset( $this->plugins_to_deactivate[$module] ) ) {
1849 $this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
1850 }
1851 } else {
1852 $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' );
1853 }
1854 if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
1855 $this->error .= "<br />\n";
1856 $this->error .= $php_errors;
1857 }
1858 break;
1859 case 'not_public' :
1860 $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' );
1861 break;
1862 case 'wpcom_408' :
1863 case 'wpcom_5??' :
1864 case 'wpcom_bad_response' :
1865 case 'wpcom_outage' :
1866 $this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack. Please try again later.', 'jetpack' );
1867 break;
1868 case 'register_http_request_failed' :
1869 case 'token_http_request_failed' :
1870 $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>" );
1871 break;
1872 default :
1873 if ( empty( $error ) ) {
1874 break;
1875 }
1876 $error = trim( substr( strip_tags( $error ), 0, 20 ) );
1877 // no break: fall through
1878 case 'no_role' :
1879 case 'no_cap' :
1880 case 'no_code' :
1881 case 'no_state' :
1882 case 'invalid_state' :
1883 case 'invalid_request' :
1884 case 'invalid_scope' :
1885 case 'unsupported_response_type' :
1886 case 'invalid_token' :
1887 case 'no_token' :
1888 case 'missing_secrets' :
1889 case 'home_missing' :
1890 case 'siteurl_missing' :
1891 case 'gmt_offset_missing' :
1892 case 'site_name_missing' :
1893 case 'secret_1_missing' :
1894 case 'secret_2_missing' :
1895 case 'site_lang_missing' :
1896 case 'home_malformed' :
1897 case 'siteurl_malformed' :
1898 case 'gmt_offset_malformed' :
1899 case 'timezone_string_malformed' :
1900 case 'site_name_malformed' :
1901 case 'secret_1_malformed' :
1902 case 'secret_2_malformed' :
1903 case 'site_lang_malformed' :
1904 case 'secrets_mismatch' :
1905 case 'verify_secret_1_missing' :
1906 case 'verify_secret_1_malformed' :
1907 case 'verify_secrets_missing' :
1908 case 'verify_secrets_mismatch' :
1909 $error = esc_html( $error );
1910 $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>" );
1911 if ( !Jetpack::is_active() ) {
1912 $this->error .= '<br />';
1913 $this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
1914 }
1915 break;
1916 }
1917
1918 $message_code = Jetpack::state( 'message' );
1919
1920 $active_state = Jetpack::state( 'activated_modules' );
1921 if ( !empty( $active_state ) ) {
1922 $available = Jetpack::get_available_modules();
1923 $active_state = explode( ',', $active_state );
1924 $active_state = array_intersect( $active_state, $available );
1925 if ( count( $active_state ) ) {
1926 foreach ( $active_state as $mod ) {
1927 $this->stat( 'module-activated', $mod );
1928 }
1929 } else {
1930 $active_state = false;
1931 }
1932 }
1933
1934 switch ( $message_code ) {
1935 case 'modules_activated' :
1936 $this->message = sprintf(
1937 __( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
1938 JETPACK__VERSION
1939 );
1940
1941 if ( $active_state ) {
1942 $titles = array();
1943 foreach ( $active_state as $mod ) {
1944 if ( $mod_headers = Jetpack::get_module( $mod ) ) {
1945 $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
1946 }
1947 }
1948 if ( $titles ) {
1949 $this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
1950 }
1951 }
1952
1953 if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
1954 $titles = array();
1955 foreach ( explode( ',', $reactive_state ) as $mod ) {
1956 if ( $mod_headers = Jetpack::get_module( $mod ) ) {
1957 $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
1958 }
1959 }
1960 if ( $titles ) {
1961 $this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
1962 }
1963 }
1964
1965 $this->message .= Jetpack::jetpack_comment_notice();
1966 break;
1967
1968 case 'module_activated' :
1969 if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
1970 $this->message = sprintf( __( '<strong>%s Activated!</strong> You can deactivate at any time by clicking Learn More and then Deactivate on the module card.', 'jetpack' ), $module['name'] );
1971 $this->stat( 'module-activated', Jetpack::state( 'module' ) );
1972 }
1973 break;
1974
1975 case 'module_deactivated' :
1976 $modules = Jetpack::state( 'module' );
1977 if ( !$modules ) {
1978 break;
1979 }
1980
1981 $module_names = array();
1982 foreach ( explode( ',', $modules ) as $module_slug ) {
1983 $module = Jetpack::get_module( $module_slug );
1984 if ( $module ) {
1985 $module_names[] = $module['name'];
1986 }
1987
1988 $this->stat( 'module-deactivated', $module_slug );
1989 }
1990
1991 if ( !$module_names ) {
1992 break;
1993 }
1994
1995 $this->message = wp_sprintf(
1996 _nx(
1997 '<strong>%l Deactivated!</strong> You can activate it again at any time using the activate button on the module card.',
1998 '<strong>%l Deactivated!</strong> You can activate them again at any time using the activate buttons on their module cards.',
1999 count( $module_names ),
2000 '%l = list of Jetpack module/feature names',
2001 'jetpack'
2002 ),
2003 $module_names
2004 );
2005 break;
2006
2007 case 'module_configured' :
2008 $this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
2009 break;
2010
2011 case 'already_authorized' :
2012 $this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
2013 break;
2014
2015 case 'authorized' :
2016 $this->message = __( "<strong>You&#8217;re fueled up and ready to go.</strong> ", 'jetpack' );
2017 $this->message .= "<br />\n";
2018 $this->message .= __( 'The features below are now active. Click the learn more buttons to explore each feature.', 'jetpack' );
2019 $this->message .= Jetpack::jetpack_comment_notice();
2020 break;
2021
2022 case 'linked' :
2023 $this->message = __( "<strong>You&#8217;re fueled up and ready to go.</strong> ", 'jetpack' );
2024 $this->message .= Jetpack::jetpack_comment_notice();
2025 break;
2026
2027 case 'unlinked' :
2028 $user = wp_get_current_user();
2029 $this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
2030 break;
2031 }
2032
2033 $deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
2034
2035 if ( !empty( $deactivated_plugins ) ) {
2036 $deactivated_plugins = explode( ',', $deactivated_plugins );
2037 $deactivated_titles = array();
2038 foreach ( $deactivated_plugins as $deactivated_plugin ) {
2039 if ( !isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
2040 continue;
2041 }
2042
2043 $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
2044 }
2045
2046 if ( $deactivated_titles ) {
2047 if ( $this->message ) {
2048 $this->message .= "<br /><br />\n";
2049 }
2050
2051 $this->message .= wp_sprintf( _n(
2052 'Jetpack contains the most recent version of the old %l plugin.',
2053 'Jetpack contains the most recent versions of the old %l plugins.',
2054 count( $deactivated_titles ),
2055 'jetpack'
2056 ), $deactivated_titles );
2057
2058 $this->message .= "<br />\n";
2059
2060 $this->message .= _n(
2061 'The old version has been deactivated and can be removed from your site.',
2062 'The old versions have been deactivated and can be removed from your site.',
2063 count( $deactivated_titles ),
2064 'jetpack'
2065 );
2066 }
2067 }
2068
2069 $this->privacy_checks = Jetpack::state( 'privacy_checks' );
2070
2071 if ( $this->message || $this->error || $this->privacy_checks ) {
2072 add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
2073 }
2074
2075 if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
2076 do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
2077 }
2078
2079 add_filter( 'jetpack_short_module_description', 'wptexturize' );
2080 }
2081
2082 function admin_notices() {
2083
2084 if ( $this->error ) {
2085 ?>
2086 <div id="message" class="jetpack-message jetpack-err">
2087 <div class="squeezer">
2088 <h4><?php echo wp_kses( $this->error, array( 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h4>
2089 <?php if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
2090 <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
2091 <?php endif; ?>
2092 </div>
2093 </div>
2094 <?php
2095 }
2096
2097 if ( $this->message ) {
2098 ?>
2099 <div id="message" class="jetpack-message">
2100 <div class="squeezer">
2101 <h4><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h4>
2102 </div>
2103 </div>
2104 <?php
2105
2106 }
2107
2108 if ( $this->privacy_checks ) :
2109 $module_names = $module_slugs = array();
2110
2111 $privacy_checks = explode( ',', $this->privacy_checks );
2112 foreach ( $privacy_checks as $module_slug ) {
2113 $module = Jetpack::get_module( $module_slug );
2114 if ( !$module ) {
2115 continue;
2116 }
2117
2118 $module_slugs[] = $module_slug;
2119 $module_names[] = "<strong>{$module['name']}</strong>";
2120 }
2121
2122 $module_slugs = join( ',', $module_slugs );
2123 ?>
2124 <div id="message" class="jetpack-message jetpack-err">
2125 <div class="squeezer">
2126 <h4><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h4><br />
2127 <p><?php
2128 echo wp_kses( wptexturize( wp_sprintf(
2129 _nx(
2130 "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
2131 "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
2132 count( $privacy_checks ),
2133 '%l = list of Jetpack module/feature names',
2134 'jetpack'
2135 ),
2136 $module_names
2137 ) ), array( 'strong' => true ) );
2138
2139 echo "\n<br />\n";
2140
2141 echo wp_kses( sprintf(
2142 _nx(
2143 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
2144 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
2145 count( $privacy_checks ),
2146 '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
2147 'jetpack'
2148 ),
2149 wp_nonce_url(
2150 Jetpack::admin_url( array(
2151 'action' => 'deactivate',
2152 'module' => urlencode( $module_slugs ),
2153 ) ),
2154 "jetpack_deactivate-$module_slugs"
2155 ),
2156 esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
2157 ), array( 'a' => array( 'href' => true, 'title' => true ) ) );
2158 ?></p>
2159 </div>
2160 </div>
2161 <?php
2162 endif;
2163 }
2164
2165 /**
2166 * Record a stat for later output
2167 */
2168 function stat( $group, $detail ) {
2169 if ( !isset( $this->stats[ $group ] ) )
2170 $this->stats[ $group ] = array();
2171 $this->stats[ $group ][] = $detail;
2172 }
2173
2174 /**
2175 * Load stats pixels. $group is auto-prefixed with "jetpack-"
2176 */
2177 function do_stats() {
2178 if ( is_array( $this->stats ) && count( $this->stats ) ) {
2179 foreach ( $this->stats as $group => $stats ) {
2180 if ( is_array( $stats ) && count( $stats ) )
2181 echo '<img src="' . ( is_ssl() ? 'https' : 'http' ) . '://stats.wordpress.com/g.gif?v=wpcom2&x_jetpack-' . esc_attr( $group ) . '=' . esc_attr( implode( ',', $stats ) ) . '&rand=' . md5( mt_rand( 0, 999 ) . time() ) . '" width="1" height="1" style="display:none;" />';
2182 }
2183 }
2184 }
2185
2186 function translate_current_user_to_role() {
2187 foreach ( $this->capability_translations as $role => $cap ) {
2188 if ( current_user_can( $role ) || current_user_can( $cap ) ) {
2189 return $role;
2190 }
2191 }
2192
2193 return false;
2194 }
2195
2196 function translate_role_to_cap( $role ) {
2197 if ( !isset( $this->capability_translations[$role] ) ) {
2198 return false;
2199 }
2200
2201 return $this->capability_translations[$role];
2202 }
2203
2204 function sign_role( $role ) {
2205 if ( !$user_id = (int) get_current_user_id() ) {
2206 return false;
2207 }
2208
2209 $token = Jetpack_Data::get_access_token();
2210 if ( !$token || is_wp_error( $token ) ) {
2211 return false;
2212 }
2213
2214 return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
2215 }
2216
2217 function build_connect_url( $raw = false, $redirect = false ) {
2218 if ( !Jetpack::get_option( 'blog_token' ) ) {
2219 $url = wp_nonce_url( add_query_arg( 'action', 'register', menu_page_url( 'jetpack', false ) ), 'jetpack-register' );
2220 } else {
2221 $role = $this->translate_current_user_to_role();
2222 $signed_role = $this->sign_role( $role );
2223
2224 $user = wp_get_current_user();
2225
2226 $redirect = $redirect ? esc_url_raw( $redirect ) : '';
2227
2228 $args = urlencode_deep( array(
2229 'response_type' => 'code',
2230 'client_id' => Jetpack::get_option( 'id' ),
2231 'redirect_uri' => add_query_arg( array(
2232 'action' => 'authorize',
2233 '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
2234 'redirect' => $redirect ? urlencode( $redirect ) : false,
2235 ), menu_page_url( 'jetpack', false ) ),
2236 'state' => $user->ID,
2237 'scope' => $signed_role,
2238 'user_email' => $user->user_email,
2239 'user_login' => $user->user_login,
2240 'is_active' => Jetpack::is_active(),
2241 'jp_version' => JETPACK__VERSION,
2242 ) );
2243
2244 $url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
2245 }
2246
2247 return $raw ? $url : esc_url( $url );
2248 }
2249
2250 public static function admin_url( $args = null ) {
2251 $url = admin_url( 'admin.php?page=jetpack' );
2252 if ( is_array( $args ) )
2253 $url = add_query_arg( $args, $url );
2254 return $url;
2255 }
2256
2257 function dismiss_jetpack_notice() {
2258 if ( isset( $_GET['jetpack-notice'] ) && 'dismiss' == $_GET['jetpack-notice'] && ! is_plugin_active_for_network( plugin_basename( __FILE__ ) ) ) {
2259 require_once ABSPATH . 'wp-admin/includes/plugin.php';
2260
2261 deactivate_plugins( plugin_basename( __FILE__ ), false, false );
2262
2263 wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
2264 exit;
2265 }
2266 }
2267
2268 function admin_page() {
2269 global $current_user;
2270
2271 $role = $this->translate_current_user_to_role();
2272 $is_connected = Jetpack::is_active();
2273 $user_token = Jetpack_Data::get_access_token($current_user->ID);
2274 $is_user_connected = $user_token && !is_wp_error($user_token);
2275 $is_master_user = $current_user->ID == Jetpack::get_option( 'master_user' );
2276 $module = false;
2277 ?>
2278 <div class="wrap" id="jetpack-settings">
2279
2280 <h2 style="display: none"></h2> <!-- For WP JS message relocation -->
2281
2282 <div id="jp-header"<?php if ( $is_connected ) : ?> class="small"<?php endif; ?>>
2283 <div id="jp-clouds">
2284 <?php if ( $is_connected ) : ?>
2285 <div id="jp-disconnectors">
2286 <?php if ( current_user_can( 'manage_options' ) ) : ?>
2287 <div id="jp-disconnect" class="jp-disconnect">
2288 <a href="<?php echo wp_nonce_url( Jetpack::admin_url( array( 'action' => 'disconnect' ) ), 'jetpack-disconnect' ); ?>"><div class="deftext"><?php _e( 'Connected to WordPress.com', 'jetpack' ); ?></div><div class="hovertext"><?php _e( 'Disconnect from WordPress.com', 'jetpack' ) ?></div></a>
2289 </div>
2290 <?php endif; ?>
2291 <?php if ( $is_user_connected && !$is_master_user ) : ?>
2292 <div id="jp-unlink" class="jp-disconnect">
2293 <a href="<?php echo wp_nonce_url( Jetpack::admin_url( array( '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>
2294 </div>
2295 <?php endif; ?>
2296 </div>
2297 <?php endif; ?>
2298 <h3><?php _e( 'Jetpack by WordPress.com', 'jetpack' ) ?></h3>
2299 <?php if ( !$is_connected ) : ?>
2300 <div id="jp-notice">
2301 <p><?php _e( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ); ?></p>
2302 </div>
2303 <?php endif; ?>
2304 </div>
2305 </div>
2306
2307 <?php if ( isset( $_GET['jetpack-notice'] ) && 'dismiss' == $_GET['jetpack-notice'] ) : ?>
2308 <div id="message" class="error">
2309 <p><?php _e( 'Jetpack is network activated and notices can not be dismissed.', 'jetpack' ); ?></p>
2310 </div>
2311 <?php endif; ?>
2312
2313 <?php do_action( 'jetpack_notices' ) ?>
2314
2315 <?php // If the connection has not been made then show the marketing text. ?>
2316 <?php if ( ! $is_connected ) : ?>
2317
2318 <div id="message" class="updated jetpack-message jp-connect">
2319 <div id="jp-dismiss" class="jetpack-close-button-container">
2320 <a class="jetpack-close-button" href="?page=jetpack&jetpack-notice=dismiss" title="<?php _e( 'Dismiss this notice.', 'jetpack' ); ?>"><?php _e( 'Dismiss this notice.', 'jetpack' ); ?></a>
2321 </div>
2322 <div class="jetpack-wrap-container">
2323 <div class="jetpack-text-container">
2324 <h4>
2325 <p><?php _e( "To enable all of the Jetpack features you&#8217;ll need to connect your website to WordPress.com using the button to the right. Once you&#8217;ve made the connection you&#8217;ll activate all the delightful features below.", 'jetpack' ) ?></p>
2326 </h4>
2327 </div>
2328 <div class="jetpack-install-container">
2329 <p class="submit"><a href="<?php echo $this->build_connect_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a></p>
2330 </div>
2331 </div>
2332 </div>
2333
2334 <?php elseif ( ! $is_user_connected ) : ?>
2335
2336 <div id="message" class="updated jetpack-message jp-connect">
2337 <div class="jetpack-wrap-container">
2338 <div class="jetpack-text-container">
2339 <h4>
2340 <p><?php _e( "To enable all of the Jetpack features you&#8217;ll need to link your account here to your WordPress.com account using the button to the right.", 'jetpack' ) ?></p>
2341 </h4>
2342 </div>
2343 <div class="jetpack-install-container">
2344 <p class="submit"><a href="<?php echo $this->build_connect_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Link account with WordPress.com', 'jetpack' ); ?></a></p>
2345 </div>
2346 </div>
2347 </div>
2348
2349 <?php else /* blog and user are connected */ : ?>
2350 <?php /* TODO: if not master user, show user disconnect button? */ ?>
2351 <?php endif; ?>
2352
2353 <?php
2354 // If we select the configure option for a module, show the configuration screen.
2355 if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) :
2356 $this->admin_screen_configure_module( $_GET['configure'] );
2357
2358 // List all the available modules.
2359 else :
2360 $this->admin_screen_list_modules();
2361 ?>
2362
2363 <div id="survey" class="jp-survey">
2364 <div class="jp-survey-container">
2365 <div class="jp-survey-text">
2366 <h4><?php _e( 'Have feedback on Jetpack?', 'jetpack' ); ?></h4>
2367 <br />
2368 <?php _e( 'Answer a short survey to let us know how we&#8217;re doing and what to add in the future.', 'jetpack' ); ?>
2369 </div>
2370 <div class="jp-survey-button-container">
2371 <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>
2372 </div>
2373 </div>
2374 </div>
2375
2376 <?php if ( $is_connected && $this->current_user_is_connection_owner() ) : ?>
2377 <p id="news-sub"><?php _e( 'Checking email updates status&hellip;', 'jetpack' ); ?></p>
2378 <script type="text/javascript">
2379 jQuery(document).ready(function($){
2380 $.get( ajaxurl, { action: 'jetpack-check-news-subscription', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
2381 if ( 'subscribed' == data ) {
2382 $( '#news-sub' ).html( '<?php printf(
2383 esc_js( _x( 'You are currently subscribed to email updates. %s', '%s = Unsubscribe link', 'jetpack' ) ),
2384 '<a href="#" class="jp-news-link button">' . esc_js( __( 'Unsubscribe', 'jetpack' ) ) . '</a>'
2385 ); ?>' );
2386 } else {
2387 $( '#news-sub' ).html( '<?php printf(
2388 esc_js( _x( 'Want to receive updates about Jetpack by email? %s', '%s = Subscribe link', 'jetpack' ) ),
2389 '<a href="#" class="jp-news-link button-primary">' . esc_js( __( 'Subscribe', 'jetpack' ) ) . '</a>'
2390 ); ?>' );
2391 }
2392 $( '.jp-news-link' ).click( function() {
2393 $( '#news-sub' ).append( ' <img src="<?php echo esc_js( esc_url( admin_url( 'images/loading.gif' ) ) ); ?>" align="absmiddle" id="jp-news-loading" />' );
2394 $.get( ajaxurl, { action: 'jetpack-subscribe-to-news', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
2395 if ( 'subscribed' == data ) {
2396 $( '#news-sub' ).text( '<?php echo esc_js( __( 'You have been subscribed to receive email updates.', 'jetpack' ) ); ?>' );
2397 } else {
2398 $( '#news-sub' ).text( '<?php echo esc_js( __( 'You will no longer receive email updates about Jetpack.', 'jetpack' ) ); ?>' );
2399 }
2400 $( '#jp-news-loading' ).remove();
2401 } );
2402 return false;
2403 } );
2404 } );
2405 } );
2406 </script>
2407 <?php endif; ?>
2408 <?php endif; ?>
2409
2410 <div id="jp-footer">
2411 <p class="automattic"><?php _e( 'An <span>Automattic</span> Airline', 'jetpack' ) ?></p>
2412 <p class="small">
2413 <a href="http://jetpack.me/" target="_blank">Jetpack <?php echo esc_html( JETPACK__VERSION ); ?></a> |
2414 <a href="http://automattic.com/privacy/" target="_blank"><?php _e( 'Privacy Policy', 'jetpack' ); ?></a> |
2415 <a href="http://wordpress.com/tos/" target="_blank"><?php _e( 'Terms of Service', 'jetpack' ); ?></a> |
2416 <?php if ( current_user_can( 'manage_options' ) ) : ?>
2417 <a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-ajax.php?action=jetpack_debug' ), 'jetpack_debug' ) ); ?>" id="jp-debug"><?php _e( 'Debug', 'jetpack' ); ?></a> |
2418 <?php endif; ?>
2419 <a href="http://jetpack.me/support/" target="_blank"><?php _e( 'Support', 'jetpack' ); ?></a>
2420 </p>
2421 </div>
2422
2423 <div id="jetpack-configuration" style="display:none;">
2424 <p><img width="16" src="<?php echo esc_url( plugins_url( '_inc/images/wpspin_light-2x.gif', __FILE__ ) ); ?>" alt="Loading ..." /></p>
2425 </div>
2426 </div>
2427 <?php
2428 }
2429
2430 function ajax_debug() {
2431 nocache_headers();
2432
2433 check_ajax_referer( 'jetpack_debug' );
2434
2435 if ( !current_user_can( 'manage_options' ) ) {
2436 die( '-1' );
2437 }
2438 ?>
2439 <p><?php esc_html_e( 'This is sensitive information. Please do not post your BLOG_TOKEN or USER_TOKEN publicly; they are like passwords.', 'jetpack' ); ?></p>
2440 <ul>
2441 <?php
2442 // Extract the current_user's token
2443 $user_id = get_current_user_id();
2444 $user_tokens = Jetpack::get_option( 'user_tokens' );
2445 if ( is_array( $user_tokens ) && array_key_exists( $user_id, $user_tokens ) ) {
2446 $user_token = $user_tokens[$user_id];
2447 } else {
2448 $user_token = '[this user has no token]';
2449 }
2450 unset( $user_tokens );
2451
2452 foreach ( array(
2453 'CLIENT_ID' => 'id',
2454 'BLOG_TOKEN' => 'blog_token',
2455 'MASTER_USER' => 'master_user',
2456 'CERT' => 'fallback_no_verify_ssl_certs',
2457 'TIME_DIFF' => 'time_diff',
2458 'VERSION' => 'version',
2459 'OLD_VERSION' => 'old_version',
2460 'PUBLIC' => 'public',
2461 ) as $label => $option_name ) :
2462 ?>
2463 <li><?php echo esc_html( $label ); ?>: <code><?php echo esc_html( Jetpack::get_option( $option_name ) ); ?></code></li>
2464 <?php endforeach; ?>
2465 <li>USER_ID: <code><?php echo esc_html( $user_id ); ?></code></li>
2466 <li>USER_TOKEN: <code><?php echo esc_html( $user_token ); ?></code></li>
2467 <li>PHP_VERSION: <code><?php echo esc_html( PHP_VERSION ); ?></code></li>
2468 <li>WORDPRESS_VERSION: <code><?php echo esc_html( $GLOBALS['wp_version'] ); ?></code></li>
2469 </ul>
2470 <?php
2471 exit;
2472 }
2473
2474 function admin_screen_configure_module( $module_id ) {
2475 if ( !in_array( $module_id, Jetpack::get_active_modules() ) || !current_user_can( 'manage_options' ) )
2476 return false; ?>
2477
2478 <div id="jp-settings-screen" style="position: relative">
2479 <h3>
2480 <?php
2481 $module = Jetpack::get_module( $module_id );
2482 echo '<a href="' . menu_page_url( 'jetpack', false ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
2483 printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
2484 ?>
2485 </h3>
2486
2487 <?php do_action( 'jetpack_module_configuration_screen_' . $module_id ); ?>
2488 </div><?php
2489 }
2490
2491 public static function sort_modules( $a, $b ) {
2492 if ( $a['sort'] == $b['sort'] )
2493 return 0;
2494
2495 return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
2496 }
2497
2498 function admin_screen_list_modules() {
2499 require_once dirname( __FILE__ ) . '/modules/module-info.php';
2500 $jetpack_connected = true;
2501 if ( !Jetpack::is_active() )
2502 $jetpack_connected = false;
2503
2504 ?>
2505 <div class="module-container">
2506 <?php
2507
2508 $avail_raw = Jetpack::get_available_modules();
2509 $available = array();
2510 $active = Jetpack::get_active_modules();
2511 $counter = 0;
2512
2513 foreach ( (array) $avail_raw as $module ) {
2514 if ( $plugin = Jetpack::get_module( $module ) ) {
2515 $plugin['module'] = $module;
2516 $available[] = $plugin;
2517 }
2518 }
2519 unset( $avail_raw );
2520 usort( $available, array( 'Jetpack', 'sort_modules' ) );
2521 $jetpack_version = Jetpack::get_option( 'version' );
2522 if ( $jetpack_version ) {
2523 list( $jetpack_version, $jetpack_version_time ) = explode( ':', $jetpack_version );
2524 } else {
2525 $jetpack_version = 0;
2526 $jetpack_version_time = 0;
2527 }
2528
2529 $jetpack_old_version = Jetpack::get_option( 'old_version' );
2530 if ( $jetpack_old_version ) {
2531 list( $jetpack_old_version ) = explode( ':', $jetpack_old_version );
2532 } else {
2533 $jetpack_old_version = 0;
2534 }
2535 $now = time();
2536
2537 foreach ( (array) $available as $module_data ) {
2538 $module = $module_data['module'];
2539 $activated = in_array( $module, $active );
2540 if ( $activated ) {
2541 $css = 'active';
2542 $toggle = __( 'Deactivate', 'jetpack' );
2543 $toggle_url = wp_nonce_url(
2544 Jetpack::admin_url( array(
2545 'action' => 'deactivate',
2546 'module' => $module
2547 ) ),
2548 "jetpack_deactivate-$module"
2549 );
2550 } else {
2551 $css = 'inactive';
2552 $toggle = __( 'Activate', 'jetpack' );
2553 $toggle_url = wp_nonce_url(
2554 Jetpack::admin_url( array(
2555 'action' => 'activate',
2556 'module' => $module
2557 ) ),
2558 "jetpack_activate-$module"
2559 );
2560 }
2561
2562 if ( $counter % 4 == 0 ) {
2563 $classes = $css . ' jetpack-newline';
2564 $counter = 0;
2565 } else {
2566 $classes = $css;
2567 }
2568
2569 $free_text = esc_html( $module_data['free'] ? __( 'Free', 'jetpack' ) : __( 'Purchase', 'jetpack' ) );
2570 $free_text = apply_filters( 'jetpack_module_free_text_' . $module, $free_text );
2571 $badge_text = $free_text;
2572
2573 if ( !$jetpack_connected ) {
2574 $classes = 'x disabled';
2575 } else if ( $jetpack_version_time + 604800 > $now ) { // 1 week
2576 if ( version_compare( $module_data['introduced'], $jetpack_old_version, '>' ) ) {
2577 $badge_text = esc_html__( 'New', 'jetpack' );
2578 $classes .= ' jetpack-new-module';
2579 } elseif ( isset( $module_data['changed'] ) && version_compare( $module_data['changed'], $jetpack_old_version, '>' ) ) {
2580 $badge_text = esc_html__( 'Updated', 'jetpack' );
2581 $classes .= ' jetpack-updated-module';
2582 } else {
2583 $badge_text = $free_text;
2584 }
2585 }
2586
2587 ?>
2588 <div class="jetpack-module jetpack-<?php echo $classes; ?>" id="<?php echo $module ?>">
2589 <h3><?php echo $module_data['name']; ?></h3>
2590 <div class="jetpack-module-description">
2591 <div class="module-image">
2592 <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>
2593 </div>
2594
2595 <p><?php echo apply_filters( 'jetpack_short_module_description', $module_data['description'], $module ); ?></p>
2596 </div>
2597
2598 <div class="jetpack-module-actions">
2599 <?php if ( $jetpack_connected ) : ?>
2600 <?php if ( !$activated && current_user_can( 'manage_options' ) && apply_filters( 'jetpack_can_activate_' . $module, true ) ) : ?>
2601 <a href="<?php echo esc_url( $toggle_url ); ?>" class="<?php echo ( 'inactive' == $css ? ' button-primary' : ' button-secondary' ); ?>"><?php echo $toggle; ?></a>&nbsp;
2602 <?php endif; ?>
2603
2604 <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
2605
2606 <?php
2607 if ( current_user_can( 'manage_options' ) && apply_filters( 'jetpack_module_configurable_' . $module, false ) ) {
2608 echo '<a href="' . esc_attr( Jetpack::module_configuration_url( $module ) ) . '" class="jetpack-configure-button button-secondary">' . __( 'Configure', 'jetpack' ) . '</a>';
2609 }
2610 ?><?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; ?>
2611
2612 <?php else : ?>
2613 <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
2614 <?php endif; ?>
2615 </div>
2616 </div>
2617 <?php if ( 'inactive' == $css && $jetpack_connected ) : ?>
2618 <script type="text/javascript">
2619 jQuery( '#<?php echo esc_js( $module ); ?>' ).bind( 'click', function(e){
2620 if ( !jQuery(e.target).hasClass('more-info-link') )
2621 document.location.href = '<?php echo str_replace( '&amp;', '&', esc_js( esc_url( $toggle_url ) ) ); ?>';
2622 } );
2623 </script>
2624 <?php endif; ?>
2625
2626 <div id="jp-more-info-<?php echo esc_attr( $module ); ?>" style="display:none;">
2627 <?php
2628 if ( $jetpack_connected && has_action( 'jetpack_module_more_info_connected_' . $module ) )
2629 do_action( 'jetpack_module_more_info_connected_' . $module );
2630 else
2631 do_action( 'jetpack_module_more_info_' . $module );
2632 ?>
2633 </div>
2634
2635 <?php
2636 $counter++;
2637 }
2638
2639 // Add in some "Coming soon..." placeholders to fill up the current row and one more
2640 for ( $i = 0; $i < 4; $i++ ) { ?>
2641 <div class="jetpack-module placeholder"<?php if ( $i > 8 - $counter ) echo ' style="display: none;"'; ?>>
2642 <h3><?php _e( 'Coming soon&#8230;', 'jetpack' ) ?></h3>
2643 </div>
2644 <?php
2645 }
2646
2647 echo '</div><!-- .module-container -->';
2648 }
2649
2650 function check_news_subscription() {
2651 if ( !$this->current_user_is_connection_owner() ) {
2652 exit;
2653 }
2654
2655 Jetpack::load_xml_rpc_client();
2656 $xml = new Jetpack_IXR_Client( array(
2657 'user_id' => JETPACK_MASTER_USER,
2658 ) );
2659 $xml->query( 'jetpack.checkNewsSubscription' );
2660 if ( $xml->isError() ) {
2661 printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
2662 } else {
2663 print_r( $xml->getResponse() );
2664 }
2665 exit;
2666 }
2667
2668 function subscribe_to_news() {
2669 if ( !$this->current_user_is_connection_owner() ) {
2670 exit;
2671 }
2672
2673 Jetpack::load_xml_rpc_client();
2674 $xml = new Jetpack_IXR_Client( array(
2675 'user_id' => JETPACK_MASTER_USER,
2676 ) );
2677 $xml->query( 'jetpack.subscribeToNews' );
2678 if ( $xml->isError() ) {
2679 printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
2680 } else {
2681 print_r( $xml->getResponse() );
2682 }
2683 exit;
2684 }
2685
2686 /* Client API */
2687
2688 /**
2689 * Returns the requested Jetpack API URL
2690 *
2691 * @return string
2692 */
2693 public static function api_url( $relative_url ) {
2694 return trailingslashit( JETPACK__API_BASE . $relative_url ) . JETPACK__API_VERSION . '/';
2695 }
2696
2697 /**
2698 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
2699 */
2700 public static function fix_url_for_bad_hosts( $url, &$args ) {
2701 if ( 0 !== strpos( $url, 'https://' ) ) {
2702 return $url;
2703 }
2704
2705 switch ( JETPACK_CLIENT__HTTPS ) {
2706 case 'ALWAYS' :
2707 return $url;
2708 case 'NEVER' :
2709 return substr_replace( $url, '', 4, 1 );
2710 // default : case 'AUTO' :
2711 }
2712
2713 $jetpack = Jetpack::init();
2714
2715 // Yay! Your host is good!
2716 if ( wp_http_supports( array( 'ssl' => true ) ) ) {
2717 return $url;
2718 }
2719
2720 // Boo! Your host is bad and makes Jetpack cry!
2721 return substr_replace( $url, '', 4, 1 );
2722 }
2723
2724 /**
2725 * Returns the Jetpack XML-RPC API
2726 *
2727 * @return string
2728 */
2729 public static function xmlrpc_api_url() {
2730 $base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
2731 return untrailingslashit( $base ) . '/xmlrpc.php';
2732 }
2733
2734 /**
2735 * @return bool|WP_Error
2736 */
2737 public static function register() {
2738 Jetpack::update_option( 'register', wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 ) );
2739
2740 @list( $secret_1, $secret_2, $secret_eol ) = explode( ':', Jetpack::get_option( 'register' ) );
2741 if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() )
2742 return new Jetpack_Error( 'missing_secrets' );
2743
2744 $timeout = (int) ini_get( 'max_execution_time' );
2745 if ( !$timeout )
2746 $timeout = 30;
2747 $timeout = intval( $timeout / 2 );
2748
2749 $gmt_offset = get_option( 'gmt_offset' );
2750 if ( !$gmt_offset ) {
2751 $gmt_offset = 0;
2752 }
2753
2754 $stats_options = get_option( 'stats_options' );
2755 $stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
2756
2757 $args = array(
2758 'method' => 'POST',
2759 'body' => array(
2760 'siteurl' => site_url(),
2761 'home' => home_url(),
2762 'gmt_offset' => $gmt_offset,
2763 'timezone_string' => (string) get_option( 'timezone_string' ),
2764 'site_name' => (string) get_option( 'blogname' ),
2765 'secret_1' => $secret_1,
2766 'secret_2' => $secret_2,
2767 'site_lang' => get_locale(),
2768 'timeout' => $timeout,
2769 'stats_id' => $stats_id,
2770 ),
2771 'headers' => array(
2772 'Accept' => 'application/json',
2773 ),
2774 'timeout' => $timeout,
2775 );
2776 $response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ), $args ), $args, true );
2777
2778 if ( is_wp_error( $response ) ) {
2779 return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
2780 }
2781
2782 $code = wp_remote_retrieve_response_code( $response );
2783 $entity = wp_remote_retrieve_body( $response );
2784
2785 if ( $entity )
2786 $json = json_decode( $entity );
2787 else
2788 $json = false;
2789
2790 $code_type = intval( $code / 100 );
2791 if ( 5 == $code_type ) {
2792 return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
2793 } elseif ( 408 == $code ) {
2794 return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
2795 } elseif ( !empty( $json->error ) ) {
2796 $error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
2797 return new Jetpack_Error( (string) $json->error, $error_description, $code );
2798 } elseif ( 200 != $code ) {
2799 return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
2800 }
2801
2802 // Jetpack ID error block
2803 if ( empty( $json->jetpack_id ) ) {
2804 return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
2805 } elseif ( ! is_scalar( $json->jetpack_id ) ) {
2806 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 );
2807 } elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
2808 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);
2809 }
2810
2811 if ( empty( $json->jetpack_secret ) || !is_string( $json->jetpack_secret ) )
2812 return new Jetpack_Error( 'jetpack_secret', '', $code );
2813
2814 if ( isset( $json->jetpack_public ) ) {
2815 $jetpack_public = (int) $json->jetpack_public;
2816 } else {
2817 $jetpack_public = false;
2818 }
2819
2820 Jetpack::update_options( array(
2821 'id' => (int) $json->jetpack_id,
2822 'blog_token' => (string) $json->jetpack_secret,
2823 'public' => $jetpack_public,
2824 ) );
2825
2826 return true;
2827 }
2828
2829
2830 /* Client Server API */
2831
2832 /**
2833 * Loads the Jetpack XML-RPC client
2834 */
2835 public static function load_xml_rpc_client() {
2836 require_once ABSPATH . WPINC . '/class-IXR.php';
2837 require_once dirname( __FILE__ ) . '/class.jetpack-ixr-client.php';
2838 }
2839
2840 function verify_xml_rpc_signature() {
2841 if ( $this->xmlrpc_verification ) {
2842 return $this->xmlrpc_verification;
2843 }
2844
2845 // It's not for us
2846 if ( !isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
2847 return false;
2848 }
2849
2850 @list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
2851 if (
2852 empty( $token_key )
2853 ||
2854 empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
2855 ) {
2856 return false;
2857 }
2858
2859 if ( '0' === $user_id ) {
2860 $token_type = 'blog';
2861 $user_id = 0;
2862 } else {
2863 $token_type = 'user';
2864 if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
2865 return false;
2866 }
2867 $user_id = (int) $user_id;
2868
2869 $user = new WP_User( $user_id );
2870 if ( ! $user || ! $user->exists() ) {
2871 return false;
2872 }
2873 }
2874
2875 $token = Jetpack_Data::get_access_token( $user_id );
2876 if ( !$token ) {
2877 return false;
2878 }
2879
2880 if ( 0 !== strpos( $token->secret, "$token_key." ) ) {
2881 return false;
2882 }
2883
2884 require_once dirname( __FILE__ ) . '/class.jetpack-signature.php';
2885
2886 $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack::get_option( 'time_diff' ) );
2887 if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
2888 $post_data = $_POST;
2889 $file_hashes = array();
2890 foreach ( $post_data as $post_data_key => $post_data_value ) {
2891 if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
2892 continue;
2893 }
2894 $post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
2895 $file_hashes[$post_data_key] = $post_data_value;
2896 }
2897
2898 foreach ( $file_hashes as $post_data_key => $post_data_value ) {
2899 unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
2900 $post_data[$post_data_key] = $post_data_value;
2901 }
2902
2903 ksort( $post_data );
2904
2905 $body = http_build_query( stripslashes_deep( $post_data ) );
2906 } elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
2907 $body = file_get_contents( 'php://input' );
2908 } else {
2909 $body = null;
2910 }
2911 $signature = $jetpack_signature->sign_current_request( array(
2912 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body
2913 ) );
2914
2915 if ( !$signature ) {
2916 return false;
2917 } else if ( is_wp_error( $signature ) ) {
2918 return $signature;
2919 } else if ( $signature !== $_GET['signature'] ) {
2920 return false;
2921 }
2922
2923 $timestamp = (int) $_GET['timestamp'];
2924 $nonce = stripslashes( (string) $_GET['nonce'] );
2925
2926 if ( !$this->add_nonce( $timestamp, $nonce ) ) {
2927 return false;
2928 }
2929
2930 $this->xmlrpc_verification = array(
2931 'type' => $token_type,
2932 'user_id' => $token->external_user_id,
2933 );
2934
2935 return $this->xmlrpc_verification;
2936 }
2937
2938 /**
2939 * Authenticates XML-RPC and other requests from the Jetpack Server
2940 */
2941 function authenticate_jetpack( $user, $username, $password ) {
2942 if ( is_a( $user, 'WP_User' ) ) {
2943 return $user;
2944 }
2945
2946 $token_details = $this->verify_xml_rpc_signature();
2947
2948 if ( ! $token_details || is_wp_error( $token_details ) ) {
2949 return $user;
2950 }
2951
2952 if ( 'user' !== $token_details['type'] ) {
2953 return $user;
2954 }
2955
2956 if ( ! $token_details['user_id'] ) {
2957 return $user;
2958 }
2959
2960 nocache_headers();
2961
2962 return new WP_User( $token_details['user_id'] );
2963 }
2964
2965 function add_nonce( $timestamp, $nonce ) {
2966 global $wpdb;
2967 static $nonces_used_this_request = array();
2968
2969 if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
2970 return $nonces_used_this_request["$timestamp:$nonce"];
2971 }
2972
2973 // This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
2974 $timestamp = (int) $timestamp;
2975 $nonce = $wpdb->escape( $nonce );
2976
2977 // Raw query so we can avoid races: add_option will also update
2978 $show_errors = $wpdb->show_errors( false );
2979 $return = $wpdb->query( $wpdb->prepare(
2980 "INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
2981 "jetpack_nonce_{$timestamp}_{$nonce}",
2982 time(),
2983 'no'
2984 ) );
2985 $wpdb->show_errors( $show_errors );
2986
2987 $nonces_used_this_request["$timestamp:$nonce"] = $return;
2988
2989 return $return;
2990 }
2991
2992 /**
2993 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
2994 * Capture it here so we can verify the signature later.
2995 */
2996 function xmlrpc_methods( $methods ) {
2997 $this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
2998 return $methods;
2999 }
3000
3001 function xmlrpc_options( $options ) {
3002 $options['jetpack_version'] = array(
3003 'desc' => __( 'Jetpack Plugin Version' , 'jetpack'),
3004 'readonly' => true,
3005 'value' => JETPACK__VERSION,
3006 );
3007
3008 $options['jetpack_client_id'] = array(
3009 'desc' => __( 'The Client ID/WP.com Blog ID of this site' , 'jetpack'),
3010 'readonly' => true,
3011 'value' => Jetpack::get_option( 'id' ),
3012 );
3013 return $options;
3014 }
3015
3016 public static function clean_nonces( $all = false ) {
3017 global $wpdb;
3018
3019 $sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
3020 $sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
3021
3022 if ( true !== $all ) {
3023 $sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
3024 $sql_args[] = time() - 3600;
3025 }
3026
3027 $sql .= ' LIMIT 100';
3028
3029 $sql = $wpdb->prepare( $sql, $sql_args );
3030
3031 for ( $i = 0; $i < 1000; $i++ ) {
3032 if ( !$wpdb->query( $sql ) ) {
3033 break;
3034 }
3035 }
3036 }
3037
3038 /**
3039 * State is passed via cookies from one request to the next, but never to subsequent requests.
3040 * SET: state( $key, $value );
3041 * GET: $value = state( $key );
3042 *
3043 * @param string $key
3044 * @param string $value
3045 * @param bool $restate private
3046 */
3047 public static function state( $key = null, $value = null, $restate = false ) {
3048 static $state = array();
3049 static $path, $domain;
3050 if ( !isset( $path ) ) {
3051 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
3052 $admin_url = Jetpack::admin_url();
3053 $bits = parse_url( $admin_url );
3054
3055 if ( is_array( $bits ) ) {
3056 $path = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
3057 $domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
3058 } else {
3059 $path = $domain = null;
3060 }
3061 }
3062
3063 // Extract state from cookies and delete cookies
3064 if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
3065 $yum = $_COOKIE[ 'jetpackState' ];
3066 unset( $_COOKIE[ 'jetpackState' ] );
3067 foreach ( $yum as $k => $v ) {
3068 if ( strlen( $v ) )
3069 $state[ $k ] = $v;
3070 setcookie( "jetpackState[$k]", false, 0, $path, $domain );
3071 }
3072 }
3073
3074 if ( $restate ) {
3075 foreach ( $state as $k => $v ) {
3076 setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
3077 }
3078 return;
3079 }
3080
3081 // Get a state variable
3082 if ( isset( $key ) && !isset( $value ) ) {
3083 if ( array_key_exists( $key, $state ) )
3084 return $state[ $key ];
3085 return null;
3086 }
3087
3088 // Set a state variable
3089 if ( isset ( $key ) && isset( $value ) ) {
3090 $state[ $key ] = $value;
3091 setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
3092 }
3093 }
3094
3095 public static function restate() {
3096 Jetpack::state( null, null, true );
3097 }
3098
3099 public static function check_privacy( $file ) {
3100 static $is_site_publicly_accessible = null;
3101
3102 if ( is_null( $is_site_publicly_accessible ) ) {
3103 $is_site_publicly_accessible = false;
3104
3105 Jetpack::load_xml_rpc_client();
3106 $rpc = new Jetpack_IXR_Client();
3107
3108 $success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
3109 if ( $success ) {
3110 $response = $rpc->getResponse();
3111 if ( $response ) {
3112 $is_site_publicly_accessible = true;
3113 }
3114 }
3115
3116 Jetpack::update_option( 'public', (int) $is_site_publicly_accessible );
3117 }
3118
3119 if ( $is_site_publicly_accessible ) {
3120 return;
3121 }
3122
3123 $module_slug = self::get_module_slug( $file );
3124
3125 $privacy_checks = Jetpack::state( 'privacy_checks' );
3126 if ( !$privacy_checks ) {
3127 $privacy_checks = $module_slug;
3128 } else {
3129 $privacy_checks .= ",$module_slug";
3130 }
3131
3132 Jetpack::state( 'privacy_checks', $privacy_checks );
3133 }
3134
3135 /**
3136 * Helper method for multicall XMLRPC.
3137 */
3138 public static function xmlrpc_async_call() {
3139 global $blog_id;
3140 static $clients = array();
3141
3142 $client_blog_id = is_multisite() ? $blog_id : 0;
3143
3144 if ( !isset( $clients[$client_blog_id] ) ) {
3145 Jetpack::load_xml_rpc_client();
3146 $clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array(
3147 'user_id' => JETPACK_MASTER_USER,
3148 ) );
3149 ignore_user_abort( true );
3150 add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
3151 }
3152
3153 $args = func_get_args();
3154
3155 if ( !empty( $args[0] ) ) {
3156 call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
3157 } elseif ( is_multisite() ) {
3158 foreach ( $clients as $client_blog_id => $client ) {
3159 if ( !$client_blog_id || empty( $client->calls ) ) {
3160 continue;
3161 }
3162
3163 $switch_success = switch_to_blog( $client_blog_id, true );
3164 if ( !$switch_success ) {
3165 continue;
3166 }
3167
3168 flush();
3169 $client->query();
3170
3171 restore_current_blog();
3172 }
3173 } else {
3174 if ( isset( $clients[0] ) && !empty( $clients[0]->calls ) ) {
3175 flush();
3176 $clients[0]->query();
3177 }
3178 }
3179 }
3180
3181 public static function staticize_subdomain( $url ) {
3182 $host = parse_url( $url, PHP_URL_HOST );
3183 if ( !preg_match( '/.?(?:wordpress|wp)\.com$/', $host ) ) {
3184 return $url;
3185 }
3186
3187 if ( is_ssl() ) {
3188 return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
3189 }
3190
3191 srand( crc32( basename( $url ) ) );
3192 $static_counter = rand( 0, 2 );
3193 srand(); // this resets everything that relies on this, like array_rand() and shuffle()
3194
3195 return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
3196 }
3197
3198 /* JSON API Authorization */
3199
3200 /**
3201 * Handles the login action for Authorizing the JSON API
3202 */
3203 function login_form_json_api_authorization() {
3204 $this->verify_json_api_authorization_request();
3205
3206 add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
3207
3208 add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
3209 add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
3210 add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
3211 }
3212
3213 // Make sure the login form is POSTed to the signed URL so we can reverify the request
3214 function post_login_form_to_signed_url( $url, $path, $scheme ) {
3215 if ( 'wp-login.php' !== $path || 'login_post' !== $scheme ) {
3216 return $url;
3217 }
3218
3219 return "$url?{$_SERVER['QUERY_STRING']}";
3220 }
3221
3222 // Make sure the POSTed request is handled by the same action
3223 function preserve_action_in_login_form_for_json_api_authorization() {
3224 echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
3225 }
3226
3227 // If someone logs in to approve API access, store the Access Code in usermeta
3228 function store_json_api_authorization_token( $user_login, $user ) {
3229 add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
3230 add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
3231 $token = wp_generate_password( 32, false );
3232 update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
3233 }
3234
3235 // Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
3236 function allow_wpcom_public_api_domain( $domains ) {
3237 $domains[] = 'public-api.wordpress.com';
3238 return $domains;
3239 }
3240
3241 // Add the Access Code details to the public-api.wordpress.com redirect
3242 function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
3243 return add_query_arg( urlencode_deep( array(
3244 'jetpack-code' => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
3245 'jetpack-user-id' => (int) $user->ID,
3246 'jetpack-state' => $this->json_api_authorization_request['state'],
3247 ) ), $redirect_to );
3248 }
3249
3250 // Verifies the request by checking the signature
3251 function verify_json_api_authorization_request() {
3252 require_once dirname( __FILE__ ) . '/class.jetpack-signature.php';
3253
3254 $token = Jetpack_Data::get_access_token( 1 );
3255 if ( !$token || empty( $token->secret ) ) {
3256 wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack') );
3257 }
3258
3259 $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' );
3260
3261 $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack::get_option( 'time_diff' ) );
3262 $signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
3263 if ( !$signature ) {
3264 wp_die( $die_error );
3265 } else if ( is_wp_error( $signature ) ) {
3266 wp_die( $die_error );
3267 } else if ( $signature !== $_GET['signature'] ) {
3268 if ( is_ssl() ) {
3269 // 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
3270 $signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
3271 if ( !$signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
3272 wp_die( $die_error );
3273 }
3274 } else {
3275 wp_die( $die_error );
3276 }
3277 }
3278
3279 $timestamp = (int) $_GET['timestamp'];
3280 $nonce = stripslashes( (string) $_GET['nonce'] );
3281
3282 if ( !$this->add_nonce( $timestamp, $nonce ) ) {
3283 // De-nonce the nonce, at least for 5 minutes.
3284 // 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)
3285 $old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
3286 if ( $old_nonce_time < time() - 300 ) {
3287 wp_die( __( 'The authorization process expired. Please go back and try again.' , 'jetpack') );
3288 }
3289 }
3290
3291 $data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
3292 $data_filters = array(
3293 'state' => 'opaque',
3294 'client_id' => 'int',
3295 'client_title' => 'string',
3296 'client_image' => 'url',
3297 );
3298
3299 foreach ( $data_filters as $key => $sanitation ) {
3300 if ( !isset( $data->$key ) ) {
3301 wp_die( $die_error );
3302 }
3303
3304 switch ( $sanitation ) {
3305 case 'int' :
3306 $this->json_api_authorization_request[$key] = (int) $data->$key;
3307 break;
3308 case 'opaque' :
3309 $this->json_api_authorization_request[$key] = (string) $data->$key;
3310 break;
3311 case 'string' :
3312 $this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
3313 break;
3314 case 'url' :
3315 $this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
3316 break;
3317 }
3318 }
3319
3320 if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
3321 wp_die( $die_error );
3322 }
3323 }
3324
3325 function login_message_json_api_authorization( $message ) {
3326 return '<p class="message">' . sprintf(
3327 esc_html__( '%s wants to access your site&#8217;s data. Log in to authorize that access.' , 'jetpack'),
3328 '<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
3329 ) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
3330 }
3331 }
3332
3333 class Jetpack_Client {
3334 /**
3335 * Makes an authorized remote request using Jetpack_Signature
3336 *
3337 * @return array|WP_Error WP HTTP response on success
3338 */
3339 public static function remote_request( $args, $body = null ) {
3340 $defaults = array(
3341 'url' => '',
3342 'user_id' => 0,
3343 'blog_id' => 0,
3344 'auth_location' => JETPACK_CLIENT__AUTH_LOCATION,
3345 'method' => 'POST',
3346 'timeout' => 10,
3347 'redirection' => 0,
3348 );
3349
3350 $args = wp_parse_args( $args, $defaults );
3351
3352 $args['blog_id'] = (int) $args['blog_id'];
3353
3354 if ( 'header' != $args['auth_location'] ) {
3355 $args['auth_location'] = 'query_string';
3356 }
3357
3358 $token = Jetpack_Data::get_access_token( $args['user_id'] );
3359 if ( !$token ) {
3360 return new Jetpack_Error( 'missing_token' );
3361 }
3362
3363 $method = strtoupper( $args['method'] );
3364
3365 $timeout = intval( $args['timeout'] );
3366
3367 $redirection = $args['redirection'];
3368
3369 $request = compact( 'method', 'body', 'timeout', 'redirection' );
3370
3371 @list( $token_key, $secret ) = explode( '.', $token->secret );
3372 if ( empty( $token ) || empty( $secret ) ) {
3373 return new Jetpack_Error( 'malformed_token' );
3374 }
3375
3376 $token_key = sprintf( '%s:%d:%d', $token_key, JETPACK__API_VERSION, $token->external_user_id );
3377
3378 require_once dirname( __FILE__ ) . '/class.jetpack-signature.php';
3379
3380 $time_diff = (int) Jetpack::get_option( 'time_diff' );
3381 $jetpack_signature = new Jetpack_Signature( $token->secret, $time_diff );
3382
3383 $timestamp = time() + $time_diff;
3384 $nonce = wp_generate_password( 10, false );
3385
3386 // Kind of annoying. Maybe refactor Jetpack_Signature to handle body-hashing
3387 if ( is_null( $body ) ) {
3388 $body_hash = '';
3389 } else {
3390 if ( !is_string( $body ) ) {
3391 return new Jetpack_Error( 'invalid_body', 'Body is malformed.' );
3392 }
3393 $body_hash = jetpack_sha1_base64( $body );
3394 }
3395
3396 $auth = array(
3397 'token' => $token_key,
3398 'timestamp' => $timestamp,
3399 'nonce' => $nonce,
3400 'body-hash' => $body_hash,
3401 );
3402
3403 if ( false !== strpos( $args['url'], 'xmlrpc.php' ) ) {
3404 $url_args = array( 'for' => 'jetpack' );
3405 } else {
3406 $url_args = array();
3407 }
3408
3409 if ( 'header' != $args['auth_location'] ) {
3410 $url_args += $auth;
3411 }
3412
3413 $url = add_query_arg( urlencode_deep( $url_args ), $args['url'] );
3414 $url = Jetpack::fix_url_for_bad_hosts( $url, $request );
3415
3416 $signature = $jetpack_signature->sign_request( $token_key, $timestamp, $nonce, $body_hash, $method, $url, $body, false );
3417
3418 if ( !$signature || is_wp_error( $signature ) ) {
3419 return $signature;
3420 }
3421
3422 // Send an Authorization header so various caches/proxies do the right thing
3423 $auth['signature'] = $signature;
3424 $auth['version'] = JETPACK__VERSION;
3425 $header_pieces = array();
3426 foreach ( $auth as $key => $value ) {
3427 $header_pieces[] = sprintf( '%s="%s"', $key, $value );
3428 }
3429 $request['headers'] = array(
3430 'Authorization' => "X_JETPACK " . join( ' ', $header_pieces ),
3431 );
3432
3433 if ( 'header' != $args['auth_location'] ) {
3434 $url = add_query_arg( 'signature', urlencode( $signature ), $url );
3435 }
3436
3437 return Jetpack_Client::_wp_remote_request( $url, $request );
3438 }
3439
3440 /**
3441 * Wrapper for wp_remote_request(). Turns off SSL verification for certain SSL errors.
3442 * This is lame, but many, many, many hosts have misconfigured SSL.
3443 *
3444 * When Jetpack is registered, the jetpack_fallback_no_verify_ssl_certs option is set to the current time if:
3445 * 1. a certificate error is found AND
3446 * 2. not verifying the certificate works around the problem.
3447 *
3448 * The option is checked on each request.
3449 *
3450 * @internal
3451 * @todo: Better fallbacks (bundled certs?), feedback, UI, ....
3452 * @see Jetpack::fix_url_for_bad_hosts()
3453 *
3454 * @return array|WP_Error WP HTTP response on success
3455 */
3456 public static function _wp_remote_request( $url, $args, $set_fallback = false ) {
3457 $fallback = Jetpack::get_option( 'fallback_no_verify_ssl_certs' );
3458 if ( false === $fallback ) {
3459 Jetpack::update_option( 'fallback_no_verify_ssl_certs', 0 );
3460 }
3461
3462 if ( (int) $fallback ) {
3463 // We're flagged to fallback
3464 $args['sslverify'] = false;
3465 }
3466
3467 $response = wp_remote_request( $url, $args );
3468
3469 if (
3470 !$set_fallback // We're not allowed to set the flag on this request, so whatever happens happens
3471 ||
3472 isset( $args['sslverify'] ) && !$args['sslverify'] // No verification - no point in doing it again
3473 ||
3474 !is_wp_error( $response ) // Let it ride
3475 ) {
3476 Jetpack_Client::set_time_diff( $response, $set_fallback );
3477 return $response;
3478 }
3479
3480 // At this point, we're not flagged to fallback and we are allowed to set the flag on this request.
3481
3482 $message = $response->get_error_message();
3483
3484 // Is it an SSL Certificate verification error?
3485 if (
3486 false === strpos( $message, '14090086' ) // OpenSSL SSL3 certificate error
3487 &&
3488 false === strpos( $message, '1407E086' ) // OpenSSL SSL2 certificate error
3489 &&
3490 false === strpos( $message, 'error setting certificate verify locations' ) // cURL CA bundle not found
3491 &&
3492 false === strpos( $message, 'Peer certificate cannot be authenticated with' ) // cURL CURLE_SSL_CACERT: CA bundle found, but not helpful
3493 // different versions of curl have different error messages
3494 // this string should catch them all
3495 &&
3496 false === strpos( $message, 'Problem with the SSL CA cert' ) // cURL CURLE_SSL_CACERT_BADFILE: probably access rights
3497 ) {
3498 // No, it is not.
3499 return $response;
3500 }
3501
3502 // Redo the request without SSL certificate verification.
3503 $args['sslverify'] = false;
3504 $response = wp_remote_request( $url, $args );
3505
3506 if ( !is_wp_error( $response ) ) {
3507 // The request went through this time, flag for future fallbacks
3508 Jetpack::update_option( 'fallback_no_verify_ssl_certs', time() );
3509 Jetpack_Client::set_time_diff( $response, $set_fallback );
3510 }
3511
3512 return $response;
3513 }
3514
3515 public static function set_time_diff( &$response, $force_set = false ) {
3516 $code = wp_remote_retrieve_response_code( $response );
3517
3518 // Only trust the Date header on some responses
3519 if ( 200 != $code && 304 != $code && 400 != $code && 401 != $code ) {
3520 return;
3521 }
3522
3523 if ( !$date = wp_remote_retrieve_header( $response, 'date' ) ) {
3524 return;
3525 }
3526
3527 if ( 0 >= $time = (int) strtotime( $date ) ) {
3528 return;
3529 }
3530
3531 $time_diff = $time - time();
3532
3533 if ( $force_set ) { // during register
3534 Jetpack::update_option( 'time_diff', $time_diff );
3535 } else { // otherwise
3536 $old_diff = Jetpack::get_option( 'time_diff' );
3537 if ( false === $old_diff || abs( $time_diff - (int) $old_diff ) > 10 ) {
3538 Jetpack::update_option( 'time_diff', $time_diff );
3539 }
3540 }
3541 }
3542 }
3543
3544 class Jetpack_Data {
3545 /**
3546 * Gets locally stored token
3547 *
3548 * @return object|false
3549 */
3550 public static function get_access_token( $user_id = false ) {
3551 if ( $user_id ) {
3552 if ( !$tokens = Jetpack::get_option( 'user_tokens' ) ) {
3553 return false;
3554 }
3555 if ( $user_id === JETPACK_MASTER_USER ) {
3556 if ( !$user_id = Jetpack::get_option( 'master_user' ) ) {
3557 return false;
3558 }
3559 }
3560 if ( !isset( $tokens[$user_id] ) || !$token = $tokens[$user_id] ) {
3561 return false;
3562 }
3563 $token_chunks = explode( '.', $token );
3564 if ( empty( $token_chunks[1] ) || empty( $token_chunks[2] ) ) {
3565 return false;
3566 }
3567 if ( $user_id != $token_chunks[2] ) {
3568 return false;
3569 }
3570 $token = "{$token_chunks[0]}.{$token_chunks[1]}";
3571 } else {
3572 $token = Jetpack::get_option( 'blog_token' );
3573 if ( empty( $token ) ) {
3574 return false;
3575 }
3576 }
3577
3578 return (object) array(
3579 'secret' => $token,
3580 'external_user_id' => (int) $user_id,
3581 );
3582 }
3583 }
3584
3585 /**
3586 * Client = Plugin
3587 * Client Server = API Methods the Plugin must respond to
3588 *
3589 * @todo Roll this into Jetpack? There's only one 'public' method now: ::authorize().
3590 */
3591 class Jetpack_Client_Server {
3592 function authorize() {
3593 $data = stripslashes_deep( $_GET );
3594
3595 $args = array();
3596
3597 $redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
3598
3599 do {
3600 $jetpack = Jetpack::init();
3601 $role = $jetpack->translate_current_user_to_role();
3602 if ( !$role ) {
3603 Jetpack::state( 'error', 'no_role' );
3604 break;
3605 }
3606
3607 $cap = $jetpack->translate_role_to_cap( $role );
3608 if ( !$cap ) {
3609 Jetpack::state( 'error', 'no_cap' );
3610 break;
3611 }
3612
3613 check_admin_referer( "jetpack-authorize_{$role}_{$redirect}" );
3614
3615 if ( !empty( $data['error'] ) ) {
3616 Jetpack::state( 'error', $data['error'] );
3617 break;
3618 }
3619
3620 if ( empty( $data['state'] ) ) {
3621 Jetpack::state( 'error', 'no_state' );
3622 break;
3623 }
3624
3625 if ( !ctype_digit( $data['state'] ) ) {
3626 Jetpack::state( 'error', 'invalid_state' );
3627 break;
3628 }
3629
3630 $current_user_id = get_current_user_id();
3631 if ( $current_user_id != $data['state'] ) {
3632 Jetpack::state( 'error', 'wrong_state' );
3633 break;
3634 }
3635
3636 if ( empty( $data['code'] ) ) {
3637 Jetpack::state( 'error', 'no_code' );
3638 break;
3639 }
3640
3641 $token = $this->get_token( $data );
3642
3643 if ( is_wp_error( $token ) ) {
3644 if ( $error = $token->get_error_code() )
3645 Jetpack::state( 'error', $error );
3646 else
3647 Jetpack::state( 'error', 'invalid_token' );
3648
3649 Jetpack::state( 'error_description', $token->get_error_message() );
3650
3651 break;
3652 }
3653
3654 if ( !$token ) {
3655 Jetpack::state( 'error', 'no_token' );
3656 break;
3657 }
3658
3659 $is_master_user = ! Jetpack::is_active();
3660
3661 Jetpack::update_user_token( $current_user_id, sprintf( '%s.%d', $token, $current_user_id ), $is_master_user );
3662
3663
3664 if ( $is_master_user ) {
3665 Jetpack::state( 'message', 'authorized' );
3666 } else {
3667 Jetpack::state( 'message', 'linked' );
3668 // Don't activate anything since we are just connecting a user.
3669 break;
3670 }
3671
3672 if ( $active_modules = Jetpack::get_option( 'active_modules' ) ) {
3673 Jetpack::delete_option( 'active_modules' );
3674
3675 Jetpack::activate_default_modules( 999, 1, $active_modules );
3676 } else {
3677 Jetpack::activate_default_modules();
3678 }
3679
3680 $jetpack->sync->register( 'noop' ); // Spawn a sync to make sure the Jetpack Servers know what modules are active.
3681
3682 // Start nonce cleaner
3683 wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3684 wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
3685 } while ( false );
3686
3687 if ( wp_validate_redirect( $redirect ) ) {
3688 wp_safe_redirect( $redirect );
3689 } else {
3690 wp_safe_redirect( Jetpack::admin_url() );
3691 }
3692
3693 exit;
3694 }
3695
3696 public static function deactivate_plugin( $probable_file, $probable_title ) {
3697 if ( is_plugin_active( $probable_file ) ) {
3698 deactivate_plugins( $probable_file );
3699 return 1;
3700 } else {
3701 // If the plugin is not in the usual place, try looking through all active plugins.
3702 $active_plugins = get_option( 'active_plugins', array() );
3703 foreach ( $active_plugins as $plugin ) {
3704 $data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
3705 if ( $data['Name'] == $probable_title ) {
3706 deactivate_plugins( $plugin );
3707 return 1;
3708 }
3709 }
3710 }
3711
3712 return 0;
3713 }
3714
3715 /**
3716 * @return object|WP_Error
3717 */
3718 function get_token( $data ) {
3719 $jetpack = Jetpack::init();
3720 $role = $jetpack->translate_current_user_to_role();
3721
3722 if ( !$role ) {
3723 return new Jetpack_Error( 'role', __( 'An administrator for this blog must set up the Jetpack connection.', 'jetpack' ) );
3724 }
3725
3726 $client_secret = Jetpack_Data::get_access_token();
3727 if ( !$client_secret ) {
3728 return new Jetpack_Error( 'client_secret', __( 'You need to register your Jetpack before connecting it.', 'jetpack' ) );
3729 }
3730
3731 $redirect = isset( $data['redirect'] ) ? esc_url_raw( (string) $data['redirect'] ) : '';
3732
3733 $body = array(
3734 'client_id' => Jetpack::get_option( 'id' ),
3735 'client_secret' => $client_secret->secret,
3736 'grant_type' => 'authorization_code',
3737 'code' => $data['code'],
3738 'redirect_uri' => add_query_arg( array(
3739 'action' => 'authorize',
3740 '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3741 'redirect' => $redirect ? urlencode( $redirect ) : false,
3742 ), menu_page_url( 'jetpack', false ) ),
3743 );
3744
3745 $args = array(
3746 'method' => 'POST',
3747 'body' => $body,
3748 'headers' => array(
3749 'Accept' => 'application/json',
3750 ),
3751 );
3752 $response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'token' ), $args ), $args );
3753
3754 if ( is_wp_error( $response ) ) {
3755 return new Jetpack_Error( 'token_http_request_failed', $response->get_error_message() );
3756 }
3757
3758 $code = wp_remote_retrieve_response_code( $response );
3759 $entity = wp_remote_retrieve_body( $response );
3760
3761 if ( $entity )
3762 $json = json_decode( $entity );
3763 else
3764 $json = false;
3765
3766 if ( 200 != $code || !empty( $json->error ) ) {
3767 if ( empty( $json->error ) )
3768 return new Jetpack_Error( 'unknown', '', $code );
3769
3770 $error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
3771
3772 return new Jetpack_Error( (string) $json->error, $error_description, $code );
3773 }
3774
3775 if ( empty( $json->access_token ) || !is_scalar( $json->access_token ) ) {
3776 return new Jetpack_Error( 'access_token', '', $code );
3777 }
3778
3779 if ( empty( $json->token_type ) || 'X_JETPACK' != strtoupper( $json->token_type ) ) {
3780 return new Jetpack_Error( 'token_type', '', $code );
3781 }
3782
3783 if ( empty( $json->scope ) ) {
3784 return new Jetpack_Error( 'scope', 'No Scope', $code );
3785 }
3786 @list( $role, $hmac ) = explode( ':', $json->scope );
3787 if ( empty( $role ) || empty( $hmac ) ) {
3788 return new Jetpack_Error( 'scope', 'Malformed Scope', $code );
3789 }
3790 if ( $jetpack->sign_role( $role ) !== $json->scope ) {
3791 return new Jetpack_Error( 'scope', 'Invalid Scope', $code );
3792 }
3793
3794 if ( !$cap = $jetpack->translate_role_to_cap( $role ) )
3795 return new Jetpack_Error( 'scope', 'No Cap', $code );
3796 if ( !current_user_can( $cap ) )
3797 return new Jetpack_Error( 'scope', 'current_user_cannot', $code );
3798
3799 return (string) $json->access_token;
3800 }
3801 }
3802
3803
3804 /**
3805 * Request that a piece of data on this WordPress install be synced back to the
3806 * Jetpack server for remote processing/notifications/etc
3807 */
3808 class Jetpack_Sync {
3809 // What modules want to sync what content
3810 var $sync_conditions = array( 'posts' => array(), 'comments' => array() );
3811
3812 // We keep track of all the options registered for sync so that we can sync them all if needed
3813 var $sync_options = array();
3814
3815 // Keep trac of status transitions, which we wouldn't always know about on the Jetpack Servers but are important when deciding what to do with the sync.
3816 var $post_transitions = array();
3817 var $comment_transitions = array();
3818
3819 // Objects to sync
3820 var $sync = array();
3821
3822 function __construct() {
3823 // WP Cron action. Only used on upgrade
3824 add_action( 'jetpack_sync_all_registered_options', array( $this, 'sync_all_registered_options' ) );
3825 }
3826
3827 /* Static Methods for Modules */
3828
3829 /**
3830 * @param string $file __FILE__
3831 * @param array settings:
3832 * post_types => array( post_type slugs ): The post types to sync. Default: post, page
3833 * post_stati => array( post_status slugs ): The post stati to sync. Default: publish
3834 */
3835 static function sync_posts( $file, array $settings = null ) {
3836 $jetpack = Jetpack::init();
3837 $args = func_get_args();
3838 return call_user_func_array( array( $jetpack->sync, 'posts' ), $args );
3839 }
3840
3841 /**
3842 * @param string $file __FILE__
3843 * @param array settings:
3844 * post_types => array( post_type slugs ): The post types to sync. Default: post, page
3845 * post_stati => array( post_status slugs ): The post stati to sync. Default: publish
3846 * comment_types => array( comment_type slugs ): The comment types to sync. Default: '', comment, trackback, pingback
3847 * comment_stati => array( comment_status slugs ): The comment stati to sync. Default: approved
3848 */
3849 static function sync_comments( $file, array $settings = null ) {
3850 $jetpack = Jetpack::init();
3851 $args = func_get_args();
3852 return call_user_func_array( array( $jetpack->sync, 'comments' ), $args );
3853 }
3854
3855 /**
3856 * @param string $file __FILE__
3857 * @param string $option, Option name to sync
3858 * @param string $option ...
3859 */
3860 static function sync_options( $file, $option /*, $option, ... */ ) {
3861 $jetpack = Jetpack::init();
3862 $args = func_get_args();
3863 return call_user_func_array( array( $jetpack->sync, 'options' ), $args );
3864 }
3865
3866 /* Internal Methods */
3867
3868 /**
3869 * Create a sync object/request
3870 *
3871 * @param string $object Type of object to sync -- [ post | comment | option ]
3872 * @param int $id Unique identifier
3873 * @param array $settings
3874 */
3875 function register( $object, $id = false, array $settings = null ) {
3876 // Since we've registered something for sync, hook it up to execute on shutdown if we haven't already
3877 if ( !$this->sync ) {
3878 ignore_user_abort( true );
3879 add_action( 'shutdown', array( $this, 'sync' ), 9 ); // Right before async XML-RPC
3880 }
3881
3882 $defaults = array(
3883 'on_behalf_of' => array(), // What modules want this data
3884 );
3885 $settings = wp_parse_args( $settings, $defaults );
3886
3887 if ( !isset( $this->sync[$object] ) ) {
3888 $this->sync[$object] = array();
3889 }
3890
3891 // Store the settings for this object
3892 if (
3893 // First time for this object
3894 !isset( $this->sync[$object][$id] )
3895 ) {
3896 // Easy: store the current settings
3897 $this->sync[$object][$id] = $settings;
3898 } else {
3899 // Not as easy: we have to manually merge the settings from previous runs for this object with the settings for this run
3900
3901 $this->sync[$object][$id]['on_behalf_of'] = array_unique( array_merge( $this->sync[$object][$id]['on_behalf_of'], $settings['on_behalf_of'] ) );
3902 }
3903
3904 $delete_prefix = 'delete_';
3905 if ( 0 === strpos( $object, $delete_prefix ) ) {
3906 $unset_object = substr( $object, strlen( $delete_prefix ) );
3907 } else {
3908 $unset_object = "{$delete_prefix}{$object}";
3909 }
3910
3911 // Ensure post ... delete_post yields a delete operation
3912 // Ensure delete_post ... post yields a sync post operation
3913 // Ensure update_option() ... delete_option() ends up as a delete
3914 // Ensure delete_option() ... update_option() ends up as an update
3915 // Etc.
3916 unset( $this->sync[$unset_object][$id] );
3917
3918 return true;
3919 }
3920
3921 function get_common_sync_data() {
3922 $available_modules = Jetpack::get_available_modules();
3923 $active_modules = Jetpack::get_active_modules();
3924 $modules = array();
3925 foreach ( $available_modules as $available_module ) {
3926 $modules[$available_module] = in_array( $available_module, $active_modules );
3927 }
3928 $modules['vaultpress'] = class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' );
3929
3930 $sync_data = array(
3931 'modules' => $modules,
3932 'version' => JETPACK__VERSION,
3933 );
3934
3935 return $sync_data;
3936 }
3937
3938 /**
3939 * Set up all the data and queue it for the outgoing XML-RPC request
3940 */
3941 function sync() {
3942 if ( !$this->sync ) {
3943 return false;
3944 }
3945
3946 $sync_data = $this->get_common_sync_data();
3947
3948 $wp_importing = defined( 'WP_IMPORTING' ) && WP_IMPORTING;
3949
3950 foreach ( $this->sync as $sync_operation_type => $sync_operations ) {
3951 switch ( $sync_operation_type ) {
3952 case 'post':
3953 if ( $wp_importing ) {
3954 break;
3955 }
3956
3957 $global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3958 $GLOBALS['post'] = null;
3959 foreach ( $sync_operations as $post_id => $settings ) {
3960 $sync_data['post'][$post_id] = $this->get_post( $post_id );
3961 if ( isset( $this->post_transitions[$post_id] ) ) {
3962 $sync_data['post'][$post_id]['transitions'] = $this->post_transitions[$post_id];
3963 } else {
3964 $sync_data['post'][$post_id]['transitions'] = array( false, false );
3965 }
3966 $sync_data['post'][$post_id]['on_behalf_of'] = $settings['on_behalf_of'];
3967 }
3968 $GLOBALS['post'] = $global_post;
3969 unset( $global_post );
3970 break;
3971 case 'comment':
3972 if ( $wp_importing ) {
3973 break;
3974 }
3975
3976 $global_comment = isset( $GLOBALS['comment'] ) ? $GLOBALS['comment'] : null;
3977 unset( $GLOBALS['comment'] );
3978 foreach ( $sync_operations as $comment_id => $settings ) {
3979 $sync_data['comment'][$comment_id] = $this->get_comment( $comment_id );
3980 if ( isset( $this->comment_transitions[$comment_id] ) ) {
3981 $sync_data['comment'][$comment_id]['transitions'] = $this->comment_transitions[$comment_id];
3982 } else {
3983 $sync_data['comment'][$comment_id]['transitions'] = array( false, false );
3984 }
3985 $sync_data['comment'][$comment_id]['on_behalf_of'] = $settings['on_behalf_of'];
3986 }
3987 $GLOBALS['comment'] = $global_comment;
3988 unset( $global_comment );
3989 break;
3990 case 'option' :
3991 foreach ( $sync_operations as $option => $settings ) {
3992 $sync_data['option'][$option] = array( 'value' => get_option( $option ) );
3993 }
3994 break;
3995
3996 case 'delete_post':
3997 case 'delete_comment':
3998 foreach ( $sync_operations as $object_id => $settings ) {
3999 $sync_data[$sync_operation_type][$object_id] = array( 'on_behalf_of' => $settings['on_behalf_of'] );
4000 }
4001 break;
4002 case 'delete_option' :
4003 foreach ( $sync_operations as $object_id => $settings ) {
4004 $sync_data[$sync_operation_type][$object_id] = true;
4005 }
4006 break;
4007 }
4008 }
4009
4010 Jetpack::xmlrpc_async_call( 'jetpack.syncContent', $sync_data );
4011 }
4012
4013 /**
4014 * Format and return content data from a direct xmlrpc request for it.
4015 *
4016 * @param array $content_ids: array( 'posts' => array of ids, 'comments' => array of ids, 'options' => array of options )
4017 */
4018 function get_content( $content_ids ) {
4019 $sync_data = $this->get_common_sync_data();
4020
4021 if ( isset( $content_ids['posts'] ) ) {
4022 foreach ( $content_ids['posts'] as $id ) {
4023 $sync_data['post'][$id] = $this->get_post( $id );
4024 }
4025 }
4026
4027 if ( isset( $content_ids['comments'] ) ) {
4028 foreach ( $content_ids['comments'] as $id ) {
4029 $sync_data['comment'][$id] = $this->get_post( $id );
4030 }
4031 }
4032
4033 if ( isset( $content_ids['options'] ) ) {
4034 foreach ( $content_ids['options'] as $option ) {
4035 $sync_data['option'][$option] = array( 'value' => get_option( $option ) );
4036 }
4037 }
4038
4039 return $sync_data;
4040 }
4041
4042 /**
4043 * Helper method for registering a post for sync
4044 *
4045 * @param int $id wp_posts.ID
4046 * @param array $settings Sync data
4047 */
4048 function register_post( $id, array $settings = null ) {
4049 $id = (int) $id;
4050 if ( !$id ) {
4051 return false;
4052 }
4053
4054 $post = get_post( $id );
4055 if ( !$post ) {
4056 return false;
4057 }
4058
4059 $settings = wp_parse_args( $settings, array(
4060 'on_behalf_of' => array(),
4061 ) );
4062
4063 return $this->register( 'post', $id, $settings );
4064 }
4065
4066 /**
4067 * Helper method for registering a comment for sync
4068 *
4069 * @param int $id wp_comments.comment_ID
4070 * @param array $settings Sync data
4071 */
4072 function register_comment( $id, array $settings = null ) {
4073 $id = (int) $id;
4074 if ( !$id ) {
4075 return false;
4076 }
4077
4078 $comment = get_comment( $id );
4079 if ( !$comment || empty( $comment->comment_post_ID ) ) {
4080 return false;
4081 }
4082
4083 $post = get_post( $comment->comment_post_ID );
4084 if ( !$post ) {
4085 return false;
4086 }
4087
4088 $settings = wp_parse_args( $settings, array(
4089 'on_behalf_of' => array(),
4090 ) );
4091
4092 return $this->register( 'comment', $id, $settings );
4093 }
4094
4095 /* Posts Sync */
4096
4097 function posts( $file, array $settings = null ) {
4098 $module_slug = Jetpack::get_module_slug( $file );
4099
4100 $defaults = array(
4101 'post_types' => array( 'post', 'page' ),
4102 'post_stati' => array( 'publish' ),
4103 );
4104
4105 $this->sync_conditions['posts'][$module_slug] = wp_parse_args( $settings, $defaults );
4106
4107 add_action( 'transition_post_status', array( $this, 'transition_post_status_action' ), 10, 3 );
4108 add_action( 'delete_post', array( $this, 'delete_post_action' ) );
4109 }
4110
4111 function delete_post_action( $post_id ) {
4112 $post = get_post( $post_id );
4113 if ( !$post ) {
4114 return $this->register( 'delete_post', (int) $post_id );
4115 }
4116
4117 $this->transition_post_status_action( 'delete', $post->post_status, $post );
4118 }
4119
4120 function transition_post_status_action( $new_status, $old_status, $post ) {
4121 $sync = $this->get_post_sync_operation( $new_status, $old_status, $post, $this->sync_conditions['posts'] );
4122 if ( !$sync ) {
4123 // No module wants to sync this post
4124 return false;
4125 }
4126
4127 // Track post transitions
4128 if ( isset( $this->post_transitions[$post->ID] ) ) {
4129 // status changed more than once - keep tha most recent $new_status
4130 $this->post_transitions[$post->ID][0] = $new_status;
4131 } else {
4132 $this->post_transitions[$post->ID] = array( $new_status, $old_status );
4133 }
4134
4135 $operation = $sync['operation'];
4136 unset( $sync['operation'] );
4137
4138 switch ( $operation ) {
4139 case 'delete' :
4140 return $this->register( 'delete_post', (int) $post->ID, $sync );
4141 case 'submit' :
4142 return $this->register_post( (int) $post->ID, $sync );
4143 }
4144 }
4145
4146 function get_post_sync_operation( $new_status, $old_status, $post, $module_conditions ) {
4147 $delete_on_behalf_of = array();
4148 $submit_on_behalf_of = array();
4149 $delete_stati = array( 'delete' );
4150
4151 foreach ( $module_conditions as $module => $conditions ) {
4152 if ( !in_array( $post->post_type, $conditions['post_types'] ) ) {
4153 continue;
4154 }
4155
4156 $deleted_post = in_array( $new_status, $delete_stati );
4157
4158 if ( $deleted_post ) {
4159 $delete_on_behalf_of[] = $module;
4160 } else {
4161 clean_post_cache( $post->ID );
4162 $new_status = get_post_status( $post->ID ); // Inherited status is resolved here
4163 }
4164
4165 $old_status_in_stati = in_array( $old_status, $conditions['post_stati'] );
4166 $new_status_in_stati = in_array( $new_status, $conditions['post_stati'] );
4167
4168 if ( $old_status_in_stati && !$new_status_in_stati ) {
4169 // Jetpack no longer needs the post
4170 if ( !$deleted_post ) {
4171 $delete_on_behalf_of[] = $module;
4172 } // else, we've already flagged it above
4173 continue;
4174 }
4175
4176 if ( !$new_status_in_stati ) {
4177 continue;
4178 }
4179
4180 // At this point, we know we want to sync the post, not delete it
4181 $submit_on_behalf_of[] = $module;
4182 }
4183
4184 if ( !empty( $submit_on_behalf_of ) ) {
4185 return array( 'operation' => 'submit', 'on_behalf_of' => $submit_on_behalf_of );
4186 }
4187
4188 if ( !empty( $delete_on_behalf_of ) ) {
4189 return array( 'operation' => 'delete', 'on_behalf_of' => $delete_on_behalf_of );
4190 }
4191
4192 return false;
4193 }
4194
4195 /**
4196 * Get a post and associated data in the standard JP format.
4197 * Cannot be called statically
4198 *
4199 * @param int $id Post ID
4200 * @return Array containing full post details
4201 */
4202 function get_post( $id ) {
4203 $post_obj = get_post( $id );
4204 if ( !$post_obj )
4205 return false;
4206
4207 if ( is_callable( $post_obj, 'to_array' ) ) {
4208 // WP >= 3.5
4209 $post = $post_obj->to_array();
4210 } else {
4211 // WP < 3.5
4212 $post = get_object_vars( $post_obj );
4213 }
4214
4215 if ( 0 < strlen( $post['post_password'] ) ) {
4216 $post['post_password'] = 'auto-' . wp_generate_password( 10, false ); // We don't want the real password. Just pass something random.
4217 }
4218
4219 // local optimizations
4220 unset(
4221 $post['filter'],
4222 $post['ancestors'],
4223 $post['post_content_filtered'],
4224 $post['to_ping'],
4225 $post['pinged']
4226 );
4227
4228 if ( $this->is_post_public( $post ) ) {
4229 $post['post_is_public'] = Jetpack::get_option( 'public' );
4230 } else {
4231 //obscure content
4232 $post['post_content'] = '';
4233 $post['post_excerpt'] = '';
4234 $post['post_is_public'] = false;
4235 }
4236 $post_type_obj = get_post_type_object( $post['post_type'] );
4237 $post['post_is_excluded_from_search'] = $post_type_obj->exclude_from_search;
4238
4239 $post['tax'] = array();
4240 $taxonomies = get_object_taxonomies( $post_obj );
4241 foreach ( $taxonomies as $taxonomy ) {
4242 $terms = get_object_term_cache( $post_obj->ID, $taxonomy );
4243 if ( empty( $terms ) )
4244 $terms = wp_get_object_terms( $post_obj->ID, $taxonomy );
4245 $term_names = array();
4246 foreach ( $terms as $term ) {
4247 $term_names[] = $term->name;
4248 }
4249 $post['tax'][$taxonomy] = $term_names;
4250 }
4251
4252 $meta = get_post_meta( $post_obj->ID, false );
4253 $post['meta'] = array();
4254 foreach ( $meta as $key => $value ) {
4255 $post['meta'][$key] = array_map( 'maybe_unserialize', $value );
4256 }
4257
4258 $post['extra'] = array(
4259 'author' => get_the_author_meta( 'display_name', $post_obj->post_author ),
4260 'author_email' => get_the_author_meta( 'email', $post_obj->post_author ),
4261 );
4262
4263 if ( $fid = get_post_thumbnail_id( $id ) ) {
4264 $feature = wp_get_attachment_image_src( $fid, 'large' );
4265 if ( !empty( $feature[0] ) )
4266 $post['extra']['featured_image'] = $feature[0];
4267 }
4268
4269 $post['permalink'] = get_permalink( $post_obj->ID );
4270 $post['shortlink'] = wp_get_shortlink( $post_obj->ID );
4271 return $post;
4272 }
4273
4274 /**
4275 * Decide whether a post/page/attachment is visible to the public.
4276 *
4277 * @param array $post
4278 * @return bool
4279 */
4280 function is_post_public( $post ) {
4281 if ( !is_array( $post ) ) {
4282 $post = (array) $post;
4283 }
4284
4285 if ( 0 < strlen( $post['post_password'] ) )
4286 return false;
4287 if ( ! in_array( $post['post_type'], get_post_types( array( 'public' => true ) ) ) )
4288 return false;
4289 $post_status = get_post_status( $post['ID'] ); // Inherited status is resolved here.
4290 if ( ! in_array( $post_status, get_post_stati( array( 'public' => true ) ) ) )
4291 return false;
4292 return true;
4293 }
4294
4295 /* Comments Sync */
4296
4297 function comments( $file, array $settings = null ) {
4298 $module_slug = Jetpack::get_module_slug( $file );
4299
4300 $defaults = array(
4301 'post_types' => array( 'post', 'page' ), // For what post types will we sync comments?
4302 'post_stati' => array( 'publish' ), // For what post stati will we sync comments?
4303 'comment_types' => array( '', 'comment', 'trackback', 'pingback' ), // What comment types will we sync?
4304 'comment_stati' => array( 'approved' ), // What comment stati will we sync?
4305 );
4306
4307 $settings = wp_parse_args( $settings, $defaults );
4308
4309 $this->sync_conditions['comments'][$module_slug] = $settings;
4310
4311 add_action( 'wp_insert_comment', array( $this, 'wp_insert_comment_action' ), 10, 2 );
4312 add_action( 'transition_comment_status', array( $this, 'transition_comment_status_action' ), 10, 3 );
4313 add_action( 'edit_comment', array( $this, 'edit_comment_action' ) );
4314 }
4315
4316 /*
4317 * This is really annoying. If you edit a comment, but don't change the status, WordPress doesn't fire the transition_comment_status hook.
4318 * That means we have to catch these comments on the edit_comment hook, but ignore comments on that hook when the transition_comment_status does fire.
4319 */
4320 function edit_comment_action( $comment_id ) {
4321 $comment = get_comment( $comment_id );
4322 $new_status = $this->translate_comment_status( $comment->comment_approved );
4323 add_action( "comment_{$new_status}_{$comment->comment_type}", array( $this, 'transition_comment_status_for_comments_whose_status_does_not_change' ), 10, 2 );
4324 }
4325
4326 function wp_insert_comment_action( $comment_id, $comment ) {
4327 $this->transition_comment_status_action( $comment->comment_approved, 'new', $comment );
4328 }
4329
4330 function transition_comment_status_for_comments_whose_status_does_not_change( $comment_id, $comment ) {
4331 if ( isset( $this->comment_transitions[$comment_id] ) ) {
4332 return $this->transition_comment_status_action( $comment->comment_approved, $this->comment_transitions[$comment_id][1], $comment );
4333 }
4334
4335 return $this->transition_comment_status_action( $comment->comment_approved, $comment->comment_approved, $comment );
4336 }
4337
4338 function translate_comment_status( $status ) {
4339 switch ( (string) $status ) {
4340 case '0' :
4341 case 'hold' :
4342 return 'unapproved';
4343 case '1' :
4344 case 'approve' :
4345 return 'approved';
4346 }
4347
4348 return $status;
4349 }
4350
4351 function transition_comment_status_action( $new_status, $old_status, $comment ) {
4352 $post = get_post( $comment->comment_post_ID );
4353 if ( !$post ) {
4354 return false;
4355 }
4356
4357 foreach ( array( 'new_status', 'old_status' ) as $_status ) {
4358 $$_status = $this->translate_comment_status( $$_status );
4359 }
4360
4361 // Track comment transitions
4362 if ( isset( $this->comment_transitions[$comment->comment_ID] ) ) {
4363 // status changed more than once - keep tha most recent $new_status
4364 $this->comment_transitions[$comment->comment_ID][0] = $new_status;
4365 } else {
4366 $this->comment_transitions[$comment->comment_ID] = array( $new_status, $old_status );
4367 }
4368
4369 $post_sync = $this->get_post_sync_operation( $post->post_status, '_jetpack_test_sync', $post, $this->sync_conditions['comments'] );
4370
4371 if ( !$post_sync ) {
4372 // No module wants to sync this comment because its post doesn't match any sync conditions
4373 return false;
4374 }
4375
4376 if ( 'delete' == $post_sync['operation'] ) {
4377 // Had we been looking at post sync operations (instead of comment sync operations),
4378 // this comment's post would have been deleted. Don't sync the comment.
4379 return false;
4380 }
4381
4382 $delete_on_behalf_of = array();
4383 $submit_on_behalf_of = array();
4384 $delete_stati = array( 'delete' );
4385
4386 foreach ( $this->sync_conditions['comments'] as $module => $conditions ) {
4387 if ( !in_array( $comment->comment_type, $conditions['comment_types'] ) ) {
4388 continue;
4389 }
4390
4391 $deleted_comment = in_array( $new_status, $delete_stati );
4392
4393 if ( $deleted_comment ) {
4394 $delete_on_behalf_of[] = $module;
4395 }
4396
4397 $old_status_in_stati = in_array( $old_status, $conditions['comment_stati'] );
4398 $new_status_in_stati = in_array( $new_status, $conditions['comment_stati'] );
4399
4400 if ( $old_status_in_stati && !$new_status_in_stati ) {
4401 // Jetpack no longer needs the comment
4402 if ( !$deleted_comment ) {
4403 $delete_on_behalf_of[] = $module;
4404 } // else, we've already flagged it above
4405 continue;
4406 }
4407
4408 if ( !$new_status_in_stati ) {
4409 continue;
4410 }
4411
4412 // At this point, we know we want to sync the comment, not delete it
4413 $submit_on_behalf_of[] = $module;
4414 }
4415
4416 if ( ! empty( $submit_on_behalf_of ) ) {
4417 $this->register_post( $comment->comment_post_ID, array( 'on_behalf_of' => $submit_on_behalf_of ) );
4418 return $this->register_comment( $comment->comment_ID, array( 'on_behalf_of' => $submit_on_behalf_of ) );
4419 }
4420
4421 if ( !empty( $delete_on_behalf_of ) ) {
4422 return $this->register( 'delete_comment', $comment->comment_ID, array( 'on_behalf_of' => $delete_on_behalf_of ) );
4423 }
4424
4425 return false;
4426 }
4427
4428 /**
4429 * Get a comment and associated data in the standard JP format.
4430 * Cannot be called statically
4431 *
4432 * @param int $id Comment ID
4433 * @return Array containing full comment details
4434 */
4435 function get_comment( $id ) {
4436 $comment_obj = get_comment( $id );
4437 if ( !$comment_obj )
4438 return false;
4439 $comment = get_object_vars( $comment_obj );
4440
4441 $meta = get_comment_meta( $id, false );
4442 $comment['meta'] = array();
4443 foreach ( $meta as $key => $value ) {
4444 $comment['meta'][$key] = array_map( 'maybe_unserialize', $value );
4445 }
4446
4447 return $comment;
4448 }
4449
4450 /* Options Sync */
4451
4452 /* Ah... so much simpler than Posts and Comments :) */
4453 function options( $file, $option /*, $option, ... */ ) {
4454 $options = func_get_args();
4455 $file = array_shift( $options );
4456
4457 $module_slug = Jetpack::get_module_slug( $file );
4458
4459 if ( !isset( $this->sync_options[$module_slug] ) ) {
4460 $this->sync_options[$module_slug] = array();
4461 }
4462
4463 foreach ( $options as $option ) {
4464 $this->sync_options[$module_slug][] = $option;
4465 add_action( "delete_option_{$option}", array( $this, 'deleted_option_action' ) );
4466 add_action( "update_option_{$option}", array( $this, 'updated_option_action' ) );
4467 add_action( "add_option_{$option}", array( $this, 'added_option_action' ) );
4468 }
4469
4470 $this->sync_options[$module_slug] = array_unique( $this->sync_options[$module_slug] );
4471 }
4472
4473 function deleted_option_action( $option ) {
4474 $this->register( 'delete_option', $option );
4475 }
4476
4477 function updated_option_action( $old_value ) {
4478 // The value of $option isn't passed to the filter
4479 // Calculate it
4480 $option = current_filter();
4481 $prefix = 'update_option_';
4482 if ( 0 !== strpos( $option, $prefix ) ) {
4483 return;
4484 }
4485 $option = substr( $option, strlen( $prefix ) );
4486
4487 $this->added_option_action( $option );
4488 }
4489
4490 function added_option_action( $option ) {
4491 $this->register( 'option', $option );
4492 }
4493
4494 function sync_all_module_options( $module_slug ) {
4495 if ( empty( $this->sync_options[$module_slug] ) ) {
4496 return;
4497 }
4498
4499 foreach ( $this->sync_options[$module_slug] as $option ) {
4500 $this->added_option_action( $option );
4501 }
4502 }
4503
4504 function sync_all_registered_options( $options = array() ) {
4505 if ( 'jetpack_sync_all_registered_options' == current_filter() ) {
4506 $all_registered_options = array_unique( call_user_func_array( 'array_merge', $this->sync_options ) );
4507 foreach ( $all_registered_options as $option ) {
4508 $this->added_option_action( $option );
4509 }
4510 } else {
4511 wp_schedule_single_event( time(), 'jetpack_sync_all_registered_options', array( $this->sync_options ) );
4512 }
4513 }
4514 }
4515
4516 require_once dirname( __FILE__ ) . '/class.jetpack-user-agent.php';
4517 require_once dirname( __FILE__ ) . '/class.jetpack-post-images.php';
4518 require_once dirname( __FILE__ ) . '/class.photon.php';
4519 require dirname( __FILE__ ) . '/functions.photon.php';
4520 require dirname( __FILE__ ) . '/functions.compat.php';
4521 require dirname( __FILE__ ) . '/functions.gallery.php';
4522
4523 class Jetpack_Error extends WP_Error {}
4524
4525 register_activation_hook( __FILE__, array( 'Jetpack', 'plugin_activation' ) );
4526 register_deactivation_hook( __FILE__, array( 'Jetpack', 'plugin_deactivation' ) );
4527
4528 add_action( 'init', array( 'Jetpack', 'init' ) );
4529 add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
4530 add_filter( 'jetpack_static_url', array( 'Jetpack', 'staticize_subdomain' ) );
4531