prefix and are backtick-quoted; values use prepare(). Caching would return stale rows. defined( 'ABSPATH' ) || exit; /** * A tiny table holding one row per job, with its resume cursor. * * Job state lives in the database rather than in a transient so a step * that dies mid-request (timeout, OOM, a killed worker) leaves an exact * record of how far it got. */ class JobStore { /** * Fully qualified table name. * * @return string */ public static function table() { global $wpdb; return $wpdb->prefix . 'sitezip_jobs'; } /** * Create or upgrade the table. * * @return void */ public static function install() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = self::table(); $collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, type varchar(16) NOT NULL DEFAULT 'backup', status varchar(16) NOT NULL DEFAULT 'pending', stage varchar(32) NOT NULL DEFAULT 'init', progress tinyint unsigned NOT NULL DEFAULT 0, state longtext NULL, log text NULL, error text NULL, runner_token char(64) NOT NULL DEFAULT '', created_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', updated_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (id), KEY status (status), KEY created_at (created_at) ) {$collate};"; dbDelta( $sql ); } /** * Create a job. * * @param string $type 'backup' or 'restore'. * @param array $state Initial state. * @return int|false Job ID. */ public function create( $type, array $state = array() ) { global $wpdb; $now = current_time( 'mysql', true ); $inserted = $wpdb->insert( self::table(), array( 'type' => 'restore' === $type ? 'restore' : 'backup', 'status' => 'running', 'stage' => 'init', 'progress' => 0, 'state' => wp_json_encode( $state ), 'runner_token' => bin2hex( random_bytes( 32 ) ), 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s' ) ); return $inserted ? (int) $wpdb->insert_id : false; } /** * Record a one-off event (an import or a deleted backup) in the * activity log. Events are never "running", so they never block jobs. * * @param string $type 'import' or 'delete'. * @param string $file Backup file name. * @param string $message Log line. * @return void */ public function record( $type, $file, $message ) { global $wpdb; $now = current_time( 'mysql', true ); $wpdb->insert( self::table(), array( 'type' => in_array( $type, array( 'import', 'delete' ), true ) ? $type : 'import', 'status' => 'completed', 'stage' => 'done', 'progress' => 100, 'state' => wp_json_encode( array( 'file' => (string) $file ) ), 'log' => gmdate( 'H:i:s' ) . ' ' . $message, 'runner_token' => '', 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s' ) ); $this->prune(); } /** * Recent activity, newest first. * * @param int $limit Rows. * @return array[] */ public function recent( $limit = 25 ) { global $wpdb; // phpcs:ignore WordPress.DB.PreparedSQL -- table name built from the trusted prefix. $ids = $wpdb->get_col( $wpdb->prepare( 'SELECT id FROM ' . self::table() . ' ORDER BY id DESC LIMIT %d', max( 1, min( 100, (int) $limit ) ) ) ); return array_values( array_filter( array_map( array( $this, 'get' ), array_map( 'intval', (array) $ids ) ) ) ); } /** * Fetch a job. * * @param int $id Job ID. * @return array|null */ public function get( $id ) { global $wpdb; $id = absint( $id ); if ( ! $id ) { return null; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- job table, no cache layer wanted. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::table() . ' WHERE id = %d', $id ), ARRAY_A ); if ( ! $row ) { return null; } $row['state'] = json_decode( (string) $row['state'], true ); if ( ! is_array( $row['state'] ) ) { $row['state'] = array(); } return $row; } /** * Update fields on a job. * * @param int $id Job ID. * @param array $fields Fields to write. * @return void */ public function update( $id, array $fields ) { global $wpdb; if ( isset( $fields['state'] ) && is_array( $fields['state'] ) ) { $fields['state'] = wp_json_encode( $fields['state'] ); } $fields['updated_at'] = current_time( 'mysql', true ); $wpdb->update( self::table(), $fields, array( 'id' => absint( $id ) ) ); } /** * Append a line to the job log, keeping only the recent tail. * * @param int $id Job ID. * @param string $message Message. * @return void */ public function log( $id, $message ) { $job = $this->get( $id ); if ( ! $job ) { return; } $lines = $job['log'] ? explode( "\n", $job['log'] ) : array(); $lines[] = gmdate( 'H:i:s' ) . ' ' . $message; $lines = array_slice( $lines, -40 ); $this->update( $id, array( 'log' => implode( "\n", $lines ) ) ); } /** * The most recent job, if any. * * @param string|null $status Optional status filter. * @return array|null */ public function latest( $status = null ) { global $wpdb; // Only real jobs; imports and deletions are just log entries. $sql = 'SELECT id FROM ' . self::table() . " WHERE type IN ('backup','restore')"; if ( $status ) { // phpcs:ignore WordPress.DB.PreparedSQL -- placeholder used below. $sql = $wpdb->prepare( $sql . ' AND status = %s ORDER BY id DESC LIMIT 1', $status ); } else { $sql .= ' ORDER BY id DESC LIMIT 1'; } $id = $wpdb->get_var( $sql ); return $id ? $this->get( (int) $id ) : null; } /** * The currently running job, if any. * * @return array|null */ public function get_running() { return $this->latest( 'running' ); } /** * Mark stale running jobs as failed. * * A job whose last heartbeat is old has lost its runner -- the process * was killed without ever reaching a failure path. * * @param int $timeout Seconds of silence before a job is considered dead. * @return void */ public function reap( $timeout = 900 ) { global $wpdb; $cutoff = gmdate( 'Y-m-d H:i:s', time() - $timeout ); $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::table() . " SET status = 'failed', error = %s WHERE status = 'running' AND updated_at < %s", __( 'The job stopped responding and was cancelled.', 'sitezip' ), $cutoff ) ); } /** * Delete job rows older than a cutoff. * * @param int $days Age in days. * @return void */ public function prune( $days = 30 ) { global $wpdb; $cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) ); $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::table() . " WHERE status IN ('completed','failed','cancelled') AND created_at < %s", $cutoff ) ); } }