PageRenderTime 78ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/plugins/jetpack/class.jetpack.php

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