insert( Schema::table( 'scans' ), array( 'scan_uuid' => wp_generate_uuid4(), 'scan_type' => $type, 'status' => 'running', 'scheduled_for' => $scheduled_for, 'started_at' => gmdate( 'Y-m-d H:i:s' ), 'engine_version' => GSFP_ENGINE_VERSION, 'feed_version' => (string) $feed_version, ) ); return (int) $wpdb->insert_id; } /** * Store findings and mark the scan finished. * * @param Finding[] $findings * @param array $check_states rule_id => 'ok'|'error'|'timeout'|'skipped'. * @param string $status completed|partial|failed. */ public static function complete( $scan_id, array $findings, array $check_states, $status = 'completed', $error_summary = '' ) { global $wpdb; $table = Schema::table( 'findings' ); foreach ( $findings as $finding ) { $row = $finding->to_array(); $wpdb->insert( $table, array( 'scan_id' => (int) $scan_id, 'finding_key' => substr( $row['finding_id'], 0, 191 ), 'rule_id' => $row['rule_id'], 'rule_version' => $row['rule_version'], 'title' => $row['title'], 'category' => $row['category'], 'severity' => $row['severity'], 'status' => $row['status'], 'confidence' => $row['confidence'], 'payload' => wp_json_encode( $row ), 'detected_at' => $row['detected_at'], ) ); } $scan = self::get( $scan_id ); $started = $scan ? strtotime( $scan['started_at'] . ' UTC' ) : time(); $wpdb->update( Schema::table( 'scans' ), array( 'status' => $status, 'completed_at' => gmdate( 'Y-m-d H:i:s' ), 'duration_ms' => max( 0, ( time() - $started ) * 1000 ), 'counts' => wp_json_encode( self::count( $findings ) ), 'check_states' => wp_json_encode( $check_states ), 'error_summary' => substr( (string) $error_summary, 0, 1000 ), ), array( 'id' => (int) $scan_id ) ); } public static function fail( $scan_id, $error_summary ) { global $wpdb; $wpdb->update( Schema::table( 'scans' ), array( 'status' => 'failed', 'completed_at' => gmdate( 'Y-m-d H:i:s' ), 'error_summary' => substr( (string) $error_summary, 0, 1000 ), ), array( 'id' => (int) $scan_id ) ); } /** * Severity counts of findings needing attention, plus totals. * * @param Finding[] $findings * @return array */ public static function count( array $findings ) { $counts = array_fill_keys( Finding::SEVERITIES, 0 ); $counts['unknown'] = 0; $counts['total'] = count( $findings ); foreach ( $findings as $f ) { if ( $f->needs_attention() ) { ++$counts[ $f->get( 'severity' ) ]; } elseif ( 'unknown' === $f->get( 'status' ) || 'error' === $f->get( 'status' ) ) { ++$counts['unknown']; } } return $counts; } /** @return array|null scan row with counts/check_states decoded */ public static function get( $scan_id ) { global $wpdb; $table = Schema::table( 'scans' ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", (int) $scan_id ), ARRAY_A ); return $row ? self::decode( $row ) : null; } /** Most recent completed (or partial) scan, optionally strictly before $before_id. */ public static function latest_completed( $before_id = 0 ) { global $wpdb; $table = Schema::table( 'scans' ); if ( $before_id > 0 ) { // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $sql = $wpdb->prepare( "SELECT * FROM {$table} WHERE status IN ('completed','partial') AND id < %d ORDER BY id DESC LIMIT 1", (int) $before_id ); } else { $sql = "SELECT * FROM {$table} WHERE status IN ('completed','partial') ORDER BY id DESC LIMIT 1"; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared } $row = $wpdb->get_row( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared return $row ? self::decode( $row ) : null; } /** Most recent scan of any status (for "last attempt" display). */ public static function latest_any() { global $wpdb; $table = Schema::table( 'scans' ); $row = $wpdb->get_row( "SELECT * FROM {$table} ORDER BY id DESC LIMIT 1", ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared return $row ? self::decode( $row ) : null; } /** @return array> newest first */ public static function history( $limit = 30, $offset = 0 ) { global $wpdb; $table = Schema::table( 'scans' ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} ORDER BY id DESC LIMIT %d OFFSET %d", (int) $limit, (int) $offset ), ARRAY_A ); return array_map( array( __CLASS__, 'decode' ), (array) $rows ); } /** @return Finding[] sorted by severity rank then title */ public static function findings( $scan_id ) { global $wpdb; $table = Schema::table( 'findings' ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_col( $wpdb->prepare( "SELECT payload FROM {$table} WHERE scan_id = %d", (int) $scan_id ) ); $out = array(); foreach ( (array) $rows as $json ) { $data = json_decode( $json, true ); if ( is_array( $data ) ) { try { $out[] = Finding::from_array( $data ); } catch ( \InvalidArgumentException $e ) { continue; // Skip rows from an incompatible older rule version. } } } usort( $out, function ( $a, $b ) { $r = Finding::severity_rank( $a->get( 'severity' ) ) - Finding::severity_rank( $b->get( 'severity' ) ); return 0 !== $r ? $r : strcmp( $a->get( 'title' ), $b->get( 'title' ) ); } ); return $out; } /** * Compare two finding sets by finding_id, considering only findings needing attention. * Pure function — unit-testable. * * @param Finding[] $previous * @param Finding[] $current * @return array{new: Finding[], resolved: Finding[], persistent: Finding[], escalated: Finding[]} */ public static function diff( array $previous, array $current ) { $prev = array(); foreach ( $previous as $f ) { if ( $f->needs_attention() ) { $prev[ $f->id() ] = $f; } } $result = array( 'new' => array(), 'resolved' => array(), 'persistent' => array(), 'escalated' => array(), ); $seen = array(); foreach ( $current as $f ) { if ( ! $f->needs_attention() ) { continue; } $seen[ $f->id() ] = true; if ( ! isset( $prev[ $f->id() ] ) ) { $result['new'][] = $f; continue; } $result['persistent'][] = $f; if ( Finding::severity_rank( $f->get( 'severity' ) ) < Finding::severity_rank( $prev[ $f->id() ]->get( 'severity' ) ) ) { $result['escalated'][] = $f; } } foreach ( $prev as $id => $f ) { if ( ! isset( $seen[ $id ] ) ) { $result['resolved'][] = $f; } } return $result; } /** Delete scans (and their findings) older than $days. Returns number of scans deleted. */ public static function prune( $days ) { global $wpdb; $scans = Schema::table( 'scans' ); $findings = Schema::table( 'findings' ); $cutoff = gmdate( 'Y-m-d H:i:s', time() - max( 1, (int) $days ) * DAY_IN_SECONDS ); // Always keep the latest completed scan so the dashboard and diffs keep working. $keep = self::latest_completed(); $keep_id = $keep ? (int) $keep['id'] : 0; // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$scans} WHERE started_at < %s AND id <> %d", $cutoff, $keep_id ) ); if ( empty( $ids ) ) { return 0; } $ids = array_map( 'intval', $ids ); $in = implode( ',', $ids ); $wpdb->query( "DELETE FROM {$findings} WHERE scan_id IN ({$in})" ); $wpdb->query( "DELETE FROM {$scans} WHERE id IN ({$in})" ); // phpcs:enable return count( $ids ); } /** @param array $row */ private static function decode( array $row ) { foreach ( array( 'counts', 'check_states' ) as $k ) { $row[ $k ] = isset( $row[ $k ] ) ? (array) json_decode( (string) $row[ $k ], true ) : array(); } return $row; } }