PageRenderTime 66ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/blog/wp-content/plugins/jetpack/class.jetpack.php

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