diff --git a/README.md b/README.md index a6534fe..ff0897b 100644 --- a/README.md +++ b/README.md @@ -186,10 +186,34 @@ curl -X POST https://your-site.com/wp-json/citecue/v1/content \ -d "$BODY" ``` -Responses: `201` created / `200` updated (`{created, updated, post_id, status, permalink, edit_link}`), `400` product push without WooCommerce, `401` bad signature or stale timestamp, `403` ingest disabled, `409` edited locally / SKU exists without `force` / type conflict, `410` push was trashed in WordPress, `429` rate-limited (120/hour, filterable). +Responses: `201` created / `200` updated (`{created, updated, post_id, status, permalink, seq, edit_link}`; `seq` is the post's status-report counter, see below), `400` product push without WooCommerce, `401` bad signature or stale timestamp, `403` ingest disabled, `409` edited locally / SKU exists without `force` / type conflict, `410` push was trashed in WordPress, `429` rate-limited (120/hour, filterable). There is also a public handshake endpoint: `GET /wp-json/citecue/v1/health` → `{plugin, version, delivery, ingest, woocommerce}`. +## Status reports (CiteCue posts only) + +The plugin tells CiteCue when a post or page it pushed changes in WordPress: published, unpublished (draft, pending, private, scheduled or any custom status), trashed, restored, permanently deleted, given a new address, or edited while live. CiteCue applies it so its own record follows the site. + +``` +hook (transition_post_status / before_delete_post / post_updated + wp_after_insert_post) + └─ mark the post: _citecue_report_pending = now, bump _citecue_report_gen + (a permanent delete builds its whole report now and stores it in the + non-autoloaded option citecue_deleted_report_) + └─ schedule citecue_report_drain at "now" (pulling a later one forward) and spawn_cron() + +WP-Cron: citecue_report_drain + up to 20 due entries, oldest first, one request at a time, 30 s budget + POST {app}/api/delivery/v2/content-status Bearer ck_live_… X-Citecue-Channel: wordpress +``` + +- **Never in the editor's request.** Nothing waits on CiteCue; a slow or unreachable CiteCue cannot slow or break saving. Each report is built from the post as it is when the run happens, not when it was marked. +- **Which posts.** A `post` or `page` carrying both `_citecue_external_id` and `_citecue_source`, on a site with an API key that accepts content pushes and whose `home_url()` is https (the plugin already refuses pushes on plain http, and CiteCue would answer 400). Nothing is marked otherwise. The plugin's own `/content` handling is suspended around its insert/update, and after a successful push it clears the post's pending mark and resets what was last reported. +- **Body.** `external_id`, `source`, `site_url` (`home_url( '/' )`), `post_id`, `status` (`publish` for any publicly viewable status, `trash`, `deleted`, otherwise `draft`), `permalink` (publish only), `edited` (the content no longer hashes to `_citecue_content_hash`; the same test as `edited_locally()`, omitted for `deleted`), `seq` and `observed_at`. +- **Order.** `seq` is a per-post counter (`_citecue_report_seq`), allocated atomically in SQL before the post is read again from the database, so a report never carries an older state than a push its number is above; the `/content` response returns the current value so each push resets CiteCue's baseline. A report CiteCue answers with `ignored` / `out_of_order` and a higher `recorded_seq` makes the plugin raise its counter and send the current state once more. +- **Concurrency.** Every mark bumps a per-post generation. A run captures it and only clears or backs off the entry if it is unchanged, so a change made while a report is in flight is never lost. +- **Outcomes.** 2xx clears the entry (and, unless `ignored`, records the `edited` value and permalink sent); 400 and 404 clear it; 401, 403, 408, 429, any 5xx, a timeout or a network error keep it and retry after 1, 5, 15, then 30 minutes (up to 30% jitter, `Retry-After` as a floor, 1 hour cap). After the fourth retry the report is dropped and counted in `citecue_report_given_up`, which Settings → CiteCue shows beside the connection status. A run stops on 401, 403, 408, 429, other 5xx and transport errors; `503 busy` defers only that post. +- **Housekeeping.** Disconnecting clears pending marks and stored delete reports; deactivating clears the cron event; uninstalling removes the options and the `_citecue_report_*` / `_citecue_reported_*` meta. On multisite, uninstalling removes the reporter's bookkeeping (options and post meta) only for the site the uninstall runs on, because those live in each site's own tables; the per-user dismissal records are cleared for every site. + ## WooCommerce With WooCommerce active: @@ -207,6 +231,7 @@ With WooCommerce active: | `GET /api/delivery/v2/page?k&u&b` | `Bearer ck_live_…` + `X-Citecue-Channel: wordpress` | Optimized page for a crawler request (ETag/304; 404 = pass through; hit recorded server-side) | | `GET /api/delivery/v2/seo-head?k&u` | `Bearer ck_live_…` + `X-Citecue-Channel: wordpress` | Enriched head block for one URL, injected into live pages (204 = nothing to inject; 404 = not optimized; fetched on cron, never on a render) | | `GET /api/delivery/v2/llms.txt?k` | `Bearer ck_live_…` | llms.txt body (ETag/304) | +| `POST /api/delivery/v2/content-status` | `Bearer ck_live_…` + `X-Citecue-Channel: wordpress` | Status report for one CiteCue post (see "Status reports"); sent from WP-Cron, never from a visitor's or editor's request | | `GET /api/delivery/v1/crawlers` | none (public) | Daily AI-crawler UA token refresh | ## Hooks @@ -313,3 +338,5 @@ The second URL must be one CiteCue holds an optimized version of; anything else `Citecue_Proxy` and `Citecue_Llms_Txt` each split into a `decide()` that returns what should happen and a `serve()` that emits headers and calls `exit`. All the branching lives in `decide()`, which is what the tests drive; `serve()` stays deliberately trivial because nothing can assert against a request that has already ended. `Citecue_Seo_Head` follows the same split for the same reason, in three pieces rather than two: `decide()` answers "what should this page get" from cache alone, `refresh()` is the only part that talks to the network (on cron, never on a render), and `merge()` is a pure function from (what the rest of `wp_head` printed, CiteCue's block) to the tags that may be added. `merge()` is the whole conflict-avoidance contract with every other SEO plugin on the site, and being pure is what lets it be tested against a real Yoast head dump without a request in sight. + +`Citecue_Status_Reporter` takes an injectable clock and cron spawner (`set_clock()`, `set_spawner()`), so its tests spend the 30 s run budget and walk the retry schedule without waiting and without a loopback request; the CiteCue endpoint is the mock's `content_status` queue. diff --git a/citecue.php b/citecue.php index 70017c1..6665de9 100644 --- a/citecue.php +++ b/citecue.php @@ -3,7 +3,7 @@ * Plugin Name: CiteCue AI Auto-Fix * Plugin URI: https://github.com/citecue/wordpress-plugin * Description: Serves CiteCue-optimized versions of your pages to AI bots and crawlers, adds CiteCue's enriched SEO metadata to your live pages, and lets CiteCue push brand-building draft content into WordPress. - * Version: 1.3.0 + * Version: 1.5.0 * Requires at least: 5.8 * Requires PHP: 7.4 * Author: CiteCue @@ -138,7 +138,7 @@ return; } -define( 'CITECUE_VERSION', '1.3.0' ); +define( 'CITECUE_VERSION', '1.5.0' ); define( 'CITECUE_PLUGIN_FILE', __FILE__ ); define( 'CITECUE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); @@ -151,6 +151,7 @@ require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-proxy.php'; require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-seo-head.php'; require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-llms-txt.php'; +require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-status-reporter.php'; require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-ingest.php'; require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-admin.php'; require_once CITECUE_PLUGIN_DIR . 'includes/class-citecue-plugin.php'; diff --git a/includes/class-citecue-admin.php b/includes/class-citecue-admin.php index d9d3113..628e31a 100644 --- a/includes/class-citecue-admin.php +++ b/includes/class-citecue-admin.php @@ -1033,6 +1033,23 @@ private function render_status_card() { + + 0 ) : ?> + + + + — + + + + diff --git a/includes/class-citecue-api-client.php b/includes/class-citecue-api-client.php index c1db545..5aa0565 100644 --- a/includes/class-citecue-api-client.php +++ b/includes/class-citecue-api-client.php @@ -8,6 +8,7 @@ * GET /api/delivery/v2/page — optimized page for an AI crawler (ETag/304) * GET /api/delivery/v2/seo-head — enriched head block for one URL (humans) * GET /api/delivery/v2/llms.txt — llms.txt body (ETag/304) + * POST /api/delivery/v2/content-status — a status change of a CiteCue post * the public keyless registry feed: * GET /api/delivery/v1/crawlers — AI crawler UA token registry * and the code-gated pairing exchange: @@ -28,6 +29,12 @@ */ class Citecue_Api_Client { + /** + * Request timeout of a status report, in seconds. The reporter budgets its + * run around it. + */ + const STATUS_TIMEOUT = 5; + /** * Settings. * @@ -195,6 +202,42 @@ public function claim_connect_code( $code, array $site ) { return $connection; } + /** + * POST /api/delivery/v2/content-status — reports one CiteCue post's status. + * + * Sent from WP-Cron, never from a visitor's or an editor's request. No + * redirects (the key rides on it) and a 5 second timeout. The reply is + * passed up as it came, because the reporter's retry rules depend on the + * exact status and on Retry-After. + * + * @param array $body The report. + * @return array|WP_Error {status:int, data:array|null, retry_after:string} + */ + public function post_content_status( array $body ) { + $response = wp_remote_post( + $this->settings->api_base() . '/api/delivery/v2/content-status', + array( + 'timeout' => self::STATUS_TIMEOUT, + 'redirection' => 0, + 'user-agent' => 'CiteCue-WordPress/' . CITECUE_VERSION . ' (+' . home_url( '/' ) . ')', + 'headers' => array_merge( $this->auth_headers(), array( 'Content-Type' => 'application/json' ) ), + 'body' => wp_json_encode( $body ), + ) + ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + $data = json_decode( (string) wp_remote_retrieve_body( $response ), true ); + + return array( + 'status' => (int) wp_remote_retrieve_response_code( $response ), + 'data' => is_array( $data ) ? $data : null, + 'retry_after' => (string) wp_remote_retrieve_header( $response, 'retry-after' ), + ); + } + /** * GET /api/delivery/v2/config — the API key's org projects. * diff --git a/includes/class-citecue-connect.php b/includes/class-citecue-connect.php index ebf6b62..cc16388 100644 --- a/includes/class-citecue-connect.php +++ b/includes/class-citecue-connect.php @@ -261,6 +261,9 @@ public function disconnect() { delete_option( 'citecue_auth_failed' ); delete_option( self::VERIFY_OPTION ); $this->plugin->cache->flush(); + // A reconnect may pair a different project, so reports meant for this + // one must not follow it there. + $this->plugin->reporter->clear_pending(); } /** diff --git a/includes/class-citecue-ingest.php b/includes/class-citecue-ingest.php index 6d1d08f..6f4cf9c 100644 --- a/includes/class-citecue-ingest.php +++ b/includes/class-citecue-ingest.php @@ -282,44 +282,52 @@ public function handle_content( WP_REST_Request $request ) { ); } - if ( 'product' === $post_type ) { - $post_id = $this->upsert_product( $existing_id, $params, $title, $content, $status ); - if ( is_wp_error( $post_id ) ) { - return $post_id; - } - } else { - $postarr = array( - 'post_title' => $title, - 'post_content' => $content, - 'post_status' => $status, - 'post_type' => $post_type, - 'post_author' => $this->resolve_author(), - ); - if ( isset( $params['excerpt'] ) ) { - $postarr['post_excerpt'] = sanitize_textarea_field( (string) $params['excerpt'] ); - } - if ( isset( $params['slug'] ) && '' !== (string) $params['slug'] ) { - $postarr['post_name'] = sanitize_title( (string) $params['slug'] ); - } - if ( $existing_id ) { - $postarr['ID'] = $existing_id; - } + // CiteCue knows what it is writing, so the status reporter must not send + // it back as a change made in WordPress. Resumed in `finally`: every + // error return below, and an exception from a filter, still lets go. + $this->plugin->reporter->suspend(); + try { + if ( 'product' === $post_type ) { + $post_id = $this->upsert_product( $existing_id, $params, $title, $content, $status ); + if ( is_wp_error( $post_id ) ) { + return $post_id; + } + } else { + $postarr = array( + 'post_title' => $title, + 'post_content' => $content, + 'post_status' => $status, + 'post_type' => $post_type, + 'post_author' => $this->resolve_author(), + ); + if ( isset( $params['excerpt'] ) ) { + $postarr['post_excerpt'] = sanitize_textarea_field( (string) $params['excerpt'] ); + } + if ( isset( $params['slug'] ) && '' !== (string) $params['slug'] ) { + $postarr['post_name'] = sanitize_title( (string) $params['slug'] ); + } + if ( $existing_id ) { + $postarr['ID'] = $existing_id; + } - /** - * Filters the post array before a CiteCue push is inserted/updated. - * Posts and pages only — products go through WooCommerce's CRUD. - * - * @param array $postarr wp_insert_post() arguments. - * @param array $params Raw (unsanitized) request payload. - */ - $postarr = apply_filters( 'citecue_ingest_postarr', $postarr, $params ); - - $result = $existing_id ? wp_update_post( $postarr, true ) : wp_insert_post( $postarr, true ); - if ( is_wp_error( $result ) ) { - $result->add_data( array( 'status' => 500 ) ); - return $result; + /** + * Filters the post array before a CiteCue push is inserted/updated. + * Posts and pages only — products go through WooCommerce's CRUD. + * + * @param array $postarr wp_insert_post() arguments. + * @param array $params Raw (unsanitized) request payload. + */ + $postarr = apply_filters( 'citecue_ingest_postarr', $postarr, $params ); + + $result = $existing_id ? wp_update_post( $postarr, true ) : wp_insert_post( $postarr, true ); + if ( is_wp_error( $result ) ) { + $result->add_data( array( 'status' => 500 ) ); + return $result; + } + $post_id = (int) $result; } - $post_id = (int) $result; + } finally { + $this->plugin->reporter->resume(); } if ( 'post' === $post_type || 'product' === $post_type ) { @@ -347,22 +355,35 @@ public function handle_content( WP_REST_Request $request ) { $stored = get_post( $post_id ); update_post_meta( $post_id, '_citecue_content_hash', md5( $stored ? $stored->post_content : '' ) ); - $response = rest_ensure_response( - array( - 'created' => ! $existing_id, - 'updated' => (bool) $existing_id, - 'post_id' => $post_id, - 'status' => get_post_status( $post_id ), - 'permalink' => get_permalink( $post_id ), - 'edit_link' => add_query_arg( - array( - 'post' => $post_id, - 'action' => 'edit', - ), - admin_url( 'post.php' ) + // The push replaced the text and the status: nothing is waiting to be + // reported any more, and what was last reported is what was just pushed. + // Posts and pages only: the reporter never tracks a product. + $reported = in_array( $post_type, array( 'post', 'page' ), true ); + if ( $reported ) { + $this->plugin->reporter->after_push( $post_id ); + } + + $data = array( + 'created' => ! $existing_id, + 'updated' => (bool) $existing_id, + 'post_id' => $post_id, + 'status' => get_post_status( $post_id ), + 'permalink' => get_permalink( $post_id ), + 'edit_link' => add_query_arg( + array( + 'post' => $post_id, + 'action' => 'edit', ), - ) + admin_url( 'post.php' ) + ), ); + if ( $reported ) { + // Where this post's status-report counter stands. CiteCue records + // it as its baseline, so a report built before this push and + // delivered after it is recognised as out of date. + $data['seq'] = $this->plugin->reporter->current_seq( $post_id ); + } + $response = rest_ensure_response( $data ); $response->set_status( $existing_id ? 200 : 201 ); return $response; } @@ -523,12 +544,9 @@ private function find_by_external_id( $external_id ) { * @return bool */ private function edited_locally( $post_id ) { - $last_hash = (string) get_post_meta( $post_id, '_citecue_content_hash', true ); - if ( '' === $last_hash ) { - return false; - } - $post = get_post( $post_id ); - return $post && md5( $post->post_content ) !== $last_hash; + // One test, shared with the status reporter, so "edited" means the same + // thing when CiteCue refuses a push and when it is told about an edit. + return Citecue_Status_Reporter::content_edited( get_post( $post_id ) ); } /** diff --git a/includes/class-citecue-plugin.php b/includes/class-citecue-plugin.php index 2da5451..5392a49 100644 --- a/includes/class-citecue-plugin.php +++ b/includes/class-citecue-plugin.php @@ -66,6 +66,13 @@ final class Citecue_Plugin { */ public $connect; + /** + * Status reporter: tells CiteCue when a CiteCue post changes in WordPress. + * + * @var Citecue_Status_Reporter + */ + public $reporter; + /** * Returns (and boots) the singleton. * @@ -88,6 +95,8 @@ private function __construct() { $this->activity = new Citecue_Activity_Log(); $this->api = new Citecue_Api_Client( $this->settings ); $this->connect = new Citecue_Connect( $this ); + $this->reporter = new Citecue_Status_Reporter( $this ); + $this->reporter->register(); ( new Citecue_Llms_Txt( $this ) )->register(); ( new Citecue_Proxy( $this ) )->register(); @@ -188,6 +197,10 @@ public function on_init() { * @return void */ public function daily_sync() { + // Local only, and before the connection check: marks can outlive a drain + // event whatever state the site is in. + $this->reporter->ensure_drain_scheduled(); + if ( ! $this->settings->is_connected() ) { return; } @@ -212,6 +225,9 @@ public static function activate() { $settings = new Citecue_Settings(); $settings->ensure_ingest_secret(); + + // Marks left from before a deactivation get their drain back. + self::instance()->reporter->ensure_drain_scheduled(); } /** @@ -221,6 +237,9 @@ public static function activate() { */ public static function deactivate() { wp_clear_scheduled_hook( self::CRON_HOOK ); + // Pending status reports stay marked on their posts; activate() and the + // daily sync schedule the drain again, and they are sent then. + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); // Queued metadata refreshes, one per URL. wp_unschedule_hook(), not // wp_clear_scheduled_hook(): the latter only clears events whose // arguments match the ones passed, and every one of these carries its diff --git a/includes/class-citecue-status-reporter.php b/includes/class-citecue-status-reporter.php new file mode 100644 index 0000000..aa74215 --- /dev/null +++ b/includes/class-citecue-status-reporter.php @@ -0,0 +1,1258 @@ +plugin = $plugin; + } + + /** + * Hooks the triggers and the drain. + * + * @return void + */ + public function register() { + add_action( 'transition_post_status', array( $this, 'on_transition_post_status' ), 10, 3 ); + add_action( 'before_delete_post', array( $this, 'on_before_delete_post' ), 10, 2 ); + add_action( 'post_updated', array( $this, 'on_post_updated' ), 10, 2 ); + add_action( 'wp_after_insert_post', array( $this, 'on_after_insert_post' ), 10, 3 ); + add_action( self::DRAIN_HOOK, array( $this, 'drain' ) ); + add_action( 'update_option_' . Citecue_Settings::OPTION, array( $this, 'on_settings_updated' ), 10, 2 ); + } + + /** + * Settings saved: when content pushes just went from off to on, marks that + * waited out the pause get their drain back. + * + * @param mixed $old_value Old settings. + * @param mixed $value New settings. + * @return void + */ + public function on_settings_updated( $old_value, $value ) { + $was = is_array( $old_value ) && ! empty( $old_value['ingest_enabled'] ); + $now = is_array( $value ) && ! empty( $value['ingest_enabled'] ); + // Not ensure_drain_scheduled(): a drain that ran during the pause left + // its retry a day out, and that event must be pulled forward. + if ( $now && ! $was && $this->has_pending() ) { + $this->schedule_drain_now(); + } + } + + /** + * Whether anything waits to be reported: a pending mark or a stored delete + * report. + * + * @return bool + */ + private function has_pending() { + global $wpdb; + + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- an existence check over the queue. + $mark = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s LIMIT 1", self::META_PENDING ) ); + if ( null !== $mark ) { + return true; + } + $option = $wpdb->get_var( $wpdb->prepare( "SELECT option_id FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT 1", $wpdb->esc_like( self::DELETED_OPTION_PREFIX ) . '%' ) ); + // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching + return null !== $option; + } + + /** + * Idempotent: schedules the drain when it has no event and something is + * waiting. Called from activation, the daily sync and the settings save, so + * a drain that died mid-run, a cron cleaner, or a deactivate/reactivate + * can't leave marks stranded until some other post changes. + * + * @return void + */ + public function ensure_drain_scheduled() { + if ( false !== wp_next_scheduled( self::DRAIN_HOOK ) || ! $this->has_pending() ) { + return; + } + wp_schedule_single_event( $this->now(), self::DRAIN_HOOK ); + } + + /** + * Replaces the clock. Pass null to go back to time(). + * + * @param callable|null $clock Returns unix seconds. + * @return void + */ + public function set_clock( $clock ) { + $this->clock = $clock; + } + + /** + * Replaces the cron spawner. Pass null to go back to spawn_cron(). + * + * @param callable|null $spawner Called after a mark. + * @return void + */ + public function set_spawner( $spawner ) { + $this->spawner = $spawner; + } + + /** + * The current time. + * + * @return int + */ + private function now() { + return $this->clock ? (int) call_user_func( $this->clock ) : time(); + } + + /** + * Stops the hooks from marking anything until resume(). Used around the + * plugin's own insert/update of a pushed post. + * + * @return void + */ + public function suspend() { + ++$this->suspended; + } + + /** + * Undoes one suspend(). + * + * @return void + */ + public function resume() { + $this->suspended = max( 0, $this->suspended - 1 ); + } + + /** + * Whether reports are marked and sent at all: the site holds an API key, + * accepts content pushes (so it can hold CiteCue posts), and reports an + * https address. A plain-http address would only earn a 400 from CiteCue, + * and the plugin already refuses pushes there. + * + * @return bool + */ + public function is_reporting_enabled() { + $settings = $this->plugin->settings; + if ( '' === (string) $settings->get( 'api_key' ) || ! $settings->get( 'ingest_enabled' ) ) { + return false; + } + return 'https' === wp_parse_url( home_url(), PHP_URL_SCHEME ); + } + + /** + * Whether the post is one this reporter tracks: a post or page carrying both + * CiteCue metas. + * + * @param WP_Post|int|null $post Post. + * @return bool + */ + public function is_tracked_post( $post ) { + $post = get_post( $post ); + if ( ! $post || ! in_array( $post->post_type, array( 'post', 'page' ), true ) ) { + return false; + } + return '' !== (string) get_post_meta( $post->ID, '_citecue_external_id', true ) + && '' !== (string) get_post_meta( $post->ID, '_citecue_source', true ); + } + + /** + * Whether a hook should act on this post right now. + * + * @param WP_Post|int|null $post Post. + * @return bool + */ + private function should_track( $post ) { + return 0 === $this->suspended && $this->is_reporting_enabled() && $this->is_tracked_post( $post ); + } + + /** + * Whether the post's text differs from what the last push stored: the same + * hash test the content endpoint uses to refuse a push over an edit. + * + * @param WP_Post|null $post Post. + * @return bool + */ + public static function content_edited( $post ) { + if ( ! $post ) { + return false; + } + $last_hash = (string) get_post_meta( $post->ID, '_citecue_content_hash', true ); + if ( '' === $last_hash ) { + return false; + } + return md5( $post->post_content ) !== $last_hash; + } + + /** + * `transition_post_status`: any real status change. + * + * @param string $new_status New status. + * @param string $old_status Old status. + * @param WP_Post $post Post. + * @return void + */ + public function on_transition_post_status( $new_status, $old_status, $post ) { + if ( $new_status === $old_status || in_array( $new_status, array( 'auto-draft', 'inherit' ), true ) ) { + return; + } + if ( $this->should_track( $post ) ) { + $this->mark( $post->ID ); + } + } + + /** + * `post_updated`: the text and the slug are stored by now, even when a + * later step of a REST save fails and `wp_after_insert_post` never fires. + * + * @param int $post_id Post ID. + * @param WP_Post $post Post after the update. + * @return void + */ + public function on_post_updated( $post_id, $post ) { + $this->check_live_post( $post_id, $post ); + } + + /** + * `wp_after_insert_post`: looks again once the REST controller (the block + * editor) has saved the categories, which it does only after + * `post_updated`; with `%category%` in the permalinks a new category alone + * is a new address. + * + * @param int $post_id Post ID. + * @param WP_Post $post Post after the save. + * @param bool $update Whether this was an update. + * @return void + */ + public function on_after_insert_post( $post_id, $post, $update = true ) { + if ( $update ) { + $this->check_live_post( $post_id, $post ); + } + } + + /** + * Marks a live post whose text or address changed since the last values + * reported, so an edit or a new address is reported once, not on every + * save. + * + * Every save bumps the generation first, so a report in flight when the + * post changed is never taken as the last word, even when the change + * undoes it and so matches the values last acknowledged. A post's earlier + * address can't be rebuilt to compare against (it is built from the terms + * as they are now), so this is the only safe test. Bumping before reading + * what was reported closes the race with a reply being recorded. + * + * @param int $post_id Post ID. + * @param WP_Post|null $post Post after the save. + * @return void + */ + private function check_live_post( $post_id, $post ) { + if ( ! $post || ! is_post_status_viewable( $post->post_status ) || ! $this->should_track( $post ) ) { + return; + } + + $this->bump_generation( $post_id ); + wp_cache_delete( $post_id, 'post_meta' ); + + $edited = self::content_edited( $post ); + $reported_edited = '1' === (string) get_post_meta( $post_id, self::META_REPORTED_EDITED, true ); + $permalink = (string) get_permalink( $post ); + $reported_permalink = (string) get_post_meta( $post_id, self::META_REPORTED_PERMALINK, true ); + + if ( $edited !== $reported_edited || $permalink !== $reported_permalink ) { + $this->mark( $post_id ); + } + } + + /** + * `before_delete_post`: the post and its meta still exist, so the whole + * report is built now and kept in an option of its own. + * + * @param int $post_id Post ID. + * @param WP_Post|null $post Post (WordPress 5.5+). + * @return void + */ + public function on_before_delete_post( $post_id, $post = null ) { + $post = $post instanceof WP_Post ? $post : get_post( $post_id ); + if ( ! $post || ! $this->should_track( $post ) ) { + return; + } + + $report = $this->build( $post, 'deleted', true ); + if ( ! is_array( $report ) ) { + return; + } + + $entry = array( + 'report' => $report, + 'pending' => $this->now(), + 'attempts' => 0, + 'not_before' => 0, + 'caught_up' => false, + ); + $name = self::DELETED_OPTION_PREFIX . (int) $post->ID; + if ( ! add_option( $name, $entry, '', 'no' ) ) { + update_option( $name, $entry, false ); + } + + $this->schedule_drain_now(); + } + + /** + * Marks a post as having something to report. + * + * Keeps an existing mark's time so the post holds its place in the queue, + * bumps the generation, and clears the attempt count, the not-before time + * the catch-up flag and any site-wide hold, so a new change goes out at the + * next run even if an older one was backing off. + * + * @param int $post_id Post ID. + * @return void + */ + public function mark( $post_id ) { + $post_id = (int) $post_id; + + // The generation first: a drain finishing between the two steps then + // either sees the new generation and marks again, or has already + // cleared the mark this one sets. + $this->bump_generation( $post_id ); + if ( '' === (string) get_post_meta( $post_id, self::META_PENDING, true ) ) { + update_post_meta( $post_id, self::META_PENDING, $this->now() ); + } + delete_post_meta( $post_id, self::META_ATTEMPTS ); + delete_post_meta( $post_id, self::META_NOT_BEFORE ); + delete_post_meta( $post_id, self::META_CAUGHT_UP ); + // A fresh change is worth one try even during an outage hold. + delete_option( self::SITE_NOT_BEFORE ); + + $this->schedule_drain_now(); + } + + /** + * Makes sure the drain runs now: schedules it if it is not scheduled, pulls + * a later one forward (WordPress ignores a second single event for the same + * hook within ten minutes of an existing one), and nudges WP-Cron. + * + * @return void + */ + private function schedule_drain_now() { + $now = $this->now(); + $next = wp_next_scheduled( self::DRAIN_HOOK ); + + if ( false === $next ) { + wp_schedule_single_event( $now, self::DRAIN_HOOK ); + } elseif ( $next > $now ) { + wp_unschedule_event( $next, self::DRAIN_HOOK ); + wp_schedule_single_event( $now, self::DRAIN_HOOK ); + } + + if ( $this->spawner ) { + call_user_func( $this->spawner ); + } elseif ( function_exists( 'spawn_cron' ) ) { + spawn_cron(); + } + } + + /** + * Adds one to a numeric post meta and returns the new value, or 0 when it + * could not be done. + * + * @param int $post_id Post ID. + * @param string $key Meta key. + * @return int The new value (always at least 1), or 0 after repeated races. + */ + private function increment_meta( $post_id, $key ) { + return $this->cas_meta( + $post_id, + $key, + static function ( $current ) { + return $current + 1; + } + ); + } + + /** + * Raises a numeric post meta to at least a value, never lowering it. + * + * @param int $post_id Post ID. + * @param string $key Meta key. + * @param int $value Minimum value. + * @return int The value now stored, or 0 after repeated races. + */ + private function raise_meta( $post_id, $key, $value ) { + return $this->cas_meta( + $post_id, + $key, + static function ( $current ) use ( $value ) { + return $current < $value ? $value : null; + } + ); + } + + /** + * A compare-and-swap on a numeric post meta, in plain SQL: read the value, + * then UPDATE that one row (by meta_id, so a duplicate row can't make two + * matches) only where it still holds what was read, and accept the + * result only when exactly one row changed. Two concurrent requests can + * never both win the same number, and nothing depends on MySQL-only + * functions or on one connection serving both statements (SQLite, + * read/write-splitting drop-ins). + * + * @param int $post_id Post ID. + * @param string $key Meta key. + * @param callable $compute Takes the current value, returns the new one, or + * null to leave it as it is. + * @return int The value now stored, or 0 after repeated races. + */ + private function cas_meta( $post_id, $key, $compute ) { + global $wpdb; + + // Creates the row when missing; a no-op when it exists. + add_post_meta( $post_id, $key, 0, true ); + + for ( $try = 0; $try < self::CAS_TRIES; $try++ ) { + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- must bypass the meta cache to see a concurrent write. + $row = $wpdb->get_row( $wpdb->prepare( "SELECT meta_id, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s ORDER BY meta_id ASC LIMIT 1", $post_id, $key ), ARRAY_A ); + if ( ! is_array( $row ) ) { + add_post_meta( $post_id, $key, 0, true ); + continue; + } + $current = (string) $row['meta_value']; + $next = call_user_func( $compute, (int) $current ); + if ( null === $next ) { + wp_cache_delete( $post_id, 'post_meta' ); + return (int) $current; + } + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- an atomic compare-and-swap has no WordPress API. + $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = %s WHERE meta_id = %d AND meta_value = %s", (string) $next, (int) $row['meta_id'], $current ) ); + if ( 1 === (int) $wpdb->rows_affected ) { + wp_cache_delete( $post_id, 'post_meta' ); + return (int) $next; + } + } + + wp_cache_delete( $post_id, 'post_meta' ); + return 0; + } + + /** + * Moves a post's generation to a value it has not had. Only has to change, + * so when the compare-and-swap keeps losing it falls back to a plain write. + * + * @param int $post_id Post ID. + * @return void + */ + private function bump_generation( $post_id ) { + if ( 0 !== $this->increment_meta( $post_id, self::META_GENERATION ) ) { + return; + } + wp_cache_delete( $post_id, 'post_meta' ); + update_post_meta( $post_id, self::META_GENERATION, (int) get_post_meta( $post_id, self::META_GENERATION, true ) + wp_rand( 1000, 9999 ) ); + } + + /** + * The post's current report counter (0 for a post pushed before 1.5.0). + * + * @param int $post_id Post ID. + * @return int + */ + public function current_seq( $post_id ) { + wp_cache_delete( (int) $post_id, 'post_meta' ); + return (int) get_post_meta( $post_id, self::META_SEQ, true ); + } + + /** + * Normalizes a WordPress status to what CiteCue accepts: publish for any + * publicly viewable status, trash, deleted, and draft for everything else + * (draft, pending, private, scheduled and custom statuses). + * + * @param string $status WordPress post status. + * @return string + */ + public static function normalize_status( $status ) { + if ( 'trash' === $status ) { + return 'trash'; + } + return is_post_status_viewable( $status ) ? 'publish' : 'draft'; + } + + /** + * Builds a report for a post as it is now, taking the next sequence number. + * + * The number comes first and the post is read after it, from the database. + * A push returns the counter as CiteCue's baseline, so a push that lands + * before the read is in the report, and one that lands after it has a + * baseline the report doesn't beat. The other way round, an old copy could + * go out with a number above the push's. + * + * @param WP_Post|int $post Post. + * @param string|null $status_override Force a status ('deleted' for a delete report). + * @param bool $allow_fallback When no sequence can be allocated, use the counter plus one + * instead of failing (a delete report has no second chance). + * @return array|null|false The request body; null when the post can't be + * reported; false when no sequence number could be + * allocated (try again later). + */ + public function build( $post, $status_override = null, $allow_fallback = false ) { + $post = get_post( $post ); + if ( ! $post ) { + return null; + } + + $external_id = (string) get_post_meta( $post->ID, '_citecue_external_id', true ); + $source = (string) get_post_meta( $post->ID, '_citecue_source', true ); + if ( '' === $external_id || '' === $source ) { + return null; + } + + $seq = $this->increment_meta( $post->ID, self::META_SEQ ); + if ( 0 === $seq ) { + if ( ! $allow_fallback ) { + return false; + } + $seq = $this->current_seq( $post->ID ) + 1; + } + + if ( null === $status_override ) { + $post = $this->read_again( $post ); + if ( ! $post ) { + return null; + } + } + + $status = null !== $status_override ? $status_override : self::normalize_status( $post->post_status ); + + $report = array( + 'external_id' => $external_id, + 'source' => $source, + 'site_url' => home_url( '/' ), + 'post_id' => (int) $post->ID, + 'status' => $status, + ); + if ( 'publish' === $status ) { + $report['permalink'] = (string) get_permalink( $post ); + } + if ( 'deleted' !== $status ) { + $report['edited'] = self::content_edited( $post ); + } + $report['seq'] = $seq; + $report['observed_at'] = $this->now(); + + return $report; + } + + /** + * Reads a post from the database again, with the meta and terms its report + * is built from. A run loads its posts up front, so by the time one is sent + * the cached copy can be half a minute old. + * + * Not clean_post_cache(): page caches purge on the hook it fires, and + * nothing has changed here. + * + * @param WP_Post $post Post. + * @return WP_Post|null Null when it is gone. + */ + private function read_again( $post ) { + wp_cache_delete( $post->ID, 'posts' ); + wp_cache_delete( $post->ID, 'post_meta' ); + clean_object_term_cache( $post->ID, $post->post_type ); + // Older WordPress leaves cached term queries alone there. + wp_cache_delete( 'last_changed', 'terms' ); + return get_post( $post->ID ); + } + + /** + * After a successful CiteCue push: the push replaced the text and the + * status, so nothing is pending any more and what was last reported is the + * pushed state. + * + * @param int $post_id Post ID. + * @return void + */ + public function after_push( $post_id ) { + $post_id = (int) $post_id; + + delete_post_meta( $post_id, self::META_PENDING ); + delete_post_meta( $post_id, self::META_ATTEMPTS ); + delete_post_meta( $post_id, self::META_NOT_BEFORE ); + delete_post_meta( $post_id, self::META_CAUGHT_UP ); + // A report in flight must not back off an entry that no longer exists. + $this->bump_generation( $post_id ); + + update_post_meta( $post_id, self::META_REPORTED_EDITED, '0' ); + update_post_meta( $post_id, self::META_REPORTED_PERMALINK, (string) get_permalink( $post_id ) ); + } + + /** + * Forgets every pending mark and stored delete report (a disconnect: a + * reconnect may pair a different project) and the cron event and the + * given-up record with them. + * + * @return void + */ + public function clear_pending() { + global $wpdb; + + $keys = array( self::META_PENDING, self::META_ATTEMPTS, self::META_NOT_BEFORE, self::META_CAUGHT_UP ); + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- finding the posts that hold a mark. + $ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s", self::META_PENDING ) ); + foreach ( (array) $ids as $id ) { + foreach ( $keys as $key ) { + delete_post_meta( (int) $id, $key ); + } + } + + foreach ( $this->delete_option_rows( 0 ) as $row ) { + delete_option( $row['name'] ); + } + + delete_option( self::GIVEN_UP_OPTION ); + delete_option( self::SITE_NOT_BEFORE ); + wp_clear_scheduled_hook( self::DRAIN_HOOK ); + } + + /** + * The given-up record, empty once its last entry is 30 days old. + * + * @return array{count:int,last:int} + */ + public static function given_up() { + $record = get_option( self::GIVEN_UP_OPTION, array() ); + $record = is_array( $record ) ? $record : array(); + $last = isset( $record['last'] ) ? (int) $record['last'] : 0; + + // One old failure must not stay on the settings screen for good. + if ( $last > 0 && time() - $last > self::GIVEN_UP_TTL ) { + return array( + 'count' => 0, + 'last' => 0, + ); + } + return array( + 'count' => isset( $record['count'] ) ? (int) $record['count'] : 0, + 'last' => $last, + ); + } + + /** + * Counts a report that ran out of retries. + * + * @return void + */ + private function record_given_up() { + $record = self::given_up(); // Already empty when the old record has expired. + update_option( + self::GIVEN_UP_OPTION, + array( + 'count' => $record['count'] + 1, + 'last' => $this->now(), + ), + false + ); + } + + /** + * The cron callback: sends due entries, then schedules the next run. + * + * @return void + */ + public function drain() { + if ( ! $this->is_reporting_enabled() ) { + // Reporting is paused (disconnected, pushes off, http site). Keep + // the marks, and look again in a day. + if ( false === wp_next_scheduled( self::DRAIN_HOOK ) && $this->has_pending() ) { + wp_schedule_single_event( $this->now() + DAY_IN_SECONDS, self::DRAIN_HOOK ); + } + return; + } + + $started = $this->now(); + + foreach ( $this->due_entries( $started, self::MAX_PER_RUN ) as $entry ) { + // Leave room for one more request to end inside the budget. + if ( $this->now() - $started >= self::RUN_BUDGET - Citecue_Api_Client::STATUS_TIMEOUT ) { + break; + } + if ( $this->send_entry( $entry ) ) { + break; + } + } + + $this->reschedule(); + } + + /** + * Due entries, oldest first: pending posts of any status (a default query + * leaves trashed posts out) and stored delete reports. + * + * @param int $now Current time. + * @param int $limit Maximum entries. + * @return array[] + */ + private function due_entries( $now, $limit ) { + $entries = array(); + + // A site-wide hold from an outage reply: nothing is due until it passes. + $hold = (int) get_option( self::SITE_NOT_BEFORE, 0 ); + if ( $hold > $now ) { + $this->purge_unprocessable(); + return array(); + } + if ( $hold > 0 ) { + delete_option( self::SITE_NOT_BEFORE ); + } + + $query = new WP_Query( + array( + 'post_type' => array( 'post', 'page' ), + 'post_status' => array_values( get_post_stati() ), + 'fields' => 'ids', + 'posts_per_page' => $limit, + 'no_found_rows' => true, + 'ignore_sticky_posts' => true, + 'suppress_filters' => true, + 'update_post_term_cache' => false, + 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- the queue is post meta by design. + 'relation' => 'AND', + 'citecue_pending' => array( + 'key' => self::META_PENDING, + 'compare' => 'EXISTS', + 'type' => 'NUMERIC', + ), + array( + 'relation' => 'OR', + array( + 'key' => self::META_NOT_BEFORE, + 'compare' => 'NOT EXISTS', + ), + array( + 'key' => self::META_NOT_BEFORE, + 'value' => $now, + 'compare' => '<=', + 'type' => 'NUMERIC', + ), + ), + ), + 'orderby' => array( + 'citecue_pending' => 'ASC', + 'ID' => 'ASC', + ), + ) + ); + foreach ( $query->posts as $post_id ) { + $post_id = (int) $post_id; + if ( ! $this->is_tracked_post( $post_id ) ) { + $this->clear_post_entry( $post_id ); + continue; + } + $entries[] = array( + 'kind' => 'post', + 'id' => $post_id, + 'pending' => (int) get_post_meta( $post_id, self::META_PENDING, true ), + 'gen' => (int) get_post_meta( $post_id, self::META_GENERATION, true ), + 'attempts' => (int) get_post_meta( $post_id, self::META_ATTEMPTS, true ), + 'caught_up' => '' !== (string) get_post_meta( $post_id, self::META_CAUGHT_UP, true ), + ); + } + + foreach ( $this->delete_option_rows( self::OPTION_WINDOW ) as $row ) { + $stored = $row['value']; + if ( ! is_array( $stored ) || empty( $stored['report'] ) || ! is_array( $stored['report'] ) ) { + delete_option( $row['name'] ); + continue; + } + if ( isset( $stored['not_before'] ) && (int) $stored['not_before'] > $now ) { + continue; + } + $entries[] = array( + 'kind' => 'delete', + 'id' => $row['id'], + 'name' => $row['name'], + 'pending' => isset( $stored['pending'] ) ? (int) $stored['pending'] : 0, + 'attempts' => isset( $stored['attempts'] ) ? (int) $stored['attempts'] : 0, + 'caught_up' => ! empty( $stored['caught_up'] ), + 'report' => $stored['report'], + ); + } + + usort( + $entries, + static function ( $a, $b ) { + return array( $a['pending'], $a['id'] ) <=> array( $b['pending'], $b['id'] ); + } + ); + + return array_slice( $entries, 0, $limit ); + } + + /** + * Stored delete reports, oldest first. + * + * @param int $limit Maximum rows; 0 for all. + * @return array + */ + private function delete_option_rows( $limit ) { + global $wpdb; + + $like = $wpdb->esc_like( self::DELETED_OPTION_PREFIX ) . '%'; + if ( $limit > 0 ) { + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- no API lists options by prefix. + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s ORDER BY option_id ASC LIMIT %d", $like, $limit ), ARRAY_A ); + } else { + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- no API lists options by prefix. + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s ORDER BY option_id ASC", $like ), ARRAY_A ); + } + + $out = array(); + foreach ( (array) $rows as $row ) { + $out[] = array( + 'name' => (string) $row['option_name'], + 'id' => (int) substr( (string) $row['option_name'], strlen( self::DELETED_OPTION_PREFIX ) ), + 'value' => maybe_unserialize( $row['option_value'] ), + ); + } + return $out; + } + + /** + * Sends one entry and applies the outcome. + * + * @param array $entry Entry from due_entries(). + * @return bool Whether the run should stop. + */ + private function send_entry( array $entry ) { + if ( 'delete' === $entry['kind'] ) { + $body = $entry['report']; + } else { + if ( ! $this->is_tracked_post( $entry['id'] ) ) { + // Gone, or no longer a CiteCue post: nothing to report. + $this->clear_post_entry( $entry['id'] ); + return false; + } + $body = $this->build( $entry['id'] ); + if ( false === $body ) { + // No sequence number to send: back this entry off so it is not + // first in line forever, and let the run go on. + $this->back_off( $entry, 0 ); + return false; + } + if ( null === $body ) { + $this->clear_post_entry( $entry['id'] ); + return false; + } + } + + $response = $this->plugin->api->post_content_status( $body ); + return $this->handle_response( $entry, $body, $response ); + } + + /** + * Applies a reply (or a transport failure) to an entry. + * + * @param array $entry Entry. + * @param array $body The report that was sent. + * @param array|WP_Error $response Client result. + * @return bool Whether the run should stop. + */ + private function handle_response( array $entry, array $body, $response ) { + if ( is_wp_error( $response ) ) { + $this->hold_site( $this->back_off( $entry, 0 ) ); + return true; + } + + $status = (int) $response['status']; + $data = isset( $response['data'] ) && is_array( $response['data'] ) ? $response['data'] : array(); + + if ( $status >= 200 && $status < 300 ) { + // Only CiteCue's own reply counts as applied: a 200 from a WAF or a + // cache in front of it carries some page, not `{ok: true, result}`. + $result = isset( $data['result'] ) && is_string( $data['result'] ) ? $data['result'] : ''; + if ( true !== ( isset( $data['ok'] ) ? $data['ok'] : null ) || ! in_array( $result, self::KNOWN_RESULTS, true ) ) { + $this->hold_site( $this->back_off( $entry, 0 ) ); + return true; + } + + if ( 'ignored' === $result ) { + $reason = isset( $data['reason'] ) ? (string) $data['reason'] : ''; + if ( + 'out_of_order' === $reason + && isset( $data['recorded_seq'] ) && is_numeric( $data['recorded_seq'] ) + && ! $entry['caught_up'] + && (int) $data['recorded_seq'] > $this->own_counter( $entry, $body ) + ) { + $this->catch_up( $entry, (int) $data['recorded_seq'] ); + return false; + } + } else { + $this->remember_reported( $entry, $body ); + } + + $this->finish_entry( $entry ); + return false; + } + + if ( 400 === $status || 404 === $status ) { + $this->finish_entry( $entry ); + return false; + } + + $busy = 503 === $status && isset( $data['error'] ) && 'busy' === $data['error']; + $not_before = $this->back_off( $entry, $this->parse_retry_after( isset( $response['retry_after'] ) ? (string) $response['retry_after'] : '' ) ); + + if ( $busy ) { + return false; + } + if ( in_array( $status, array( 401, 403, 408, 429 ), true ) || $status >= 500 ) { + $this->hold_site( $not_before ); + return true; + } + return false; + } + + /** + * Remembers that CiteCue is not taking reports until a time, so the next run + * does not walk into the same outage one entry at a time. + * + * @param int $not_before Unix time, or 0 to fall back to the first retry delay. + * @return void + */ + private function hold_site( $not_before ) { + $not_before = $not_before > 0 ? $not_before : $this->now() + self::RETRY_DELAYS[0]; + if ( $not_before > (int) get_option( self::SITE_NOT_BEFORE, 0 ) ) { + update_option( self::SITE_NOT_BEFORE, $not_before, false ); + } + } + + /** + * The post's own counter, for deciding whether CiteCue's is ahead of it. + * + * @param array $entry Entry. + * @param array $body Report sent. + * @return int + */ + private function own_counter( array $entry, array $body ) { + return 'delete' === $entry['kind'] ? (int) $body['seq'] : $this->current_seq( $entry['id'] ); + } + + /** + * CiteCue's recorded sequence is ahead of this post's counter (a restore, a + * reinstall that dropped meta). Raises the counter and keeps the entry so + * the current state goes out again with a sequence CiteCue accepts. Once per + * entry. + * + * @param array $entry Entry. + * @param int $recorded_seq CiteCue's recorded sequence. + * @return void + */ + private function catch_up( array $entry, $recorded_seq ) { + if ( 'delete' === $entry['kind'] ) { + $stored = get_option( $entry['name'] ); + if ( is_array( $stored ) && isset( $stored['report'] ) ) { + $stored['report']['seq'] = $recorded_seq + 1; + $stored['caught_up'] = true; + update_option( $entry['name'], $stored, false ); + } + return; + } + + // Never lowers: a concurrent request may have moved the counter past it. + if ( 0 === $this->raise_meta( $entry['id'], self::META_SEQ, $recorded_seq ) ) { + return; + } + if ( $this->entry_is_current( $entry ) ) { + update_post_meta( $entry['id'], self::META_CAUGHT_UP, 1 ); + } + } + + /** + * Stores what was reported, so check_live_post() can tell a new change from the + * one already sent. + * + * @param array $entry Entry. + * @param array $body Report sent. + * @return void + */ + private function remember_reported( array $entry, array $body ) { + if ( 'post' !== $entry['kind'] || 'deleted' === $body['status'] || ! $this->entry_is_current( $entry ) ) { + return; + } + update_post_meta( $entry['id'], self::META_REPORTED_EDITED, ! empty( $body['edited'] ) ? '1' : '0' ); + if ( isset( $body['permalink'] ) ) { + update_post_meta( $entry['id'], self::META_REPORTED_PERMALINK, (string) $body['permalink'] ); + } + } + + /** + * Whether a post entry still carries the generation it was captured with. + * A delete report has no generation: nothing can change a deleted post. + * + * @param array $entry Entry. + * @return bool + */ + private function entry_is_current( array $entry ) { + if ( 'delete' === $entry['kind'] ) { + return true; + } + wp_cache_delete( $entry['id'], 'post_meta' ); + return (int) get_post_meta( $entry['id'], self::META_GENERATION, true ) === (int) $entry['gen']; + } + + /** + * Clears a sent entry, unless the post changed while the report was in + * flight. + * + * @param array $entry Entry. + * @return bool Whether it was cleared. + */ + private function finish_entry( array $entry ) { + if ( ! $this->entry_is_current( $entry ) ) { + return false; + } + if ( 'delete' === $entry['kind'] ) { + delete_option( $entry['name'] ); + } else { + $this->clear_post_entry( $entry['id'] ); + // A change can land between the check and the delete above: look + // again, and mark it once more if the generation moved. + if ( ! $this->entry_is_current( $entry ) ) { + $this->mark( $entry['id'] ); + return false; + } + } + return true; + } + + /** + * Removes a post's pending mark and its retry state. + * + * @param int $post_id Post ID. + * @return void + */ + private function clear_post_entry( $post_id ) { + delete_post_meta( $post_id, self::META_PENDING ); + delete_post_meta( $post_id, self::META_ATTEMPTS ); + delete_post_meta( $post_id, self::META_NOT_BEFORE ); + delete_post_meta( $post_id, self::META_CAUGHT_UP ); + } + + /** + * Adds an attempt and sets the not-before time, or gives the entry up after + * the fourth retry. A changed post keeps its fresh state either way. + * + * @param array $entry Entry. + * @param int $retry_after Seconds the server asked for, or 0. + * @return int The not-before time set, or 0 when none was. + */ + private function back_off( array $entry, $retry_after ) { + if ( ! $this->entry_is_current( $entry ) ) { + return 0; + } + + $attempts = (int) $entry['attempts'] + 1; + if ( $attempts > count( self::RETRY_DELAYS ) ) { + if ( $this->finish_entry( $entry ) ) { + $this->record_given_up(); + } + return 0; + } + + $delay = self::RETRY_DELAYS[ $attempts - 1 ]; + $delay = (int) round( $delay * ( 1 + wp_rand( 0, 30 ) / 100 ) ); + $not_before = $this->now() + min( max( $delay, (int) $retry_after ), self::RETRY_CAP ); + + if ( 'delete' === $entry['kind'] ) { + $stored = get_option( $entry['name'] ); + if ( is_array( $stored ) ) { + $stored['attempts'] = $attempts; + $stored['not_before'] = $not_before; + update_option( $entry['name'], $stored, false ); + } + return $not_before; + } + + update_post_meta( $entry['id'], self::META_ATTEMPTS, $attempts ); + update_post_meta( $entry['id'], self::META_NOT_BEFORE, $not_before ); + return $not_before; + } + + /** + * Seconds from a Retry-After header: a number of seconds or an HTTP date. + * + * @param string $header Header value. + * @return int + */ + private function parse_retry_after( $header ) { + $header = trim( $header ); + if ( '' === $header ) { + return 0; + } + if ( preg_match( '/^\d+$/', $header ) ) { + return (int) $header; + } + $at = strtotime( $header ); + return false === $at ? 0 : max( 0, $at - $this->now() ); + } + + /** + * Removes what due_entries() can never process: marks on posts that are gone + * or no longer tracked, and delete options that hold no report. Without + * this a stuck entry would reschedule the drain every minute for ever. + * + * @return array{remaining:int,earliest:int|null} What is left that can be processed. + */ + private function purge_unprocessable() { + global $wpdb; + + $remaining = 0; + $earliest = null; + + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- one scan over the front of the queue. + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT p.post_id AS post_id, nb.meta_value AS nb FROM {$wpdb->postmeta} p LEFT JOIN {$wpdb->postmeta} nb ON nb.post_id = p.post_id AND nb.meta_key = %s WHERE p.meta_key = %s ORDER BY CAST( COALESCE( nb.meta_value, '0' ) AS UNSIGNED ) ASC LIMIT %d", self::META_NOT_BEFORE, self::META_PENDING, self::OPTION_WINDOW ), ARRAY_A ); + $stati = get_post_stati(); + foreach ( (array) $rows as $row ) { + $post_id = (int) $row['post_id']; + if ( ! $this->is_tracked_post( $post_id ) ) { + $this->clear_post_entry( $post_id ); + continue; + } + if ( ! in_array( get_post_status( $post_id ), $stati, true ) ) { + continue; // The queue query can't see it either. + } + ++$remaining; + $not_before = (int) $row['nb']; + $earliest = null === $earliest ? $not_before : min( $earliest, $not_before ); + } + + foreach ( $this->delete_option_rows( self::OPTION_WINDOW ) as $option ) { + if ( ! is_array( $option['value'] ) || empty( $option['value']['report'] ) || ! is_array( $option['value']['report'] ) ) { + delete_option( $option['name'] ); + continue; + } + ++$remaining; + $not_before = isset( $option['value']['not_before'] ) ? (int) $option['value']['not_before'] : 0; + $earliest = null === $earliest ? $not_before : min( $earliest, $not_before ); + } + + return array( + 'remaining' => $remaining, + 'earliest' => $earliest, + ); + } + + /** + * Schedules the next run for the earliest not-before time among what can + * still be processed, held back by an outage's site-wide not-before, and no + * sooner than a minute from now. + * + * @return void + */ + private function reschedule() { + $state = $this->purge_unprocessable(); + if ( 0 === $state['remaining'] || null === $state['earliest'] ) { + return; + } + + $at = max( $this->now() + self::MIN_RESCHEDULE, $state['earliest'], (int) get_option( self::SITE_NOT_BEFORE, 0 ) ); + + wp_clear_scheduled_hook( self::DRAIN_HOOK ); + wp_schedule_single_event( $at, self::DRAIN_HOOK ); + } +} diff --git a/readme.txt b/readme.txt index 69cffa7..29814f1 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Tags: ai, ai-crawlers, gptbot, ai-seo, woocommerce Requires at least: 5.8 Tested up to: 7.1 Requires PHP: 7.4 -Stable tag: 1.3.0 +Stable tag: 1.5.0 License: GPLv2 or later License URI: https://www.gnu.org/licenses/gpl-2.0.html @@ -70,6 +70,8 @@ Before a URL is cached, queued or sent, every query argument WordPress does not **Refreshing the AI-crawler list** — once a day, on WP-Cron, for a connected site only. An unauthenticated request to `/api/delivery/v1/crawlers` fetches the current list of AI crawler User-Agent tokens, so newly launched crawlers are recognised without a plugin update. +**Reporting status changes** — in the background, on WP-Cron, after you publish, unpublish, trash, restore, permanently delete or re-address a post or page that CiteCue pushed, or edit the text of a live one, on a connected site that accepts content pushes and has an https address. The plugin posts to `/api/delivery/v2/content-status`: the post's CiteCue content id and source label, its WordPress post id, its status (published, draft, trash or deleted), its public address when it is published, whether its text was edited since CiteCue sent it, a per-post counter, a timestamp and this site's address. It never sends the post's text, title or author, or any visitor data. Reports are sent one at a time, at most 20 per run, and a failed report is retried up to four times, over about an hour or over several hours when CiteCue asks the plugin to wait longer, and then dropped. Posts CiteCue did not push are never reported. + **Verifying the installation** — when you connect, and whenever you click "Verify installation". The plugin requests your own site's `/llms.txt` over HTTP, identifying itself as an AI crawler, to confirm the plugin answers rather than a cache or CDN. This request goes to your site, not to CiteCue. Every outbound request identifies itself with a `CiteCue-WordPress/ (+)` User-Agent. @@ -140,6 +142,9 @@ Yes. Store pages (cart, checkout, account, all WooCommerce endpoints) are never == Upgrade Notice == += 1.5.0 = +Tells CiteCue when you publish, unpublish, trash, delete or edit a post it pushed, so CiteCue shows what is really on your site. Needs your site address to start with https. Nothing to reconfigure. + = 1.3.0 = Tells CiteCue when Maximum status is Published, so posts you schedule in CiteCue's Calendar are published live rather than sent as drafts. Sites already set to Published need one reconnect. Settings → CiteCue will ask. @@ -163,6 +168,13 @@ The plugin folder is now citecue-ai-auto-fix. If you installed 1.0.0 by uploadin == Changelog == += 1.5.0 = +* New: status reports. When you publish, unpublish, trash, restore or permanently delete a post or page that CiteCue pushed, change its address, or edit the text of a live one, the plugin tells CiteCue, so what CiteCue shows follows what is on your site. It is sent in the background on WP-Cron, never while you are saving, and a slow or unreachable CiteCue cannot hold up the editor. +* Reports are sent one at a time, at most 20 per run, and a failed one is retried up to four times, over about an hour or over several hours when CiteCue sends a Retry-After, before it is given up. Settings → CiteCue shows next to the connection status how many reports were given up, if any. +* Only posts and pages CiteCue pushed are reported, only on a connected site that accepts content pushes, and only while the site address is https. CiteCue's own pushes are never reported back to it. +* The content endpoint's reply now includes `seq`, the post's report counter, so CiteCue can tell a report built before a push from one built after it. +* Disconnecting now forgets reports that were waiting, and uninstalling removes the plugin's bookkeeping from posts and options. The posts themselves are left alone. + = 1.3.0 = * Connecting now tells CiteCue whether this site publishes pushed posts live. When Maximum status is Published, CiteCue's Calendar defaults its posts to published instead of draft. Draft and Pending keep them as drafts, as before. There is no new setting: the flag follows Maximum status, so it can never promise more than the site allows, and the cap still has the final say on every post. * Raising or lowering Maximum status after connecting now asks for a reconnect while content pushes are accepted, because CiteCue learns the setting only when the site connects. The prompt and the "Content pushes" status line say it is about publishing, not about page enhancements. diff --git a/tests/cases/test-admin-screen.php b/tests/cases/test-admin-screen.php index c18021f..e65a652 100644 --- a/tests/cases/test-admin-screen.php +++ b/tests/cases/test-admin-screen.php @@ -151,6 +151,41 @@ public function test_a_connected_site_shows_its_status_and_settings() { $this->assertStringNotContainsString( 'citecue_connect_start', $html ); } + /** + * Reports to CiteCue that ran out of retries are shown beside the connection + * status, so a person can tell why CiteCue disagrees with their site. + * + * @return void + */ + public function test_given_up_status_reports_are_shown_with_the_connection_status() { + $this->configure_delivery( array( 'project_domain' => 'example.org' ) ); + update_option( + Citecue_Status_Reporter::GIVEN_UP_OPTION, + array( + 'count' => 3, + 'last' => 1800000000, + ), + false + ); + + $html = $this->render(); + + $this->assertStringContainsString( 'Status reports', $html ); + $this->assertStringContainsString( '3 status changes could not be delivered to CiteCue', $html ); + $this->assertStringContainsString( esc_html( date_i18n( get_option( 'date_format' ), 1800000000 ) ), $html ); + } + + /** + * A row with nothing to say isn't rendered. + * + * @return void + */ + public function test_no_status_report_row_when_none_were_given_up() { + $this->configure_delivery( array( 'project_domain' => 'example.org' ) ); + + $this->assertStringNotContainsString( 'Status reports', $this->render() ); + } + /** * The status card puts a stale publish flag on the row it is about — * content pushes — and leaves page enhancements, which have not changed, diff --git a/tests/cases/test-ingest-content.php b/tests/cases/test-ingest-content.php index 5f7d831..1c84870 100644 --- a/tests/cases/test-ingest-content.php +++ b/tests/cases/test-ingest-content.php @@ -36,6 +36,40 @@ public function set_up() { ); } + /** + * Puts the reporter's cron spawner back. + * + * @return void + */ + public function tear_down() { + $this->plugin->reporter->set_spawner( null ); + parent::tear_down(); + } + + /** + * Makes the site one that reports status changes (https, connected), with a + * cron spawner that goes nowhere. + * + * @return void + */ + private function report_status_changes() { + update_option( 'home', 'https://example.org' ); + update_option( 'siteurl', 'https://example.org' ); + $this->plugin->settings->update( array( 'api_key' => self::API_KEY ) ); + $this->plugin->reporter->set_spawner( '__return_null' ); + } + + /** + * Whether a post has a pending status report. + * + * @param int $id Post ID. + * @return bool + */ + private function has_pending_report( $id ) { + wp_cache_delete( $id, 'post_meta' ); + return '' !== (string) get_post_meta( $id, Citecue_Status_Reporter::META_PENDING, true ); + } + /** * @return void */ @@ -289,6 +323,136 @@ public function test_force_overwrites_a_locally_edited_post() { $this->assertStringContainsString( 'Pushed again.', get_post( $id )->post_content ); } + /** + * CiteCue already knows what it just sent: a push that publishes or updates a + * post must not come back as a status report. + * + * @return void + */ + public function test_a_push_does_not_report_its_own_changes() { + $this->report_status_changes(); + $this->plugin->settings->update( array( 'ingest_post_status' => 'publish' ) ); + $id = $this->push( array( 'source' => 'citecue_autofix:optp_1' ) )->get_data()['post_id']; + + $this->push( + array( + 'source' => 'citecue_autofix:optp_1', + 'status' => 'publish', + 'title' => 'Retitled', + ), + array( 'timestamp' => time() + 1 ) + ); + + $this->assertSame( 'publish', get_post_status( $id ) ); + $this->assertFalse( $this->has_pending_report( $id ) ); + + // Suspension ends with the push: the next change by a person is reported. + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'draft', + ) + ); + $this->assertTrue( $this->has_pending_report( $id ) ); + } + + /** + * @return void + */ + public function test_a_push_that_throws_still_resumes_the_reporter() { + $this->report_status_changes(); + $id = $this->push( array( 'source' => 'citecue_autofix:optp_1' ) )->get_data()['post_id']; + + add_filter( + 'citecue_ingest_postarr', + static function () { + throw new RuntimeException( 'boom' ); + } + ); + try { + $this->push( array( 'source' => 'citecue_autofix:optp_1' ), array( 'timestamp' => time() + 1 ) ); + } catch ( RuntimeException $e ) { + unset( $e ); + } + + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + $this->assertTrue( $this->has_pending_report( $id ) ); + } + + /** + * A push replaces the text and the status, so whatever was waiting to be + * reported is stale and what was last reported is the pushed state. + * + * @return void + */ + public function test_a_successful_push_clears_the_pending_report_and_resets_what_was_reported() { + $this->report_status_changes(); + $id = $this->push( array( 'source' => 'citecue_autofix:optp_1' ) )->get_data()['post_id']; + $this->plugin->reporter->mark( $id ); + update_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, 2 ); + update_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, time() + 900 ); + update_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, '1' ); + + $response = $this->push( array( 'source' => 'citecue_autofix:optp_1' ), array( 'timestamp' => time() + 1 ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertFalse( $this->has_pending_report( $id ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, true ) ); + $this->assertSame( '0', get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, true ) ); + $this->assertSame( get_permalink( $id ), get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ) ); + } + + /** + * A push that is refused changes nothing, so what was waiting still is. + * + * @return void + */ + public function test_a_refused_push_leaves_the_pending_report_alone() { + $this->report_status_changes(); + $id = $this->push( array( 'source' => 'citecue_autofix:optp_1' ) )->get_data()['post_id']; + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Rewritten by the site owner.

', + ) + ); + update_post_meta( $id, Citecue_Status_Reporter::META_PENDING, 12345 ); + update_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, 2 ); + update_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, '1' ); + + $response = $this->push( array( 'source' => 'citecue_autofix:optp_1' ), array( 'timestamp' => time() + 1 ) ); + + $this->assertSame( 409, $response->get_status() ); + $this->assertSame( '12345', get_post_meta( $id, Citecue_Status_Reporter::META_PENDING, true ) ); + $this->assertSame( '2', get_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertSame( '1', get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, true ) ); + } + + /** + * Each push resets CiteCue's baseline for the post, so the response says + * where the post's report counter stands. + * + * @return void + */ + public function test_the_response_carries_the_current_report_sequence() { + $first = $this->push( array( 'source' => 'citecue_autofix:optp_1' ) ); + $this->assertSame( 0, $first->get_data()['seq'], 'A post that has never reported starts at 0.' ); + + $id = $first->get_data()['post_id']; + update_post_meta( $id, Citecue_Status_Reporter::META_SEQ, 7 ); + + $second = $this->push( array( 'source' => 'citecue_autofix:optp_1' ), array( 'timestamp' => time() + 1 ) ); + + $this->assertSame( 7, $second->get_data()['seq'] ); + $this->assertSame( 7, $this->plugin->reporter->current_seq( $id ), 'A push does not take a number.' ); + } + /** * An unchanged post is not an edited one — pushes must keep flowing. * diff --git a/tests/cases/test-ingest-products.php b/tests/cases/test-ingest-products.php index 9d860d3..4aa0acf 100644 --- a/tests/cases/test-ingest-products.php +++ b/tests/cases/test-ingest-products.php @@ -69,6 +69,27 @@ public function test_a_product_push_creates_a_draft_simple_product() { $this->assertSame( 'A good widget.', $product->get_short_description() ); } + /** + * Products are never reported, so their push carries no status counter and + * leaves no reporter bookkeeping. + * + * @return void + */ + public function test_a_product_push_carries_no_report_counter_and_no_bookkeeping() { + $response = $this->push( + array( + 'type' => 'product', + 'title' => 'Acme Widget', + ) + ); + + $this->assertArrayNotHasKey( 'seq', $response->get_data() ); + $meta = get_post_meta( $response->get_data()['post_id'] ); + foreach ( array_keys( $meta ) as $key ) { + $this->assertStringStartsNotWith( '_citecue_report', $key ); + } + } + /** * @return void */ diff --git a/tests/cases/test-status-reporter.php b/tests/cases/test-status-reporter.php new file mode 100644 index 0000000..981db2c --- /dev/null +++ b/tests/cases/test-status-reporter.php @@ -0,0 +1,2225 @@ +set_permalink_structure( '/%postname%/' ); + + $this->plugin->settings->update( + array( + 'api_key' => self::API_KEY, + 'public_key' => self::PUBLIC_KEY, + 'ingest_enabled' => true, + ) + ); + + $this->now = self::T0; + $this->spawns = 0; + $this->reporter = $this->plugin->reporter; + $this->reporter->set_clock( + function () { + return $this->now; + } + ); + $this->reporter->set_spawner( + function () { + ++$this->spawns; + } + ); + } + + /** + * Puts the singleton reporter back to real time and real cron. + * + * @return void + */ + public function tear_down() { + $this->reporter->set_clock( null ); + $this->reporter->set_spawner( null ); + parent::tear_down(); + } + + /** + * A post CiteCue pushed. + * + * @param array $args wp_insert_post() overrides. + * @param string $suffix Distinguishes the external id. + * @return int + */ + private function make_post( array $args = array(), $suffix = '1' ) { + $id = self::factory()->post->create( + array_merge( + array( + 'post_status' => 'draft', + 'post_title' => 'Acme ' . $suffix, + 'post_content' => '

Original ' . $suffix . '

', + ), + $args + ) + ); + update_post_meta( $id, '_citecue_external_id', 'optp_' . $suffix ); + update_post_meta( $id, '_citecue_source', 'citecue_autofix:optp_' . $suffix ); + update_post_meta( $id, '_citecue_content_hash', md5( get_post( $id )->post_content ) ); + return $id; + } + + /** + * Queues a 2xx reply. + * + * @param string $result Result word. + * @param array $extra More reply fields. + * @return void + */ + private function reply_ok( $result = 'mirrored', array $extra = array() ) { + $this->http->queue( + 'content_status', + 200, + wp_json_encode( + array_merge( + array( + 'ok' => true, + 'result' => $result, + ), + $extra + ) + ) + ); + } + + /** + * The body of the nth request sent. + * + * @param int $index Request index. + * @return array + */ + private function sent( $index = 0 ) { + $requests = $this->http->requests( 'content_status' ); + return json_decode( $requests[ $index ]['args']['body'], true ); + } + + /** + * Whether a post has a pending mark. + * + * @param int $id Post ID. + * @return bool + */ + private function is_pending( $id ) { + wp_cache_delete( $id, 'post_meta' ); + return '' !== (string) get_post_meta( $id, Citecue_Status_Reporter::META_PENDING, true ); + } + + /** + * Marks a post and moves the clock on a second, so marks sort. + * + * @param int $id Post ID. + * @return void + */ + private function mark_and_tick( $id ) { + $this->reporter->mark( $id ); + ++$this->now; + } + + /** + * Advances the fake clock by a given amount on every request, so a test can + * spend the run's time budget without waiting. + * + * @param int $seconds Seconds each request takes. + * @return void + */ + private function each_request_takes( $seconds ) { + add_filter( + 'pre_http_request', + function ( $pre ) use ( $seconds ) { + $this->now += $seconds; + return $pre; + }, + 5 + ); + } + + /** + * Runs fn when a request goes out, i.e. while a report is in flight. + * + * @param callable $callback Callback. + * @return void + */ + private function during_the_request( $callback ) { + add_filter( + 'pre_http_request', + function ( $pre ) use ( $callback ) { + call_user_func( $callback ); + return $pre; + }, + 5 + ); + } + + // --------------------------------------------------------------------- + // Hooks: what marks a post. + // --------------------------------------------------------------------- + + /** + * @return void + */ + public function test_publishing_a_citecue_post_marks_it_and_schedules_the_drain() { + $id = $this->make_post(); + $this->assertFalse( $this->is_pending( $id ) ); + + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + + $this->assertTrue( $this->is_pending( $id ) ); + $this->assertSame( self::T0, (int) get_post_meta( $id, Citecue_Status_Reporter::META_PENDING, true ) ); + $this->assertSame( self::T0, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_trashing_restoring_and_other_status_changes_mark_the_post() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + + wp_trash_post( $id ); + $this->assertTrue( $this->is_pending( $id ) ); + } + + /** + * @return void + */ + public function test_a_post_without_both_metas_is_ignored() { + $only_id = self::factory()->post->create( array( 'post_status' => 'draft' ) ); + update_post_meta( $only_id, '_citecue_external_id', 'optp_x' ); + $plain = self::factory()->post->create( array( 'post_status' => 'draft' ) ); + + foreach ( array( $only_id, $plain ) as $id ) { + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + $this->assertFalse( $this->is_pending( $id ) ); + } + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * Revisions, attachments and other children never report. + * + * @return void + */ + public function test_other_post_types_are_ignored() { + $id = self::factory()->post->create( + array( + 'post_type' => 'attachment', + 'post_status' => 'inherit', + ) + ); + update_post_meta( $id, '_citecue_external_id', 'optp_a' ); + update_post_meta( $id, '_citecue_source', 'citecue_autofix:optp_a' ); + + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'private', + ) + ); + $this->assertFalse( $this->is_pending( $id ) ); + } + + /** + * Saving without changing status, text or address is not a change. + * + * @return void + */ + public function test_a_save_that_changes_nothing_marks_nothing() { + $id = $this->make_post(); + wp_update_post( + array( + 'ID' => $id, + 'post_title' => 'A new title', + ) + ); + $this->assertFalse( $this->is_pending( $id ) ); + } + + /** + * @return void + */ + public function test_nothing_is_marked_while_suspended_around_the_plugins_own_push() { + $id = $this->make_post(); + + $this->reporter->suspend(); + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + $this->reporter->resume(); + $this->assertFalse( $this->is_pending( $id ) ); + + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'draft', + ) + ); + $this->assertTrue( $this->is_pending( $id ) ); + } + + /** + * @return void + */ + public function test_nothing_is_marked_when_the_site_is_not_connected() { + $this->plugin->settings->update( + array( + 'api_key' => '', + 'api_key_clear' => 1, + ) + ); + $id = $this->make_post(); + + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + + $this->assertFalse( $this->is_pending( $id ) ); + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_nothing_is_marked_when_content_pushes_are_not_accepted() { + $this->plugin->settings->update( array( 'ingest_enabled' => false ) ); + $id = $this->make_post(); + + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + + $this->assertFalse( $this->is_pending( $id ) ); + } + + /** + * CiteCue would answer 400 to an http address, and the plugin refuses + * pushes there too, so nothing is marked or sent. + * + * @return void + */ + public function test_nothing_is_marked_or_sent_on_a_plain_http_site() { + $id = $this->make_post(); + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + $this->assertTrue( $this->is_pending( $id ) ); + + update_option( 'home', 'http://example.org' ); + + $other = $this->make_post( array(), '2' ); + wp_update_post( + array( + 'ID' => $other, + 'post_status' => 'publish', + ) + ); + $this->assertFalse( $this->is_pending( $other ) ); + + $this->reporter->drain(); + $this->assertSame( 0, $this->http->count( 'content_status' ) ); + } + + /** + * @return void + */ + public function test_marking_keeps_an_existing_marks_time_and_resets_the_retry_state() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + update_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, 3 ); + update_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, self::T0 + 1000 ); + update_post_meta( $id, Citecue_Status_Reporter::META_CAUGHT_UP, 1 ); + $generation = (int) get_post_meta( $id, Citecue_Status_Reporter::META_GENERATION, true ); + + $this->now += 500; + $this->reporter->mark( $id ); + + $this->assertSame( self::T0, (int) get_post_meta( $id, Citecue_Status_Reporter::META_PENDING, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_CAUGHT_UP, true ) ); + $this->assertSame( $generation + 1, (int) get_post_meta( $id, Citecue_Status_Reporter::META_GENERATION, true ) ); + } + + /** + * @return void + */ + public function test_marking_schedules_the_drain_now_and_spawns_cron() { + $id = $this->make_post(); + + $this->reporter->mark( $id ); + + $this->assertSame( self::T0, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + $this->assertSame( 1, $this->spawns ); + } + + /** + * WordPress ignores a second single event for a hook within ten minutes of + * an existing one, so a later-scheduled drain has to be moved, not added to. + * + * @return void + */ + public function test_marking_pulls_a_later_drain_forward() { + wp_schedule_single_event( self::T0 + 1800, Citecue_Status_Reporter::DRAIN_HOOK ); + $id = $this->make_post(); + + $this->reporter->mark( $id ); + + $this->assertSame( self::T0, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + $this->assertCount( + 1, + array_filter( + (array) _get_cron_array(), + static function ( $events ) { + return isset( $events[ Citecue_Status_Reporter::DRAIN_HOOK ] ); + } + ) + ); + $this->assertSame( 1, $this->spawns ); + } + + /** + * @return void + */ + public function test_the_sequence_is_allocated_atomically_and_counts_up_from_zero() { + $id = $this->make_post(); + + $this->assertSame( 0, $this->reporter->current_seq( $id ), 'A post pushed before 1.5.0 starts at 0.' ); + $this->assertSame( 1, $this->reporter->build( $id )['seq'] ); + $this->assertSame( 2, $this->reporter->build( $id )['seq'] ); + $this->assertSame( 2, $this->reporter->current_seq( $id ) ); + } + + /** + * Runs a competing write to a meta row just before each of the reporter's own + * UPDATEs of it, as a concurrent request would. + * + * @param string $key Meta key. + * @param int $times How many UPDATEs to beat (0 for all of them). + * @param int $only_post Only beat UPDATEs of this post's row (0 for any). + * @return void + */ + private function race_the_update( $key, $times = 0, $only_post = 0 ) { + global $wpdb; + $beaten = 0; + $busy = false; + add_filter( + 'query', + function ( $sql ) use ( $key, $times, $only_post, &$beaten, &$busy ) { + global $wpdb; + if ( $busy || 0 !== strpos( $sql, "UPDATE {$wpdb->postmeta} SET meta_value" ) || ! preg_match( '/WHERE meta_id = (\d+) /', $sql, $m ) ) { + return $sql; + } + $busy = true; + $hit = $wpdb->get_row( $wpdb->prepare( "SELECT meta_key, post_id FROM {$wpdb->postmeta} WHERE meta_id = %d", (int) $m[1] ), ARRAY_A ); + $busy = false; + if ( ! $hit || $hit['meta_key'] !== $key || ( $only_post && (int) $hit['post_id'] !== $only_post ) ) { + return $sql; + } + if ( $times > 0 && $beaten >= $times ) { + return $sql; + } + ++$beaten; + $busy = true; + $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = meta_value + 10 WHERE meta_id = %d", (int) $m[1] ) ); + $busy = false; + return $sql; + } + ); + } + + /** + * A competing request that wins the race forces a re-read, never a repeat. + * + * @return void + */ + public function test_a_sequence_beaten_to_the_update_is_re_read_and_retried() { + $id = $this->make_post(); + $this->assertSame( 1, $this->reporter->build( $id )['seq'] ); + $this->race_the_update( Citecue_Status_Reporter::META_SEQ, 1 ); + + $seq = $this->reporter->build( $id )['seq']; + + $this->assertSame( 12, $seq, 'Read 1, beaten to 11, re-read, took 12.' ); + $this->assertSame( 12, $this->reporter->current_seq( $id ) ); + } + + /** + * A sequence that can't be allocated sends nothing and keeps the mark. + * + * @return void + */ + public function test_a_sequence_that_cannot_be_allocated_sends_nothing_and_keeps_the_mark() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->race_the_update( Citecue_Status_Reporter::META_SEQ ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 0, $this->http->count( 'content_status' ) ); + $this->assertTrue( $this->is_pending( $id ) ); + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_a_generation_that_cannot_be_allocated_still_changes() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $before = (int) get_post_meta( $id, Citecue_Status_Reporter::META_GENERATION, true ); + $this->race_the_update( Citecue_Status_Reporter::META_GENERATION ); + + $this->reporter->mark( $id ); + + wp_cache_delete( $id, 'post_meta' ); + $this->assertNotSame( $before, (int) get_post_meta( $id, Citecue_Status_Reporter::META_GENERATION, true ) ); + } + + // --------------------------------------------------------------------- + // Review round: replies, outages, stuck entries, fences. + // --------------------------------------------------------------------- + + /** + * @return array + */ + public function provide_unusable_success_bodies() { + return array( + 'html from a WAF' => array( 200, 'Just a moment...' ), + 'empty body' => array( 204, '' ), + 'ok is false' => array( 200, '{"ok":false,"result":"mirrored"}' ), + 'no result' => array( 200, '{"ok":true}' ), + 'an unknown result' => array( 200, '{"ok":true,"result":"banana"}' ), + ); + } + + /** + * A 2xx that is not CiteCue's reply is a failure to retry, not "applied". + * + * @dataProvider provide_unusable_success_bodies + * + * @param int $status HTTP status. + * @param string $body Body. + * @return void + */ + public function test_a_success_that_is_not_a_citecue_reply_is_retried( $status, $body ) { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->mark( $id ); + $this->http->queue( 'content_status', $status, $body ); + + $this->reporter->drain(); + + $this->assertTrue( $this->is_pending( $id ), 'The mark is kept.' ); + $this->assertSame( 1, (int) get_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ), 'Nothing is recorded as reported.' ); + } + + /** + * @return void + */ + public function test_an_outage_reply_holds_back_the_whole_site_not_just_its_post() { + $first = $this->make_post( array(), '1' ); + $second = $this->make_post( array(), '2' ); + $this->mark_and_tick( $first ); + $this->mark_and_tick( $second ); + $this->http->queue( 'content_status', 503, '{"error":"disabled"}', array( 'Retry-After' => '600' ) ); + + $until = $this->now + 600; + + $this->reporter->drain(); + $this->assertSame( 1, $this->http->count( 'content_status' ) ); + $this->assertSame( $until, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + + $this->now += 100; + $this->reporter->drain(); + + $this->assertSame( 1, $this->http->count( 'content_status' ), 'The second post is not tried into the same outage.' ); + $this->assertSame( $until, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_a_mark_on_a_post_that_is_gone_is_purged_and_schedules_nothing() { + update_post_meta( 999999, Citecue_Status_Reporter::META_PENDING, self::T0 ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->reporter->drain(); + + $this->assertSame( 0, $this->http->count( 'content_status' ) ); + $this->assertSame( '', (string) get_post_meta( 999999, Citecue_Status_Reporter::META_PENDING, true ) ); + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_a_mark_on_a_post_that_is_no_longer_tracked_is_purged() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + delete_post_meta( $id, '_citecue_source' ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->reporter->drain(); + + $this->assertFalse( $this->is_pending( $id ) ); + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_a_delete_option_that_is_not_a_report_is_purged_and_schedules_nothing() { + add_option( 'citecue_deleted_report_77', 'garbage', '', 'no' ); + add_option( 'citecue_deleted_report_78', array( 'pending' => self::T0 ), '', 'no' ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->reporter->drain(); + + $this->assertFalse( get_option( 'citecue_deleted_report_77' ) ); + $this->assertFalse( get_option( 'citecue_deleted_report_78' ) ); + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * A stored report missing its bookkeeping keys is still sent, without notices. + * + * @return void + */ + public function test_a_delete_option_without_bookkeeping_keys_is_still_sent() { + $id = $this->make_post(); + wp_delete_post( $id, true ); + $name = 'citecue_deleted_report_' . $id; + $stored = get_option( $name ); + update_option( $name, array( 'report' => $stored['report'] ), false ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 1, $this->http->count( 'content_status' ) ); + $this->assertFalse( get_option( $name ) ); + } + + /** + * @return void + */ + public function test_catching_up_never_lowers_a_counter_that_moved_on() { + $id = $this->make_post(); + $this->reporter->build( $id ); + $this->race_the_update( Citecue_Status_Reporter::META_SEQ, 1 ); + + $catch_up = new ReflectionMethod( $this->reporter, 'catch_up' ); + $catch_up->setAccessible( true ); + $catch_up->invoke( + $this->reporter, + array( + 'kind' => 'post', + 'id' => $id, + 'gen' => 0, + ), + 5 + ); + + $this->assertSame( 11, $this->reporter->current_seq( $id ), 'Beaten to 11, re-read, 11 is already past 5.' ); + } + + /** + * @return void + */ + public function test_a_report_for_an_entry_that_changed_meanwhile_does_not_record_what_it_sent() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->mark( $id ); + $this->during_the_request( + function () use ( $id ) { + $this->reporter->mark( $id ); + } + ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, true ) ); + } + + /** + * A change landing between the generation check and the delete is re-marked. + * + * @return void + */ + public function test_a_change_between_the_check_and_the_clear_is_not_lost() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $fired = false; + add_action( + 'delete_post_meta', + function ( $meta_ids, $post_id, $key ) use ( $id, &$fired ) { + if ( ! $fired && (int) $post_id === $id && Citecue_Status_Reporter::META_PENDING === $key ) { + $fired = true; + // A concurrent request's mark, landing just before our delete. + update_post_meta( $id, Citecue_Status_Reporter::META_GENERATION, 9 ); + } + }, + 10, + 3 + ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertTrue( $fired ); + $this->assertTrue( $this->is_pending( $id ), 'The newer change is re-marked.' ); + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * A mark that read the pending meta just before a finishing drain cleared + * it must still leave its change queued: the drain's second generation + * check has already passed by the time the mark bumps the generation. + * + * @return void + */ + public function test_a_mark_racing_a_finishing_drain_is_not_lost() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + wp_cache_delete( $id, 'post_meta' ); + $captured_gen = (int) get_post_meta( $id, Citecue_Status_Reporter::META_GENERATION, true ); + + $finish = new ReflectionMethod( Citecue_Status_Reporter::class, 'finish_entry' ); + $finish->setAccessible( true ); + $reporter = $this->reporter; + $fired = false; + $filter = function ( $value, $object_id, $key, $single ) use ( $id, $captured_gen, $finish, $reporter, &$fired, &$filter ) { + if ( $fired || (int) $object_id !== $id || Citecue_Status_Reporter::META_PENDING !== $key ) { + return $value; + } + $fired = true; + remove_filter( 'get_post_metadata', $filter, 10 ); + // The mark reads the pending meta... + wp_cache_delete( $id, 'post_meta' ); + $read = get_post_meta( $id, $key, $single ); + // ...then a drain whose report was captured before this change + // finishes, before the mark carries on. + $finish->invoke( + $reporter, + array( + 'kind' => 'post', + 'id' => $id, + 'gen' => $captured_gen, + ) + ); + return $single ? array( $read ) : $read; + }; + add_filter( 'get_post_metadata', $filter, 10, 4 ); + + $this->reporter->mark( $id ); + + $this->assertTrue( $fired ); + $this->assertTrue( $this->is_pending( $id ), 'The newer change is still queued.' ); + } + + /** + * @return void + */ + public function test_a_run_leaves_room_for_the_last_request_inside_the_budget() { + $ids = array(); + for ( $i = 1; $i <= 4; $i++ ) { + $ids[ $i ] = $this->make_post( array(), (string) $i ); + $this->mark_and_tick( $ids[ $i ] ); + } + $this->each_request_takes( 13 ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 2, $this->http->count( 'content_status' ), '26 s in, a 5 s request could end past 30 s: not started.' ); + } + + /** + * One entry that can't get a sequence is backed off and the run goes on. + * + * @return void + */ + public function test_an_entry_without_a_sequence_is_backed_off_and_the_run_goes_on() { + $stuck = $this->make_post( array(), 'stuck' ); + $fine = $this->make_post( array(), 'fine' ); + $this->mark_and_tick( $stuck ); + $this->mark_and_tick( $fine ); + $this->race_the_update( Citecue_Status_Reporter::META_SEQ, 0, $stuck ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 1, $this->http->count( 'content_status' ) ); + $this->assertSame( 'optp_fine', $this->sent()['external_id'] ); + $this->assertTrue( $this->is_pending( $stuck ) ); + $this->assertFalse( $this->is_pending( $fine ) ); + $this->assertSame( 1, (int) get_post_meta( $stuck, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertGreaterThan( $this->now, (int) get_post_meta( $stuck, Citecue_Status_Reporter::META_NOT_BEFORE, true ) ); + } + + /** + * A permanent delete has no second chance, so it is stored even when no + * sequence could be allocated, above the post's counter. + * + * @return void + */ + public function test_a_delete_is_stored_even_when_no_sequence_can_be_allocated() { + $id = $this->make_post(); + $this->reporter->build( $id ); + $this->reporter->build( $id ); + $this->race_the_update( Citecue_Status_Reporter::META_SEQ, 0, $id ); + + wp_delete_post( $id, true ); + + $stored = get_option( 'citecue_deleted_report_' . $id ); + $this->assertIsArray( $stored ); + $this->assertSame( 'deleted', $stored['report']['status'] ); + $this->assertGreaterThan( 2, $stored['report']['seq'] ); + } + + /** + * A duplicate meta row can't make the swap match twice. + * + * @return void + */ + public function test_a_duplicate_counter_row_does_not_break_the_allocation() { + $id = $this->make_post(); + $this->assertSame( 1, $this->reporter->build( $id )['seq'] ); + add_post_meta( $id, Citecue_Status_Reporter::META_SEQ, 1 ); + + $this->assertSame( 2, $this->reporter->build( $id )['seq'] ); + $this->assertSame( 3, $this->reporter->build( $id )['seq'] ); + } + + /** + * The given-up record fades after thirty days. + * + * @return void + */ + public function test_the_given_up_record_expires_after_thirty_days() { + update_option( + Citecue_Status_Reporter::GIVEN_UP_OPTION, + array( + 'count' => 2, + 'last' => time() - 31 * DAY_IN_SECONDS, + ), + false + ); + $this->assertSame( 0, Citecue_Status_Reporter::given_up()['count'] ); + + update_option( + Citecue_Status_Reporter::GIVEN_UP_OPTION, + array( + 'count' => 2, + 'last' => time() - 5 * DAY_IN_SECONDS, + ), + false + ); + $this->assertSame( 2, Citecue_Status_Reporter::given_up()['count'] ); + } + + // --------------------------------------------------------------------- + // The report itself. + // --------------------------------------------------------------------- + + /** + * @dataProvider provide_status_normalization + * + * @param string $wordpress WordPress status. + * @param string $reported What CiteCue is told. + * @return void + */ + public function test_statuses_are_normalized( $wordpress, $reported ) { + register_post_status( 'editorial_review', array( 'public' => false ) ); + + $this->assertSame( $reported, Citecue_Status_Reporter::normalize_status( $wordpress ) ); + } + + /** + * WordPress status to reported status. + * + * @return array + */ + public function provide_status_normalization() { + return array( + 'publish' => array( 'publish', 'publish' ), + 'draft' => array( 'draft', 'draft' ), + 'pending' => array( 'pending', 'draft' ), + 'private' => array( 'private', 'draft' ), + 'scheduled' => array( 'future', 'draft' ), + 'trash' => array( 'trash', 'trash' ), + 'custom editorial' => array( 'editorial_review', 'draft' ), + 'unregistered status' => array( 'whatever', 'draft' ), + ); + } + + /** + * @return void + */ + public function test_a_published_report_carries_the_address_and_the_edited_flag() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + + $report = $this->reporter->build( $id ); + + $this->assertSame( + array( 'external_id', 'source', 'site_url', 'post_id', 'status', 'permalink', 'edited', 'seq', 'observed_at' ), + array_keys( $report ) + ); + $this->assertSame( 'optp_1', $report['external_id'] ); + $this->assertSame( 'citecue_autofix:optp_1', $report['source'] ); + $this->assertSame( 'https://example.org/', $report['site_url'] ); + $this->assertSame( $id, $report['post_id'] ); + $this->assertSame( 'publish', $report['status'] ); + $this->assertSame( get_permalink( $id ), $report['permalink'] ); + $this->assertFalse( $report['edited'] ); + $this->assertSame( self::T0, $report['observed_at'] ); + } + + /** + * @return void + */ + public function test_only_a_published_report_carries_a_permalink() { + $id = $this->make_post( array( 'post_status' => 'private' ) ); + + $report = $this->reporter->build( $id ); + + $this->assertSame( 'draft', $report['status'] ); + $this->assertArrayNotHasKey( 'permalink', $report ); + } + + /** + * The same hash test as the content endpoint's edited_locally(). + * + * @return void + */ + public function test_edited_follows_the_content_hash() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->suspend(); + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Changed by a person

', + ) + ); + $this->reporter->resume(); + + $this->assertTrue( $this->reporter->build( $id )['edited'] ); + + delete_post_meta( $id, '_citecue_content_hash' ); + $this->assertFalse( $this->reporter->build( $id )['edited'], 'No stored hash means never pushed by this plugin: not edited.' ); + } + + // --------------------------------------------------------------------- + // Permanent deletes. + // --------------------------------------------------------------------- + + /** + * @return void + */ + public function test_a_permanent_delete_stores_its_own_option_and_the_drain_sends_it() { + global $wpdb; + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->after_push( $id ); + + wp_delete_post( $id, true ); + + $name = 'citecue_deleted_report_' . $id; + $this->assertIsArray( get_option( $name ) ); + $this->assertContains( $wpdb->get_var( $wpdb->prepare( "SELECT autoload FROM {$wpdb->options} WHERE option_name = %s", $name ) ), array( 'no', 'off' ), 'Not autoloaded.' ); + $this->assertSame( self::T0, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + + $this->reply_ok(); + $this->reporter->drain(); + + $body = $this->sent(); + $this->assertSame( 'deleted', $body['status'] ); + $this->assertSame( $id, $body['post_id'] ); + $this->assertSame( 'optp_1', $body['external_id'] ); + $this->assertArrayNotHasKey( 'edited', $body ); + $this->assertArrayNotHasKey( 'permalink', $body ); + $this->assertSame( 1, $body['seq'] ); + $this->assertFalse( get_option( $name ), 'A sent delete report is removed.' ); + } + + /** + * @return void + */ + public function test_a_delete_of_a_post_that_is_not_a_citecue_post_stores_nothing() { + global $wpdb; + $id = self::factory()->post->create(); + + wp_delete_post( $id, true ); + + $this->assertSame( '0', (string) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE 'citecue\\_deleted\\_report\\_%'" ) ); + } + + /** + * @return void + */ + public function test_a_failed_delete_report_backs_off_and_is_sent_again() { + $id = $this->make_post(); + wp_delete_post( $id, true ); + $name = 'citecue_deleted_report_' . $id; + + $this->http->queue( 'content_status', 500, '{}' ); + $this->reply_ok(); + $this->reporter->drain(); + $stored = get_option( $name ); + $this->assertSame( 1, $stored['attempts'] ); + $this->assertGreaterThanOrEqual( self::T0 + 60, $stored['not_before'] ); + + $this->reporter->drain(); + $this->assertSame( 1, $this->http->count( 'content_status' ), 'Not due yet.' ); + + $this->now = $stored['not_before']; + $this->reporter->drain(); + $this->assertSame( 2, $this->http->count( 'content_status' ) ); + $this->assertFalse( get_option( $name ) ); + } + + // --------------------------------------------------------------------- + // The drain. + // --------------------------------------------------------------------- + + /** + * The default query leaves trashed posts out; the queue must not. + * + * @return void + */ + public function test_the_drain_finds_trashed_posts() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + wp_trash_post( $id ); + $this->assertSame( 'trash', get_post_status( $id ) ); + + $this->reply_ok(); + $this->reporter->drain(); + + $this->assertSame( 1, $this->http->count( 'content_status' ) ); + $this->assertSame( 'trash', $this->sent()['status'] ); + $this->assertFalse( $this->is_pending( $id ) ); + } + + /** + * @return void + */ + public function test_the_request_is_authenticated_and_does_not_follow_redirects() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->reply_ok(); + + $this->reporter->drain(); + + $request = $this->http->last( 'content_status' ); + $this->assertSame( 'https://app.citecue.com/api/delivery/v2/content-status', $request['url'] ); + $this->assertSame( 'Bearer ' . self::API_KEY, $request['args']['headers']['Authorization'] ); + $this->assertSame( 'wordpress', $request['args']['headers']['X-Citecue-Channel'] ); // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText -- the channel name on the wire. + $this->assertSame( 0, $request['args']['redirection'] ); + $this->assertSame( 5, $request['args']['timeout'] ); + $this->assertSame( 'POST', $request['args']['method'] ); + } + + /** + * What is sent is the post as it is when the run happens, not as it was when + * it was marked. + * + * @return void + */ + public function test_a_report_is_built_at_send_time() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + + $this->reporter->suspend(); + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + $this->reporter->resume(); + + $this->reply_ok(); + $this->reporter->drain(); + + $this->assertSame( 'publish', $this->sent()['status'] ); + $this->assertSame( get_permalink( $id ), $this->sent()['permalink'] ); + } + + /** + * Writes what a CiteCue push in another PHP process leaves behind: the rows + * change, this process's cached copies don't. + * + * @param int $id Post ID. + * @param int $category Category to move the post to, or 0 to leave it. + * @return int The counter the push returned to CiteCue as its baseline. + */ + private function push_from_another_process( $id, $category = 0 ) { + global $wpdb; + + $content = '

Pushed again

'; + $wpdb->update( + $wpdb->posts, + array( + 'post_status' => 'publish', + 'post_name' => 'pushed-again', + 'post_content' => $content, + ), + array( 'ID' => $id ) + ); + $wpdb->update( + $wpdb->postmeta, + array( 'meta_value' => md5( $content ) ), + array( + 'post_id' => $id, + 'meta_key' => '_citecue_content_hash', + ) + ); + if ( $category ) { + $wpdb->delete( $wpdb->term_relationships, array( 'object_id' => $id ) ); + $wpdb->insert( + $wpdb->term_relationships, + array( + 'object_id' => $id, + 'term_taxonomy_id' => get_term( $category )->term_taxonomy_id, + ) + ); + } + $wpdb->delete( + $wpdb->postmeta, + array( + 'post_id' => $id, + 'meta_key' => Citecue_Status_Reporter::META_PENDING, + ) + ); + + return (int) $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s", $id, Citecue_Status_Reporter::META_SEQ ) ); + } + + /** + * A run loads its posts up front. One that CiteCue pushes while an earlier + * report is in flight gets a number above the push's baseline, so CiteCue + * would believe an old copy. + * + * @return void + */ + public function test_a_post_pushed_during_the_run_is_reported_as_pushed() { + $this->set_permalink_structure( '/%category%/%postname%/' ); + $old = self::factory()->category->create( array( 'slug' => 'old-category' ) ); + $new = self::factory()->category->create( array( 'slug' => 'new-category' ) ); + $first = $this->make_post( array(), '1' ); + $second = $this->make_post( array( 'post_category' => array( $old ) ), '2' ); + $this->mark_and_tick( $first ); + $this->mark_and_tick( $second ); + get_the_category( $second ); + + $baseline = null; + $this->during_the_request( + function () use ( $second, $new, &$baseline ) { + if ( null === $baseline ) { + $baseline = $this->push_from_another_process( $second, $new ); + } + } + ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 2, $this->http->count( 'content_status' ) ); + $report = $this->sent( 1 ); + $this->assertGreaterThan( $baseline, $report['seq'], 'CiteCue will apply this report.' ); + $this->assertSame( 'publish', $report['status'] ); + $this->assertSame( 'https://example.org/new-category/pushed-again/', $report['permalink'] ); + $this->assertFalse( $report['edited'] ); + } + + /** + * The number is taken before the post is read: a push that lands just + * before it is in the report, and one that lands after it returns a baseline + * the report doesn't beat. + * + * @return void + */ + public function test_a_push_just_before_the_number_is_taken_is_in_the_report() { + $id = $this->make_post(); + $baseline = null; + $filter = function ( $sql ) use ( $id, &$baseline ) { + if ( null === $baseline && 0 === strpos( $sql, 'SELECT meta_id, meta_value' ) && false !== strpos( $sql, "'" . Citecue_Status_Reporter::META_SEQ . "'" ) ) { + $baseline = 0; + $baseline = $this->push_from_another_process( $id ); + } + return $sql; + }; + add_filter( 'query', $filter ); + $report = $this->reporter->build( $id ); + remove_filter( 'query', $filter ); + + $this->assertNotNull( $baseline, 'The push landed.' ); + $this->assertGreaterThan( $baseline, $report['seq'] ); + $this->assertSame( 'publish', $report['status'] ); + $this->assertFalse( $report['edited'] ); + } + + /** + * @return void + */ + public function test_a_run_sends_at_most_twenty_oldest_first_and_reschedules_for_the_rest() { + $ids = array(); + for ( $i = 1; $i <= 22; $i++ ) { + $ids[ $i ] = $this->make_post( array(), (string) $i ); + $this->mark_and_tick( $ids[ $i ] ); + } + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 20, $this->http->count( 'content_status' ) ); + $this->assertSame( 'optp_1', $this->sent( 0 )['external_id'] ); + $this->assertSame( 'optp_20', $this->sent( 19 )['external_id'] ); + $this->assertFalse( $this->is_pending( $ids[1] ) ); + $this->assertTrue( $this->is_pending( $ids[21] ) ); + $this->assertTrue( $this->is_pending( $ids[22] ) ); + $this->assertSame( $this->now + 60, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + + $this->now += 60; + $this->reporter->drain(); + $this->assertSame( 22, $this->http->count( 'content_status' ) ); + $this->assertFalse( $this->is_pending( $ids[22] ) ); + } + + /** + * @return void + */ + public function test_a_run_skips_posts_that_are_not_due_yet_without_counting_them() { + $waiting = $this->make_post( array(), 'waiting' ); + $this->mark_and_tick( $waiting ); + update_post_meta( $waiting, Citecue_Status_Reporter::META_NOT_BEFORE, $this->now + 500 ); + $due = $this->make_post( array(), 'due' ); + $this->mark_and_tick( $due ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 1, $this->http->count( 'content_status' ) ); + $this->assertSame( 'optp_due', $this->sent()['external_id'] ); + $this->assertTrue( $this->is_pending( $waiting ) ); + $this->assertSame( (int) get_post_meta( $waiting, Citecue_Status_Reporter::META_NOT_BEFORE, true ), wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_a_run_stops_after_thirty_seconds() { + $ids = array(); + for ( $i = 1; $i <= 4; $i++ ) { + $ids[ $i ] = $this->make_post( array(), (string) $i ); + $this->mark_and_tick( $ids[ $i ] ); + } + $this->each_request_takes( 20 ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 2, $this->http->count( 'content_status' ), '20 s and 40 s in: the third report is not started.' ); + $this->assertTrue( $this->is_pending( $ids[3] ) ); + $this->assertTrue( $this->is_pending( $ids[4] ) ); + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @dataProvider provide_run_stopping_failures + * + * @param int|string $failure A status, or 'timeout' / 'network'. + * @return void + */ + public function test_a_run_stops_at_the_first_failure_that_says_stop( $failure ) { + $first = $this->make_post( array(), '1' ); + $second = $this->make_post( array(), '2' ); + $this->mark_and_tick( $first ); + $this->mark_and_tick( $second ); + + if ( is_int( $failure ) ) { + $this->http->queue( 'content_status', $failure, '{}' ); + } else { + $this->http->queue_error( 'content_status', 'timeout' === $failure ? 'cURL error 28: Operation timed out' : 'Could not resolve host' ); + } + + $this->reporter->drain(); + + $this->assertSame( 1, $this->http->count( 'content_status' ) ); + $this->assertTrue( $this->is_pending( $first ), 'The failed report is kept.' ); + $this->assertTrue( $this->is_pending( $second ), 'The rest wait for the next run.' ); + $this->assertSame( 1, (int) get_post_meta( $first, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertSame( '', (string) get_post_meta( $second, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + } + + /** + * Failures that stop a run. + * + * @return array + */ + public function provide_run_stopping_failures() { + return array( + '401' => array( 401 ), + '403' => array( 403 ), + '408' => array( 408 ), + '429' => array( 429 ), + '500' => array( 500 ), + '502' => array( 502 ), + '503' => array( 503 ), + 'timeout' => array( 'timeout' ), + 'network' => array( 'network' ), + ); + } + + /** + * Busy is about that one post, so the run goes on. + * + * @return void + */ + public function test_a_busy_reply_defers_only_its_post() { + $first = $this->make_post( array(), '1' ); + $second = $this->make_post( array(), '2' ); + $this->mark_and_tick( $first ); + $this->mark_and_tick( $second ); + + $this->http->queue( 'content_status', 503, '{"error":"busy"}' ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 2, $this->http->count( 'content_status' ) ); + $this->assertTrue( $this->is_pending( $first ) ); + $this->assertSame( 1, (int) get_post_meta( $first, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertFalse( $this->is_pending( $second ) ); + } + + /** + * A report CiteCue refuses or doesn't recognize can't be fixed by retrying. + * + * @dataProvider provide_final_statuses + * + * @param int $status HTTP status. + * @return void + */ + public function test_a_400_or_404_clears_the_mark_and_the_run_goes_on( $status ) { + $first = $this->make_post( array(), '1' ); + $second = $this->make_post( array(), '2' ); + $this->mark_and_tick( $first ); + $this->mark_and_tick( $second ); + + $this->http->queue( 'content_status', $status, '{"error":"nope"}' ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertSame( 2, $this->http->count( 'content_status' ) ); + $this->assertFalse( $this->is_pending( $first ) ); + $this->assertFalse( $this->is_pending( $second ) ); + $this->assertSame( 0, Citecue_Status_Reporter::given_up()['count'] ); + } + + /** + * Statuses that end an entry without a retry. + * + * @return array + */ + public function provide_final_statuses() { + return array( + '400' => array( 400 ), + '404' => array( 404 ), + ); + } + + /** + * Retries at 1, 5, 15 and 30 minutes with up to 30% jitter; the fifth + * failure gives the report up and counts it. + * + * @return void + */ + public function test_retries_follow_the_schedule_and_the_fifth_failure_gives_up() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->http->queue( 'content_status', 500, '{}' ); + + foreach ( array( 60, 300, 900, 1800 ) as $attempt => $delay ) { + $this->reporter->drain(); + $not_before = (int) get_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, true ); + $this->assertSame( $attempt + 1, (int) get_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertGreaterThanOrEqual( $this->now + $delay, $not_before ); + $this->assertLessThanOrEqual( $this->now + (int) ceil( $delay * 1.3 ), $not_before ); + $this->now = $not_before; + } + + $this->assertSame( 0, Citecue_Status_Reporter::given_up()['count'] ); + + $this->reporter->drain(); + + $this->assertSame( 5, $this->http->count( 'content_status' ) ); + $this->assertFalse( $this->is_pending( $id ), 'After the fourth retry the report is dropped.' ); + $this->assertSame( + array( + 'count' => 1, + 'last' => $this->now, + ), + Citecue_Status_Reporter::given_up() + ); + } + + /** + * @dataProvider provide_retry_after + * + * @param string $header Retry-After header. + * @param int $expected Expected wait in seconds at least (and at most this plus jitter room). + * @param bool $exact Whether the wait is exactly this (the cap or a floor above the jitter). + * @return void + */ + public function test_retry_after_is_a_floor_capped_at_an_hour( $header, $expected, $exact ) { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->http->queue( 'content_status', 503, '{"error":"disabled"}', array( 'Retry-After' => $header ) ); + + $this->reporter->drain(); + + $wait = (int) get_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, true ) - $this->now; + if ( $exact ) { + $this->assertSame( $expected, $wait ); + } else { + $this->assertGreaterThanOrEqual( $expected, $wait ); + } + } + + /** + * Retry-After shapes. + * + * @return array + */ + public function provide_retry_after() { + return array( + 'seconds above the schedule' => array( '1800', 1800, true ), + 'capped at an hour' => array( '86400', 3600, true ), + 'below the schedule' => array( '5', 60, false ), + 'http date' => array( gmdate( 'D, d M Y H:i:s', self::T0 + 900 ) . ' GMT', 900, true ), + 'nonsense' => array( 'soon', 60, false ), + ); + } + + /** + * @return void + */ + public function test_the_next_run_is_scheduled_at_the_earliest_not_before_time() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->http->queue( 'content_status', 503, '{"error":"disabled"}', array( 'Retry-After' => '1800' ) ); + + $this->reporter->drain(); + + $this->assertSame( self::T0 + 1800, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * Nothing left means nothing scheduled. + * + * @return void + */ + public function test_nothing_is_scheduled_when_nothing_remains() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->reply_ok(); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->reporter->drain(); + + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * A change that lands while the report is on the wire is a different change + * from the one being sent, and must still be sent. + * + * @return void + */ + public function test_a_change_during_an_in_flight_report_survives_a_success() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->during_the_request( + function () use ( $id ) { + $this->reporter->mark( $id ); + } + ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertTrue( $this->is_pending( $id ) ); + } + + /** + * @return void + */ + public function test_a_change_during_an_in_flight_report_survives_a_failure() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->during_the_request( + function () use ( $id ) { + $this->reporter->mark( $id ); + } + ); + $this->http->queue( 'content_status', 500, '{}' ); + + $this->reporter->drain(); + + $this->assertTrue( $this->is_pending( $id ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, true ), 'The new change is not delayed by the old failure.' ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, true ) ); + } + + /** + * @return void + */ + public function test_a_failed_report_that_changed_meanwhile_is_not_given_up() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + update_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, 4 ); + $this->during_the_request( + function () use ( $id ) { + $this->reporter->mark( $id ); + } + ); + $this->http->queue( 'content_status', 500, '{}' ); + + $this->reporter->drain(); + + $this->assertTrue( $this->is_pending( $id ) ); + $this->assertSame( 0, Citecue_Status_Reporter::given_up()['count'] ); + } + + /** + * A new change is sent at the next run even when an older one was backing + * off. + * + * @return void + */ + public function test_a_new_change_clears_the_backoff() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->http->queue( 'content_status', 500, '{}' ); + $this->reply_ok(); + $this->reporter->drain(); + $this->assertNotSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, true ) ); + + wp_update_post( + array( + 'ID' => $id, + 'post_status' => 'publish', + ) + ); + + $this->reporter->drain(); + + $this->assertSame( 2, $this->http->count( 'content_status' ), 'Sent without waiting for the backoff.' ); + $this->assertFalse( $this->is_pending( $id ) ); + } + + // --------------------------------------------------------------------- + // What the reply changes. + // --------------------------------------------------------------------- + + /** + * @return void + */ + public function test_the_reported_values_are_stored_only_for_a_reply_that_is_not_ignored() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->mark( $id ); + $this->reply_ok( 'ignored', array( 'reason' => 'foreign_site' ) ); + $this->reply_ok( 'none' ); + + $this->reporter->drain(); + + $this->assertFalse( $this->is_pending( $id ), 'An ignored report is still finished.' ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ) ); + + $this->reporter->mark( $id ); + $this->reporter->drain(); + + $this->assertSame( '0', (string) get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, true ) ); + $this->assertSame( get_permalink( $id ), get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ) ); + } + + /** + * @return void + */ + public function test_a_post_that_went_out_of_sync_catches_its_counter_up_once() { + $id = $this->make_post(); + update_post_meta( $id, Citecue_Status_Reporter::META_SEQ, 3 ); + $this->reporter->mark( $id ); + $this->reply_ok( + 'ignored', + array( + 'reason' => 'out_of_order', + 'recorded_seq' => 10, + ) + ); + + $this->reporter->drain(); + + $this->assertSame( 4, $this->sent( 0 )['seq'] ); + $this->assertSame( 10, $this->reporter->current_seq( $id ) ); + $this->assertTrue( $this->is_pending( $id ), 'The entry is kept so the current state goes out again.' ); + + $this->now += 60; + $this->reporter->drain(); + + $this->assertSame( 11, $this->sent( 1 )['seq'] ); + + $this->assertFalse( $this->is_pending( $id ), 'Out of order again after catching up: once is all an entry gets.' ); + $this->assertSame( 2, $this->http->count( 'content_status' ) ); + } + + /** + * Out of order with a lower recorded_seq is just a report that lost a race. + * + * @return void + */ + public function test_out_of_order_without_a_higher_recorded_sequence_is_final() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->reply_ok( + 'ignored', + array( + 'reason' => 'out_of_order', + 'recorded_seq' => 0, + ) + ); + + $this->reporter->drain(); + + $this->assertFalse( $this->is_pending( $id ) ); + $this->assertSame( 1, $this->reporter->current_seq( $id ) ); + } + + /** + * @return void + */ + public function test_a_stored_delete_report_catches_up_once_too() { + $id = $this->make_post(); + wp_delete_post( $id, true ); + $name = 'citecue_deleted_report_' . $id; + $this->reply_ok( + 'ignored', + array( + 'reason' => 'out_of_order', + 'recorded_seq' => 10, + ) + ); + + $this->reporter->drain(); + + $stored = get_option( $name ); + $this->assertIsArray( $stored ); + $this->assertSame( 11, $stored['report']['seq'] ); + + $this->now += 60; + $this->reporter->drain(); + + $this->assertSame( 11, $this->sent( 1 )['seq'] ); + $this->assertFalse( get_option( $name ) ); + } + + // --------------------------------------------------------------------- + // post_updated and wp_after_insert_post: edits and new addresses. + // --------------------------------------------------------------------- + + /** + * @return void + */ + public function test_an_edit_of_a_live_post_is_reported_once() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->after_push( $id ); + + wp_update_post( + array( + 'ID' => $id, + 'post_title' => 'Only the title', + ) + ); + $this->assertFalse( $this->is_pending( $id ), 'The text is still what CiteCue sent.' ); + + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Edited by hand

', + ) + ); + $this->assertTrue( $this->is_pending( $id ) ); + + $this->reply_ok(); + $this->reporter->drain(); + $this->assertTrue( $this->sent()['edited'] ); + $this->assertSame( '1', get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, true ) ); + + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Edited by hand again

', + ) + ); + $this->assertFalse( $this->is_pending( $id ), 'Still edited, and CiteCue already knows.' ); + + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Original 1

', + ) + ); + $this->assertTrue( $this->is_pending( $id ), 'Back to the stored content: the line must clear.' ); + } + + /** + * @return void + */ + public function test_a_new_address_for_a_live_post_is_reported_once() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->after_push( $id ); + + wp_update_post( + array( + 'ID' => $id, + 'post_name' => 'a-new-slug', + ) + ); + $this->assertTrue( $this->is_pending( $id ) ); + + $this->reply_ok(); + $this->reporter->drain(); + $this->assertStringContainsString( 'a-new-slug', $this->sent()['permalink'] ); + + wp_update_post( + array( + 'ID' => $id, + 'post_title' => 'Another save', + ) + ); + $this->assertFalse( $this->is_pending( $id ) ); + } + + /** + * The block editor saves through REST, which writes the categories only + * after post_updated fired; with %category% in the permalinks, a new + * category alone is a new address. + * + * @return void + */ + public function test_a_new_category_saved_through_rest_is_a_new_address() { + $this->set_permalink_structure( '/%category%/%postname%/' ); + $old = self::factory()->category->create( array( 'slug' => 'old-cat' ) ); + $new = self::factory()->category->create( array( 'slug' => 'new-cat' ) ); + $id = $this->make_post( + array( + 'post_status' => 'publish', + 'post_category' => array( $old ), + ) + ); + $this->reporter->after_push( $id ); + $this->assertStringContainsString( 'old-cat', get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ) ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/posts/' . $id ); + $request->set_param( 'categories', array( $new ) ); + $response = rest_do_request( $request ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertTrue( $this->is_pending( $id ) ); + $this->reply_ok(); + $this->reporter->drain(); + $this->assertStringContainsString( 'new-cat', $this->sent()['permalink'] ); + } + + /** + * An edit undone while the report of the edit is in flight: the undo + * matches what was last acknowledged, but not what is being sent, so it + * must go out too. + * + * @return void + */ + public function test_an_edit_undone_while_its_report_is_in_flight_is_reported() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->after_push( $id ); + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Edited by hand

', + ) + ); + $fired = false; + $this->during_the_request( + function () use ( $id, &$fired ) { + if ( $fired ) { + return; + } + $fired = true; + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Original 1

', + ) + ); + } + ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertTrue( $this->sent()['edited'] ); + $this->assertTrue( $this->is_pending( $id ), 'The undo still has to reach CiteCue.' ); + $this->reply_ok(); + $this->now += HOUR_IN_SECONDS; + $this->reporter->drain(); + $this->assertFalse( $this->sent( 1 )['edited'] ); + } + + /** + * The same for an address changed back while the new one is in flight. + * + * @return void + */ + public function test_a_slug_changed_back_while_its_report_is_in_flight_is_reported() { + $id = $this->make_post( + array( + 'post_status' => 'publish', + 'post_name' => 'first-slug', + ) + ); + $this->reporter->after_push( $id ); + wp_update_post( + array( + 'ID' => $id, + 'post_name' => 'second-slug', + ) + ); + $fired = false; + $this->during_the_request( + function () use ( $id, &$fired ) { + if ( $fired ) { + return; + } + $fired = true; + wp_update_post( + array( + 'ID' => $id, + 'post_name' => 'first-slug', + ) + ); + } + ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertStringContainsString( 'second-slug', $this->sent()['permalink'] ); + $this->assertTrue( $this->is_pending( $id ), 'The old address is back and CiteCue must hear it.' ); + } + + /** + * A category changed back through REST while the new address is in + * flight: the post's own before-state can't show it (an address is built + * from the terms as they are now), so the in-flight report must not count. + * + * @return void + */ + public function test_a_category_changed_back_while_its_report_is_in_flight_is_reported() { + $this->set_permalink_structure( '/%category%/%postname%/' ); + $old = self::factory()->category->create( array( 'slug' => 'old-cat' ) ); + $new = self::factory()->category->create( array( 'slug' => 'new-cat' ) ); + $id = $this->make_post( + array( + 'post_status' => 'publish', + 'post_category' => array( $old ), + ) + ); + $this->reporter->after_push( $id ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + $save_categories = function ( $categories ) use ( $id ) { + $request = new WP_REST_Request( 'POST', '/wp/v2/posts/' . $id ); + $request->set_param( 'categories', $categories ); + return rest_do_request( $request )->get_status(); + }; + $this->assertSame( 200, $save_categories( array( $new ) ) ); + $fired = false; + $this->during_the_request( + function () use ( $old, $save_categories, &$fired ) { + if ( ! $fired ) { + $fired = true; + $save_categories( array( $old ) ); + } + } + ); + $this->reply_ok(); + + $this->reporter->drain(); + + $this->assertStringContainsString( 'new-cat', $this->sent()['permalink'] ); + $this->assertTrue( $this->is_pending( $id ), 'The old address is back and CiteCue must hear it.' ); + $this->reply_ok(); + $this->now += HOUR_IN_SECONDS; + $this->reporter->drain(); + $this->assertStringContainsString( 'old-cat', $this->sent( 1 )['permalink'] ); + } + + /** + * A REST save stores the text first; if a later step fails (a term, meta + * or extra field), wp_after_insert_post never fires, but the edit is + * saved and must still be reported. + * + * @return void + */ + public function test_an_edit_saved_through_rest_is_reported_even_when_a_later_step_fails() { + global $wp_rest_additional_fields; + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->after_push( $id ); + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + register_rest_field( + 'post', + 'citecue_test_failing_field', + array( + 'update_callback' => static function () { + return new WP_Error( 'citecue_test', 'This field never saves.' ); + }, + ) + ); + + try { + $request = new WP_REST_Request( 'POST', '/wp/v2/posts/' . $id ); + $request->set_param( 'content', '

Edited in the block editor

' ); + $request->set_param( 'citecue_test_failing_field', 'x' ); + $response = rest_do_request( $request ); + } finally { + unset( $wp_rest_additional_fields['post']['citecue_test_failing_field'] ); + } + + $this->assertTrue( $response->is_error(), 'The request failed after the text was stored.' ); + $this->assertStringContainsString( 'Edited in the block editor', get_post( $id )->post_content ); + $this->assertTrue( $this->is_pending( $id ) ); + } + + /** + * A draft's address isn't public, so editing a draft says nothing. + * + * @return void + */ + public function test_editing_a_draft_reports_nothing() { + $id = $this->make_post(); + + wp_update_post( + array( + 'ID' => $id, + 'post_content' => '

Edited draft

', + ) + ); + + $this->assertFalse( $this->is_pending( $id ) ); + } + + // --------------------------------------------------------------------- + // Bookkeeping around pushes, disconnects and uninstall. + // --------------------------------------------------------------------- + + /** + * @return void + */ + public function test_after_a_push_nothing_is_pending_and_the_reported_values_are_reset() { + $id = $this->make_post( array( 'post_status' => 'publish' ) ); + $this->reporter->mark( $id ); + update_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, 2 ); + update_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, self::T0 + 500 ); + update_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, '1' ); + + $this->reporter->after_push( $id ); + + $this->assertFalse( $this->is_pending( $id ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_ATTEMPTS, true ) ); + $this->assertSame( '', (string) get_post_meta( $id, Citecue_Status_Reporter::META_NOT_BEFORE, true ) ); + $this->assertSame( '0', get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_EDITED, true ) ); + $this->assertSame( get_permalink( $id ), get_post_meta( $id, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ) ); + } + + /** + * A reconnect may pair a different project, so the old one's reports must + * not follow it. + * + * @return void + */ + public function test_disconnecting_clears_pending_marks_and_delete_reports() { + $pending = $this->make_post( array(), '1' ); + $this->reporter->mark( $pending ); + $deleted = $this->make_post( array(), '2' ); + wp_delete_post( $deleted, true ); + update_option( + Citecue_Status_Reporter::GIVEN_UP_OPTION, + array( + 'count' => 2, + 'last' => self::T0, + ), + false + ); + + $this->plugin->connect->disconnect(); + + $this->assertFalse( $this->is_pending( $pending ) ); + $this->assertFalse( get_option( 'citecue_deleted_report_' . $deleted ) ); + $this->assertSame( 0, Citecue_Status_Reporter::given_up()['count'] ); + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_deactivating_clears_the_drain_event() { + $this->reporter->mark( $this->make_post() ); + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + + Citecue_Plugin::deactivate(); + + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * Uninstall removes the plugin's bookkeeping and leaves the posts. + * + * @return void + */ + public function test_uninstall_removes_report_options_and_meta_but_keeps_the_posts() { + $kept = $this->make_post( array( 'post_status' => 'publish' ), '1' ); + $this->reporter->mark( $kept ); + $this->reporter->after_push( $kept ); + $this->reporter->build( $kept ); + $deleted = $this->make_post( array(), '2' ); + wp_delete_post( $deleted, true ); + update_option( + Citecue_Status_Reporter::GIVEN_UP_OPTION, + array( + 'count' => 1, + 'last' => self::T0, + ), + false + ); + + update_option( Citecue_Status_Reporter::SITE_NOT_BEFORE, self::T0, false ); + + if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) { + define( 'WP_UNINSTALL_PLUGIN', 'citecue-ai-auto-fix/citecue.php' ); + } + require dirname( __DIR__, 2 ) . '/uninstall.php'; + + $this->assertFalse( get_option( 'citecue_deleted_report_' . $deleted ) ); + $this->assertFalse( get_option( Citecue_Status_Reporter::GIVEN_UP_OPTION ) ); + $this->assertFalse( get_option( Citecue_Status_Reporter::SITE_NOT_BEFORE ) ); + wp_cache_flush(); + $this->assertSame( '', (string) get_post_meta( $kept, Citecue_Status_Reporter::META_SEQ, true ) ); + $this->assertSame( '', (string) get_post_meta( $kept, Citecue_Status_Reporter::META_REPORTED_PERMALINK, true ) ); + $this->assertSame( '', (string) get_post_meta( $kept, Citecue_Status_Reporter::META_GENERATION, true ) ); + $this->assertSame( 'optp_1', get_post_meta( $kept, '_citecue_external_id', true ), 'The post and its identity stay.' ); + $this->assertSame( 'publish', get_post_status( $kept ) ); + } + + // --------------------------------------------------------------------- + // Re-arming the drain. + // --------------------------------------------------------------------- + + /** + * @return void + */ + public function test_reactivating_schedules_the_drain_for_marks_still_pending() { + $this->reporter->mark( $this->make_post() ); + Citecue_Plugin::deactivate(); + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + + Citecue_Plugin::activate(); + + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_the_daily_sync_re_arms_the_drain_only_when_something_is_pending() { + $this->http->queue_error( 'crawlers' ); + $this->http->queue_error( 'config' ); + $this->plugin->daily_sync(); + $this->assertFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ), 'Nothing pending: nothing scheduled.' ); + + $id = $this->make_post(); + $this->reporter->mark( $id ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + $this->plugin->daily_sync(); + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_a_stored_delete_report_alone_re_arms_the_drain() { + $id = $this->make_post(); + wp_delete_post( $id, true ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->reporter->ensure_drain_scheduled(); + + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_ensuring_the_drain_leaves_an_existing_event_alone() { + $this->reporter->mark( $this->make_post() ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + wp_schedule_single_event( self::T0 + 900, Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->reporter->ensure_drain_scheduled(); + + $this->assertSame( self::T0 + 900, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_switching_content_pushes_on_re_arms_the_drain() { + $this->reporter->mark( $this->make_post() ); + $this->plugin->settings->update( array( 'ingest_enabled' => false ) ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->plugin->settings->update( array( 'ingest_enabled' => true ) ); + + $this->assertNotFalse( wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * A drain that ran while pushes were off left its retry a day out; turning + * pushes back on must not wait for it. + * + * @return void + */ + public function test_switching_content_pushes_on_pulls_a_day_later_drain_forward() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->plugin->settings->update( array( 'ingest_enabled' => false ) ); + // WP-Cron takes the event off the schedule before it runs the drain. + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + $this->reporter->drain(); + $this->assertSame( self::T0 + DAY_IN_SECONDS, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + + $this->plugin->settings->update( array( 'ingest_enabled' => true ) ); + + $this->assertSame( self::T0, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * @return void + */ + public function test_a_drain_while_reporting_is_off_keeps_the_marks_and_retries_later() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->plugin->settings->update( array( 'ingest_enabled' => false ) ); + wp_clear_scheduled_hook( Citecue_Status_Reporter::DRAIN_HOOK ); + + $this->reporter->drain(); + + $this->assertSame( 0, $this->http->count( 'content_status' ) ); + $this->assertTrue( $this->is_pending( $id ) ); + $this->assertSame( self::T0 + DAY_IN_SECONDS, wp_next_scheduled( Citecue_Status_Reporter::DRAIN_HOOK ) ); + } + + /** + * The drain does nothing once the site is no longer connected. + * + * @return void + */ + public function test_the_drain_sends_nothing_when_not_connected() { + $id = $this->make_post(); + $this->reporter->mark( $id ); + $this->plugin->settings->update( + array( + 'api_key' => '', + 'api_key_clear' => 1, + ) + ); + + $this->reporter->drain(); + + $this->assertSame( 0, $this->http->count( 'content_status' ) ); + } +} diff --git a/tests/includes/class-citecue-http-mock.php b/tests/includes/class-citecue-http-mock.php index 9c3a3a8..9df4d53 100644 --- a/tests/includes/class-citecue-http-mock.php +++ b/tests/includes/class-citecue-http-mock.php @@ -68,7 +68,7 @@ public function disable() { /** * Queues a response for an endpoint. * - * @param string $endpoint One of page|seo_head|llms|config|crawlers. + * @param string $endpoint One of page|seo_head|llms|config|crawlers|content_status. * @param int $status HTTP status code. * @param string $body Response body. * @param array $headers Response headers (case-insensitive). @@ -86,7 +86,7 @@ public function queue( $endpoint, $status, $body = '', array $headers = array() /** * Queues a transport failure (timeout, DNS error, refused connection). * - * @param string $endpoint One of page|seo_head|llms|config|crawlers. + * @param string $endpoint One of page|seo_head|llms|config|crawlers|content_status. * @param string $message Error message. * @return $this */ @@ -190,6 +190,9 @@ private static function classify( $url ) { if ( false !== strpos( $url, '/api/delivery/v2/connect/claim' ) ) { return 'connect'; } + if ( false !== strpos( $url, '/api/delivery/v2/content-status' ) ) { + return 'content_status'; + } if ( false !== strpos( $url, '/api/delivery/v2/seo-head' ) ) { return 'seo_head'; } @@ -224,6 +227,10 @@ private static function headers( array $headers ) { if ( class_exists( '\WpOrg\Requests\Utility\CaseInsensitiveDictionary' ) ) { return new \WpOrg\Requests\Utility\CaseInsensitiveDictionary( $headers ); } + // WordPress before 6.2. + if ( class_exists( 'Requests_Utility_CaseInsensitiveDictionary' ) ) { + return new Requests_Utility_CaseInsensitiveDictionary( $headers ); + } return $headers; } } diff --git a/uninstall.php b/uninstall.php index e0bc0e3..451dd52 100644 --- a/uninstall.php +++ b/uninstall.php @@ -19,6 +19,8 @@ delete_option( 'citecue_projects_cache' ); delete_option( 'citecue_last_config_at' ); delete_option( 'citecue_install_verified' ); +delete_option( 'citecue_report_given_up' ); +delete_option( 'citecue_report_not_before' ); /* * One row per administrator who dismissed the reconnect notice, stored through @@ -53,6 +55,24 @@ unset( $citecue_dismissal_key, $citecue_site_ids, $citecue_site_id ); +/* + * Status reports: one option per permanently deleted post still waiting to be + * reported, and the per-post marks and last-reported values on the posts CiteCue + * pushed. The posts themselves stay (see above); only the plugin's bookkeeping + * goes. + */ +// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching +$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( 'citecue_deleted_report_' ) . '%' ) ); +$wpdb->query( + $wpdb->prepare( + "DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s OR meta_key LIKE %s", + $wpdb->esc_like( '_citecue_report_' ) . '%', + $wpdb->esc_like( '_citecue_reported_' ) . '%' + ) +); +// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching +wp_cache_flush(); + delete_transient( 'citecue_circuit' ); delete_transient( 'citecue_ingest_rate' ); delete_transient( 'citecue_connect_state' ); @@ -60,6 +80,7 @@ // within a day. wp_clear_scheduled_hook( 'citecue_daily_sync' ); +wp_clear_scheduled_hook( 'citecue_report_drain' ); // Single events, one per URL awaiting a metadata refresh. wp_unschedule_hook() // rather than wp_clear_scheduled_hook(), which only clears events whose // arguments match the ones passed — each of these carries its own URL.