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