prefix . 'aiou_email_log'; } /** * Create/upgrade the table if the stored schema version is behind. * * @return void */ public static function maybe_install(): void { if ( self::DB_VERSION === get_option( self::OPTION_KEY ) ) { return; } self::install(); } /** * Create/upgrade the table. `dbDelta()` only applies the diff. * * @return void */ public static function install(): void { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table_name = self::table_name(); $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$table_name} ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, sent_at DATETIME NOT NULL, to_address TEXT NOT NULL, subject TEXT NOT NULL, body LONGTEXT NULL, headers TEXT NULL, is_html TINYINT(1) UNSIGNED NOT NULL DEFAULT 0, status VARCHAR(10) NOT NULL DEFAULT 'sent', error TEXT NULL, PRIMARY KEY (id), KEY sent_at (sent_at), KEY status (status) ) {$charset_collate};"; dbDelta( $sql ); update_option( self::OPTION_KEY, self::DB_VERSION ); } /** * Drop the table (uninstall only). * * @return void */ public static function uninstall(): void { global $wpdb; $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', self::table_name() ) ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- %i (identifier placeholder, WP 6.2+) is correct here; this plugin requires WP 6.6+. delete_option( self::OPTION_KEY ); } /** * Record a sent (or about-to-be-attempted) email. * * @param array $data Columns: to_address, subject, body (nullable), headers (nullable), is_html. * @return int The new row's id. */ public static function insert( array $data ): int { global $wpdb; $wpdb->insert( self::table_name(), array( 'sent_at' => current_time( 'mysql' ), 'to_address' => $data['to_address'], 'subject' => $data['subject'], 'body' => $data['body'], 'headers' => $data['headers'], 'is_html' => $data['is_html'] ? 1 : 0, 'status' => 'sent', ), array( '%s', '%s', '%s', '%s', '%s', '%d', '%s' ) ); return (int) $wpdb->insert_id; } /** * Mark a logged email as failed. * * @param int $id Row id. * @param string $error Error message. * @return void */ public static function mark_failed( int $id, string $error ): void { global $wpdb; $wpdb->update( self::table_name(), array( 'status' => 'failed', 'error' => $error, ), array( 'id' => $id ), array( '%s', '%s' ), array( '%d' ) ); } /** * A single logged email. * * @param int $id Row id. * @return object|null */ public static function get( int $id ): ?object { global $wpdb; return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', self::table_name(), $id ) ); } /** * Paginated, filterable query for the admin list table. * * @param array $args { * Query arguments. * * @type int $page 1-based page number. * @type int $per_page Rows per page. * @type string $status 'sent', 'failed', or '' for all. * @type string $search Matches to_address, subject or the error message. * @type string $date_from 'Y-m-d' (inclusive, site time) or ''. * @type string $date_to 'Y-m-d' (inclusive, site time) or ''. * @type string $format 'html', 'plain', or '' for both. * @type string $orderby 'sent_at', 'status', 'to_address', or 'subject'. * @type string $order 'ASC' or 'DESC'. * } * @return object[] */ public static function query( array $args = array() ): array { global $wpdb; $args = wp_parse_args( $args, array( 'page' => 1, 'per_page' => 20, 'status' => '', 'search' => '', 'orderby' => 'sent_at', 'order' => 'DESC', ) ); list( $where_sql, $where_values ) = self::build_where( $args ); $orderby = in_array( $args['orderby'], self::SORTABLE, true ) ? $args['orderby'] : 'sent_at'; $order = 'ASC' === strtoupper( (string) $args['order'] ) ? 'ASC' : 'DESC'; $offset = max( 0, ( (int) $args['page'] - 1 ) * (int) $args['per_page'] ); $sql = "SELECT id, sent_at, to_address, subject, is_html, status, error FROM %i {$where_sql} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d"; return $wpdb->get_results( $wpdb->prepare( $sql, array_merge( array( self::table_name() ), $where_values, array( (int) $args['per_page'], $offset ) ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $where_sql's own placeholders pass through this same prepare() call; $orderby/$order are whitelisted against a fixed enum above, never raw input. } /** * Count rows matching the same filters `query()` accepts. * * @param array $args Same filter keys as query(). * @return int */ public static function count( array $args = array() ): int { global $wpdb; list( $where_sql, $where_values ) = self::build_where( $args ); $sql = "SELECT COUNT(*) FROM %i {$where_sql}"; return (int) $wpdb->get_var( $wpdb->prepare( $sql, array_merge( array( self::table_name() ), $where_values ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $where_sql's own placeholders pass through this same prepare() call. } /** * Build a shared WHERE clause (status, search, dates, format) for query()/count(). * * @param array $args Filter keys; see query(). * @return array{0: string, 1: array} SQL fragment (placeholders only, no table name) and its values, in order. */ private static function build_where( array $args ): array { global $wpdb; $clauses = array(); $values = array(); $status = $args['status'] ?? ''; if ( in_array( $status, array( 'sent', 'failed' ), true ) ) { $clauses[] = 'status = %s'; $values[] = $status; } $search = trim( (string) ( $args['search'] ?? '' ) ); if ( '' !== $search ) { $clauses[] = '(to_address LIKE %s OR subject LIKE %s OR error LIKE %s)'; $like = '%' . $wpdb->esc_like( $search ) . '%'; array_push( $values, $like, $like, $like ); } $date_from = self::valid_date( $args['date_from'] ?? '' ); if ( '' !== $date_from ) { $clauses[] = 'sent_at >= %s'; $values[] = $date_from . ' 00:00:00'; } $date_to = self::valid_date( $args['date_to'] ?? '' ); if ( '' !== $date_to ) { $clauses[] = 'sent_at <= %s'; $values[] = $date_to . ' 23:59:59'; } $format = $args['format'] ?? ''; if ( 'html' === $format || 'plain' === $format ) { $clauses[] = 'is_html = %d'; $values[] = 'html' === $format ? 1 : 0; } $sql = $clauses ? ( 'WHERE ' . implode( ' AND ', $clauses ) ) : ''; return array( $sql, $values ); } /** * A 'Y-m-d' date string if it is a real calendar date, otherwise ''. * * @param mixed $date Candidate date. * @return string */ public static function valid_date( $date ): string { $date = (string) $date; if ( ! preg_match( '/^(\d{4})-(\d{2})-(\d{2})$/', $date, $m ) || ! checkdate( (int) $m[2], (int) $m[3], (int) $m[1] ) ) { return ''; } return $date; } /** * Every row matching the filters, oldest last, for the CSV export. * * @param array $args Same filter keys as query(). * @param int $limit Safety cap on the number of rows. * @return object[] */ public static function export_rows( array $args, int $limit = 10000 ): array { global $wpdb; list( $where_sql, $where_values ) = self::build_where( $args ); $sql = "SELECT sent_at, status, to_address, subject, is_html, error FROM %i {$where_sql} ORDER BY sent_at DESC LIMIT %d"; return $wpdb->get_results( $wpdb->prepare( $sql, array_merge( array( self::table_name() ), $where_values, array( $limit ) ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $where_sql's own placeholders pass through this same prepare() call. } /** * Delete specific rows by id. * * @param int[] $ids Row ids. * @return void */ public static function delete( array $ids ): void { $ids = array_filter( array_map( 'absint', $ids ) ); if ( ! $ids ) { return; } global $wpdb; $placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE id IN ({$placeholders})", array_merge( array( self::table_name() ), $ids ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- {$placeholders} is built entirely from a literal '%d' repeated count($ids) times above, never from raw input; every value, including the id list, goes through this same prepare() call. } /** * Delete every logged email (the manual "Clear log" action). * * @return void */ public static function delete_all(): void { global $wpdb; $wpdb->query( $wpdb->prepare( 'TRUNCATE TABLE %i', self::table_name() ) ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- %i identifier placeholder; no other values. } /** * Delete logged emails older than a retention window (the automatic * cleanup cron). A `$days` of 0 means "keep forever" and is a no-op. * * @param int $days Retention window in days. * @return void */ public static function delete_older_than( int $days ): void { if ( $days <= 0 ) { return; } global $wpdb; $cutoff = gmdate( 'Y-m-d H:i:s', (int) current_time( 'timestamp' ) - ( $days * DAY_IN_SECONDS ) ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested -- compared against sent_at, which is also stored via current_time( 'mysql' ) (site local time), so both sides must use the same local reference. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE sent_at < %s', self::table_name(), $cutoff ) ); } }