prefix . 'waref_queue'; } /** * Creates or updates the table. */ public static function install() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = self::table(); $collate = $wpdb->get_charset_collate(); dbDelta( "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, submission_id varchar(64) NOT NULL, plugin varchar(40) NOT NULL DEFAULT '', form_id varchar(120) NOT NULL DEFAULT '', form_name varchar(191) NOT NULL DEFAULT '', connection_key varchar(191) NOT NULL DEFAULT '', body longtext NOT NULL, attempts smallint(5) unsigned NOT NULL DEFAULT 0, next_attempt_at datetime NOT NULL, status varchar(20) NOT NULL DEFAULT 'queued', last_status smallint(5) unsigned NOT NULL DEFAULT 0, last_result varchar(191) NOT NULL DEFAULT '', created_at datetime NOT NULL, updated_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY submission_id (submission_id), KEY status_next (status,next_attempt_at), KEY created_at (created_at) ) {$collate};" ); // Rows from before 2.0.2 have no connection: they belong to the current one // (queued rows were already failed on every disconnect or reconnect). $connection = Waref_Forms_Options::connection(); if ( '' !== $connection['public_key'] ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table, one-time upgrade. $wpdb->query( $wpdb->prepare( "UPDATE %i SET connection_key = %s WHERE connection_key = ''", $table, $connection['public_key'] ) ); } update_option( Waref_Forms_Options::DB_VERSION, self::DB_VERSION, true ); } /** * Adds the five-minute schedule. * * @param array $schedules Schedules. * @return array */ public static function cron_schedules( $schedules ) { $schedules[ self::SCHEDULE ] = array( 'interval' => 5 * MINUTE_IN_SECONDS, 'display' => __( 'Every five minutes (Waref Forms)', 'waref-forms' ), ); return $schedules; } /** * Current UTC time as MySQL datetime, optionally shifted. * * @param int $offset Seconds to add. * @return string */ private static function now( $offset = 0 ) { return gmdate( 'Y-m-d H:i:s', time() + $offset ); } /** * Stores a payload and tries to send it once right away. * * @param array $payload Payload built by Waref_Forms_Payload (≤ 16 KB encoded). * @param bool $send_now Attempt the first delivery immediately. * @return int Row id, 0 when it could not be stored. */ public static function add( array $payload, $send_now = true ) { global $wpdb; $body = Waref_Forms_Client::encode( $payload ); $connection = Waref_Forms_Options::connection(); if ( '' === $body || '' === $connection['public_key'] ) { return 0; } $now = self::now(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- custom table. $inserted = $wpdb->insert( self::table(), array( 'submission_id' => (string) $payload['submissionId'], 'plugin' => isset( $payload['source']['plugin'] ) ? substr( (string) $payload['source']['plugin'], 0, 40 ) : '', 'form_id' => isset( $payload['source']['formId'] ) ? substr( (string) $payload['source']['formId'], 0, 120 ) : '', 'form_name' => isset( $payload['source']['formName'] ) ? mb_substr( (string) $payload['source']['formName'], 0, 180 ) : '', 'connection_key' => $connection['public_key'], 'body' => $body, 'attempts' => 0, 'next_attempt_at' => $now, 'status' => 'queued', 'last_status' => 0, 'last_result' => '', 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%d', '%s', '%s', '%s' ) ); if ( ! $inserted ) { return 0; } $id = (int) $wpdb->insert_id; if ( $send_now ) { self::attempt( $id ); } return $id; } /** * Claims a due row so two runs never send it at the same time. * * @param int $id Row id. * @return bool */ private static function claim( $id ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table, atomic claim. $claimed = $wpdb->query( $wpdb->prepare( "UPDATE %i SET next_attempt_at = %s, updated_at = %s WHERE id = %d AND status = 'queued' AND next_attempt_at <= %s", $table, self::now( 2 * MINUTE_IN_SECONDS ), self::now(), $id, self::now() ) ); return 1 === (int) $claimed; } /** * Sends one row (when due) and records the answer. * * @param int $id Row id. */ public static function attempt( $id ) { global $wpdb; $table = self::table(); if ( ! Waref_Forms_Options::is_connected() || ! self::claim( $id ) ) { return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $row = $wpdb->get_row( $wpdb->prepare( "SELECT id, body, attempts, connection_key FROM %i WHERE id = %d", $table, $id ) ); if ( ! $row ) { return; } // Only the connection the submission was captured for may receive it. $connection = Waref_Forms_Options::connection(); if ( ! hash_equals( (string) $connection['public_key'], (string) $row->connection_key ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $wpdb->update( $table, array( 'status' => 'failed', 'body' => '', 'last_result' => 'CONNECTION_CHANGED', 'updated_at' => self::now(), ), array( 'id' => $id ) ); return; } // Re-signed with a fresh timestamp on every attempt; the submissionId in the body stays the same. $result = Waref_Forms_Client::submit( (string) $row->body ); $attempts = (int) $row->attempts + 1; $data = array( 'attempts' => $attempts, 'last_status' => $result['status'], 'last_result' => substr( $result['code'], 0, 180 ), 'updated_at' => self::now(), ); if ( $result['ok'] ) { $data['status'] = 'sent'; $data['body'] = ''; // Delivered: keep no personal data here. if ( Waref_Forms_Options::needs_reconnect() ) { Waref_Forms_Options::update_connection( array( 'status' => 'active' ) ); } } elseif ( Waref_Forms_Client::is_retryable( $result ) && $attempts <= count( self::BACKOFF ) ) { $data['status'] = 'queued'; $data['next_attempt_at'] = self::now( self::BACKOFF[ $attempts - 1 ] ); } else { $data['status'] = 'failed'; if ( Waref_Forms_Client::is_refused( $result ) ) { Waref_Forms_Options::update_connection( array( 'status' => Waref_Forms_Options::STATUS_NEEDS_RECONNECT ) ); } } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $wpdb->update( $table, $data, array( 'id' => $id ) ); } /** * Cron: sends due rows (at most BATCH per run) and purges old rows. */ public static function process() { global $wpdb; $table = self::table(); self::purge(); if ( ! Waref_Forms_Options::is_connected() ) { return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i WHERE status = 'queued' AND next_attempt_at <= %s ORDER BY next_attempt_at ASC, id ASC LIMIT %d", $table, self::now(), self::BATCH ) ); foreach ( (array) $ids as $id ) { self::attempt( (int) $id ); if ( ! Waref_Forms_Options::is_connected() || Waref_Forms_Options::needs_reconnect() ) { break; } } } /** * Makes every waiting row due now, then processes the queue (admin button). */ public static function send_now() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $wpdb->query( $wpdb->prepare( "UPDATE %i SET next_attempt_at = %s WHERE status = 'queued'", $table, self::now() ) ); self::process(); } /** * Deletes sent rows after 7 days and failed rows after 30. */ public static function purge() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE (status = 'sent' AND updated_at < %s) OR (status = 'failed' AND updated_at < %s)", $table, self::now( -self::KEEP_SENT_DAYS * DAY_IN_SECONDS ), self::now( -self::KEEP_FAILED_DAYS * DAY_IN_SECONDS ) ) ); } /** * Puts failed rows that still have their body back in the queue — only rows * captured for the current connection. * * @return int Rows re-queued. */ public static function retry_failed() { global $wpdb; $table = self::table(); $connection = Waref_Forms_Options::connection(); if ( '' === $connection['public_key'] ) { return 0; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $count = $wpdb->query( $wpdb->prepare( "UPDATE %i SET status = 'queued', attempts = 0, next_attempt_at = %s, updated_at = %s WHERE status = 'failed' AND body <> '' AND connection_key = %s", $table, self::now(), self::now(), $connection['public_key'] ) ); return (int) $count; } /** * Marks every queued row as failed and drops the bodies of failed rows (on disconnect * or reconnect, so nothing reaches a later connection). * * @param string $reason Result code. */ public static function fail_queued( $reason ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $wpdb->query( $wpdb->prepare( "UPDATE %i SET status = 'failed', body = '', last_result = %s, updated_at = %s WHERE status = 'queued'", $table, (string) $reason, self::now() ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $wpdb->query( $wpdb->prepare( "UPDATE %i SET body = '' WHERE status = 'failed'", $table ) ); } /** * The latest rows for the log (no body: no personal data). * * @param int $limit Rows. * @return array */ public static function recent( $limit = 50 ) { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, plugin, form_id, form_name, attempts, next_attempt_at, status, last_status, last_result, created_at, (body <> '') AS has_body FROM %i ORDER BY id DESC LIMIT %d", $table, (int) $limit ) ); return is_array( $rows ) ? $rows : array(); } /** * Row counts by status. * * @return array */ public static function counts() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom table, no input. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT status, COUNT(*) AS n FROM %i GROUP BY status", $table ) ); $counts = array( 'queued' => 0, 'sent' => 0, 'failed' => 0, ); foreach ( (array) $rows as $row ) { $counts[ (string) $row->status ] = (int) $row->n; } return $counts; } /** * Drops the table (uninstall). */ public static function drop() { global $wpdb; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange -- uninstall. $wpdb->query( $wpdb->prepare( "DROP TABLE IF EXISTS %i", $table ) ); } }