PageRenderTime 358ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 2ms

/class.jetpack.php

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