class.jetpack-sync-actions.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. require_once dirname( __FILE__ ) . '/class.jetpack-sync-modules.php';
  3. /**
  4. * The role of this class is to hook the Sync subsystem into WordPress - when to listen for actions,
  5. * when to send, when to perform a full sync, etc.
  6. *
  7. * It also binds the action to send data to WPCOM to Jetpack's XMLRPC client object.
  8. */
  9. class Jetpack_Sync_Actions {
  10. static $sender = null;
  11. static $listener = null;
  12. const DEFAULT_SYNC_CRON_INTERVAL_NAME = 'jetpack_sync_interval';
  13. const DEFAULT_SYNC_CRON_INTERVAL_VALUE = 300; // 5 * MINUTE_IN_SECONDS;
  14. static function init() {
  15. // everything below this point should only happen if we're a valid sync site
  16. if ( ! self::sync_allowed() ) {
  17. return;
  18. }
  19. if ( self::sync_via_cron_allowed() ) {
  20. self::init_sync_cron_jobs();
  21. } else if ( wp_next_scheduled( 'jetpack_sync_cron' ) ) {
  22. self::clear_sync_cron_jobs();
  23. }
  24. // When importing via cron, do not sync
  25. add_action( 'wp_cron_importer_hook', array( __CLASS__, 'set_is_importing_true' ), 1 );
  26. // Sync connected user role changes to .com
  27. require_once dirname( __FILE__ ) . '/class.jetpack-sync-users.php';
  28. // publicize filter to prevent publicizing blacklisted post types
  29. add_filter( 'publicize_should_publicize_published_post', array( __CLASS__, 'prevent_publicize_blacklisted_posts' ), 10, 2 );
  30. /**
  31. * Fires on every request before default loading sync listener code.
  32. * Return false to not load sync listener code that monitors common
  33. * WP actions to be serialized.
  34. *
  35. * By default this returns true for cron jobs, non-GET-requests, or requests where the
  36. * user is logged-in.
  37. *
  38. * @since 4.2.0
  39. *
  40. * @param bool should we load sync listener code for this request
  41. */
  42. if ( apply_filters( 'jetpack_sync_listener_should_load', true ) ) {
  43. self::initialize_listener();
  44. }
  45. add_action( 'init', array( __CLASS__, 'add_sender_shutdown' ), 90 );
  46. }
  47. static function add_sender_shutdown() {
  48. /**
  49. * Fires on every request before default loading sync sender code.
  50. * Return false to not load sync sender code that serializes pending
  51. * data and sends it to WPCOM for processing.
  52. *
  53. * By default this returns true for cron jobs, POST requests, admin requests, or requests
  54. * by users who can manage_options.
  55. *
  56. * @since 4.2.0
  57. *
  58. * @param bool should we load sync sender code for this request
  59. */
  60. if ( apply_filters( 'jetpack_sync_sender_should_load',
  61. (
  62. ( isset( $_SERVER["REQUEST_METHOD"] ) && 'POST' === $_SERVER['REQUEST_METHOD'] )
  63. ||
  64. current_user_can( 'manage_options' )
  65. ||
  66. is_admin()
  67. ||
  68. defined( 'PHPUNIT_JETPACK_TESTSUITE' )
  69. )
  70. ) ) {
  71. self::initialize_sender();
  72. add_action( 'shutdown', array( self::$sender, 'do_sync' ) );
  73. add_action( 'shutdown', array( self::$sender, 'do_full_sync' ) );
  74. }
  75. }
  76. static function sync_allowed() {
  77. require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
  78. return ( ! Jetpack_Sync_Settings::get_setting( 'disable' )
  79. && ( doing_action( 'jetpack_user_authorized' ) || Jetpack::is_active() )
  80. && ! ( Jetpack::is_development_mode() || Jetpack::is_staging_site() ) )
  81. || defined( 'PHPUNIT_JETPACK_TESTSUITE' );
  82. }
  83. static function sync_via_cron_allowed() {
  84. require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
  85. return ( Jetpack_Sync_Settings::get_setting( 'sync_via_cron' ) );
  86. }
  87. static function prevent_publicize_blacklisted_posts( $should_publicize, $post ) {
  88. require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
  89. if ( in_array( $post->post_type, Jetpack_Sync_Settings::get_setting( 'post_types_blacklist' ) ) ) {
  90. return false;
  91. }
  92. return $should_publicize;
  93. }
  94. static function set_is_importing_true() {
  95. require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
  96. Jetpack_Sync_Settings::set_importing( true );
  97. }
  98. static function send_data( $data, $codec_name, $sent_timestamp, $queue_id, $checkout_duration, $preprocess_duration ) {
  99. require_once dirname( __FILE__ ) . '/class.jetpack-sync-functions.php';
  100. Jetpack::load_xml_rpc_client();
  101. $query_args = array(
  102. 'sync' => '1', // add an extra parameter to the URL so we can tell it's a sync action
  103. 'codec' => $codec_name, // send the name of the codec used to encode the data
  104. 'timestamp' => $sent_timestamp, // send current server time so we can compensate for clock differences
  105. 'queue' => $queue_id, // sync or full_sync
  106. 'home' => Jetpack_Sync_Functions::home_url(), // Send home url option to check for Identity Crisis server-side
  107. 'siteurl' => Jetpack_Sync_Functions::site_url(), // Send siteurl option to check for Identity Crisis server-side
  108. 'cd' => sprintf( '%.4f', $checkout_duration), // Time spent retrieving queue items from the DB
  109. 'pd' => sprintf( '%.4f', $preprocess_duration), // Time spent converting queue items into data to send
  110. );
  111. // Has the site opted in to IDC mitigation?
  112. if ( Jetpack::sync_idc_optin() ) {
  113. $query_args['idc'] = true;
  114. }
  115. if ( Jetpack_Options::get_option( 'migrate_for_idc', false ) ) {
  116. $query_args['migrate_for_idc'] = true;
  117. }
  118. $query_args['timeout'] = Jetpack_Sync_Settings::is_doing_cron() ? 30 : 15;
  119. /**
  120. * Filters query parameters appended to the Sync request URL sent to WordPress.com.
  121. *
  122. * @since 4.7.0
  123. *
  124. * @param array $query_args associative array of query parameters.
  125. */
  126. $query_args = apply_filters( 'jetpack_sync_send_data_query_args', $query_args );
  127. $url = add_query_arg( $query_args, Jetpack::xmlrpc_api_url() );
  128. $rpc = new Jetpack_IXR_Client( array(
  129. 'url' => $url,
  130. 'user_id' => JETPACK_MASTER_USER,
  131. 'timeout' => $query_args['timeout'],
  132. ) );
  133. $result = $rpc->query( 'jetpack.syncActions', $data );
  134. if ( ! $result ) {
  135. return $rpc->get_jetpack_error();
  136. }
  137. $response = $rpc->getResponse();
  138. // Check if WordPress.com IDC mitigation blocked the sync request
  139. if ( is_array( $response ) && isset( $response['error_code'] ) ) {
  140. $error_code = $response['error_code'];
  141. $allowed_idc_error_codes = array(
  142. 'jetpack_url_mismatch',
  143. 'jetpack_home_url_mismatch',
  144. 'jetpack_site_url_mismatch'
  145. );
  146. if ( in_array( $error_code, $allowed_idc_error_codes ) ) {
  147. Jetpack_Options::update_option(
  148. 'sync_error_idc',
  149. Jetpack::get_sync_error_idc_option( $response )
  150. );
  151. }
  152. return new WP_Error(
  153. 'sync_error_idc',
  154. esc_html__( 'Sync has been blocked from WordPress.com because it would cause an identity crisis', 'jetpack' )
  155. );
  156. }
  157. return $response;
  158. }
  159. static function do_initial_sync() {
  160. // Lets not sync if we are not suppose to.
  161. if ( ! self::sync_allowed() ) {
  162. return false;
  163. }
  164. $initial_sync_config = array(
  165. 'options' => true,
  166. 'functions' => true,
  167. 'constants' => true,
  168. 'users' => array( get_current_user_id() ),
  169. );
  170. if ( is_multisite() ) {
  171. $initial_sync_config['network_options'] = true;
  172. }
  173. self::do_full_sync( $initial_sync_config );
  174. }
  175. static function do_full_sync( $modules = null ) {
  176. if ( ! self::sync_allowed() ) {
  177. return false;
  178. }
  179. $full_sync_module = Jetpack_Sync_Modules::get_module( 'full-sync' );
  180. if ( ! $full_sync_module ) {
  181. return false;
  182. }
  183. self::initialize_listener();
  184. $full_sync_module->start( $modules );
  185. return true;
  186. }
  187. static function jetpack_cron_schedule( $schedules ) {
  188. if ( ! isset( $schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] ) ) {
  189. $schedules[ self::DEFAULT_SYNC_CRON_INTERVAL_NAME ] = array(
  190. 'interval' => self::DEFAULT_SYNC_CRON_INTERVAL_VALUE,
  191. 'display' => sprintf(
  192. esc_html( _n( 'Every minute', 'Every %d minutes', intval( self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60 ), 'jetpack' ) ),
  193. intval( self::DEFAULT_SYNC_CRON_INTERVAL_VALUE / 60 )
  194. )
  195. );
  196. }
  197. return $schedules;
  198. }
  199. static function do_cron_sync() {
  200. self::do_cron_sync_by_type( 'sync' );
  201. }
  202. static function do_cron_full_sync() {
  203. self::do_cron_sync_by_type( 'full_sync' );
  204. }
  205. /**
  206. * Try to send actions until we run out of things to send,
  207. * or have to wait more than 15s before sending again,
  208. * or we hit a lock or some other sending issue
  209. *
  210. * @param string $type Sync type. Can be `sync` or `full_sync`.
  211. */
  212. static function do_cron_sync_by_type( $type ) {
  213. if ( ! self::sync_allowed() || ( 'sync' !== $type && 'full_sync' !== $type ) ) {
  214. return;
  215. }
  216. self::initialize_sender();
  217. $time_limit = Jetpack_Sync_Settings::get_setting( 'cron_sync_time_limit' );
  218. $start_time = time();
  219. do {
  220. $next_sync_time = self::$sender->get_next_sync_time( $type );
  221. if ( $next_sync_time ) {
  222. $delay = $next_sync_time - time() + 1;
  223. if ( $delay > 15 ) {
  224. break;
  225. } elseif ( $delay > 0 ) {
  226. sleep( $delay );
  227. }
  228. }
  229. $result = 'full_sync' === $type ? self::$sender->do_full_sync() : self::$sender->do_sync();
  230. } while ( $result && ! is_wp_error( $result ) && ( $start_time + $time_limit ) > time() );
  231. }
  232. static function initialize_listener() {
  233. require_once dirname( __FILE__ ) . '/class.jetpack-sync-listener.php';
  234. self::$listener = Jetpack_Sync_Listener::get_instance();
  235. }
  236. static function initialize_sender() {
  237. require_once dirname( __FILE__ ) . '/class.jetpack-sync-sender.php';
  238. self::$sender = Jetpack_Sync_Sender::get_instance();
  239. // bind the sending process
  240. add_filter( 'jetpack_sync_send_data', array( __CLASS__, 'send_data' ), 10, 6 );
  241. }
  242. static function initialize_woocommerce() {
  243. if ( false === class_exists( 'WooCommerce' ) ) {
  244. return;
  245. }
  246. add_filter( 'jetpack_sync_modules', array( 'Jetpack_Sync_Actions', 'add_woocommerce_sync_module' ) );
  247. }
  248. static function add_woocommerce_sync_module( $sync_modules ) {
  249. require_once dirname( __FILE__ ) . '/class.jetpack-sync-module-woocommerce.php';
  250. $sync_modules[] = 'Jetpack_Sync_Module_WooCommerce';
  251. return $sync_modules;
  252. }
  253. static function initialize_wp_super_cache() {
  254. if ( false === function_exists( 'wp_cache_is_enabled' ) ) {
  255. return;
  256. }
  257. add_filter( 'jetpack_sync_modules', array( 'Jetpack_Sync_Actions', 'add_wp_super_cache_sync_module' ) );
  258. }
  259. static function add_wp_super_cache_sync_module( $sync_modules ) {
  260. require_once dirname( __FILE__ ) . '/class.jetpack-sync-module-wp-super-cache.php';
  261. $sync_modules[] = 'Jetpack_Sync_Module_WP_Super_Cache';
  262. return $sync_modules;
  263. }
  264. static function sanitize_filtered_sync_cron_schedule( $schedule ) {
  265. $schedule = sanitize_key( $schedule );
  266. $schedules = wp_get_schedules();
  267. // Make sure that the schedule has actually been registered using the `cron_intervals` filter.
  268. if ( isset( $schedules[ $schedule ] ) ) {
  269. return $schedule;
  270. }
  271. return self::DEFAULT_SYNC_CRON_INTERVAL_NAME;
  272. }
  273. static function get_start_time_offset( $schedule = '', $hook = '' ) {
  274. $start_time_offset = is_multisite()
  275. ? mt_rand( 0, ( 2 * self::DEFAULT_SYNC_CRON_INTERVAL_VALUE ) )
  276. : 0;
  277. /**
  278. * Allows overriding the offset that the sync cron jobs will first run. This can be useful when scheduling
  279. * cron jobs across multiple sites in a network.
  280. *
  281. * @since 4.5
  282. *
  283. * @param int $start_time_offset
  284. * @param string $hook
  285. * @param string $schedule
  286. */
  287. return intval( apply_filters(
  288. 'jetpack_sync_cron_start_time_offset',
  289. $start_time_offset,
  290. $hook,
  291. $schedule
  292. ) );
  293. }
  294. static function maybe_schedule_sync_cron( $schedule, $hook ) {
  295. if ( ! $hook ) {
  296. return;
  297. }
  298. $schedule = self::sanitize_filtered_sync_cron_schedule( $schedule );
  299. $start_time = time() + self::get_start_time_offset( $schedule, $hook );
  300. if ( ! wp_next_scheduled( $hook ) ) {
  301. // Schedule a job to send pending queue items once a minute
  302. wp_schedule_event( $start_time, $schedule, $hook );
  303. } else if ( $schedule != wp_get_schedule( $hook ) ) {
  304. // If the schedule has changed, update the schedule
  305. wp_clear_scheduled_hook( $hook );
  306. wp_schedule_event( $start_time, $schedule, $hook );
  307. }
  308. }
  309. static function clear_sync_cron_jobs() {
  310. wp_clear_scheduled_hook( 'jetpack_sync_cron' );
  311. wp_clear_scheduled_hook( 'jetpack_sync_full_cron' );
  312. }
  313. static function init_sync_cron_jobs() {
  314. add_filter( 'cron_schedules', array( __CLASS__, 'jetpack_cron_schedule' ) );
  315. add_action( 'jetpack_sync_cron', array( __CLASS__, 'do_cron_sync' ) );
  316. add_action( 'jetpack_sync_full_cron', array( __CLASS__, 'do_cron_full_sync' ) );
  317. /**
  318. * Allows overriding of the default incremental sync cron schedule which defaults to once every 5 minutes.
  319. *
  320. * @since 4.3.2
  321. *
  322. * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
  323. */
  324. $incremental_sync_cron_schedule = apply_filters( 'jetpack_sync_incremental_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
  325. self::maybe_schedule_sync_cron( $incremental_sync_cron_schedule, 'jetpack_sync_cron' );
  326. /**
  327. * Allows overriding of the full sync cron schedule which defaults to once every 5 minutes.
  328. *
  329. * @since 4.3.2
  330. *
  331. * @param string self::DEFAULT_SYNC_CRON_INTERVAL_NAME
  332. */
  333. $full_sync_cron_schedule = apply_filters( 'jetpack_sync_full_sync_interval', self::DEFAULT_SYNC_CRON_INTERVAL_NAME );
  334. self::maybe_schedule_sync_cron( $full_sync_cron_schedule, 'jetpack_sync_full_cron' );
  335. }
  336. static function cleanup_on_upgrade( $new_version = null, $old_version = null ) {
  337. if ( wp_next_scheduled( 'jetpack_sync_send_db_checksum' ) ) {
  338. wp_clear_scheduled_hook( 'jetpack_sync_send_db_checksum' );
  339. }
  340. $is_new_sync_upgrade = version_compare( $old_version, '4.2', '>=' );
  341. if ( ! empty( $old_version ) && $is_new_sync_upgrade && version_compare( $old_version, '4.5', '<' ) ) {
  342. require_once dirname( __FILE__ ) . '/class.jetpack-sync-settings.php';
  343. self::clear_sync_cron_jobs();
  344. Jetpack_Sync_Settings::update_settings( array(
  345. 'render_filtered_content' => Jetpack_Sync_Defaults::$default_render_filtered_content
  346. ) );
  347. }
  348. }
  349. static function get_sync_status() {
  350. self::initialize_sender();
  351. $sync_module = Jetpack_Sync_Modules::get_module( 'full-sync' );
  352. $queue = self::$sender->get_sync_queue();
  353. $full_queue = self::$sender->get_full_sync_queue();
  354. $cron_timestamps = array_keys( _get_cron_array() );
  355. $next_cron = $cron_timestamps[0] - time();
  356. $full_sync_status = ( $sync_module ) ? $sync_module->get_status() : array();
  357. return array_merge(
  358. $full_sync_status,
  359. array(
  360. 'cron_size' => count( $cron_timestamps ),
  361. 'next_cron' => $next_cron,
  362. 'queue_size' => $queue->size(),
  363. 'queue_lag' => $queue->lag(),
  364. 'queue_next_sync' => ( self::$sender->get_next_sync_time( 'sync' ) - microtime( true ) ),
  365. 'full_queue_size' => $full_queue->size(),
  366. 'full_queue_lag' => $full_queue->lag(),
  367. 'full_queue_next_sync' => ( self::$sender->get_next_sync_time( 'full_sync' ) - microtime( true ) ),
  368. )
  369. );
  370. }
  371. }
  372. // Check for WooCommerce support
  373. add_action( 'plugins_loaded', array( 'Jetpack_Sync_Actions', 'initialize_woocommerce' ), 5 );
  374. // Check for WP Super Cache
  375. add_action( 'plugins_loaded', array( 'Jetpack_Sync_Actions', 'initialize_wp_super_cache' ), 5 );
  376. /*
  377. * Init after plugins loaded and before the `init` action. This helps with issues where plugins init
  378. * with a high priority or sites that use alternate cron.
  379. */
  380. add_action( 'plugins_loaded', array( 'Jetpack_Sync_Actions', 'init' ), 90 );
  381. // We need to define this here so that it's hooked before `updating_jetpack_version` is called
  382. add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'do_initial_sync' ), 10, 0 );
  383. add_action( 'updating_jetpack_version', array( 'Jetpack_Sync_Actions', 'cleanup_on_upgrade' ), 10, 2 );
  384. add_action( 'jetpack_user_authorized', array( 'Jetpack_Sync_Actions', 'do_initial_sync' ), 10, 0 );