insert( // phpcs:ignore Install::table( 'logs' ), array( 'form_id' => (int) $form_id, 'entry_id' => (int) $entry_id, 'component' => substr( (string) $component, 0, 50 ), 'status' => substr( (string) $status, 0, 20 ), 'title' => substr( (string) $title, 0, 250 ), 'message' => is_scalar( $message ) ? (string) $message : wp_json_encode( $message ), 'created_at' => current_time( 'mysql', true ), ) ); } /** @return array Logs (newest first). */ public static function query( array $args = array() ) { global $wpdb; $a = wp_parse_args( $args, array( 'form_id' => 0, 'entry_id' => 0, 'component' => '', 'status' => '', 'per_page' => 50, 'page' => 1 ) ); $where = array( '1=1' ); foreach ( array( 'form_id', 'entry_id' ) as $k ) { if ( $a[ $k ] ) { $where[] = $wpdb->prepare( "$k = %d", $a[ $k ] ); // phpcs:ignore } } foreach ( array( 'component', 'status' ) as $k ) { if ( $a[ $k ] ) { $where[] = $wpdb->prepare( "$k = %s", $a[ $k ] ); // phpcs:ignore } } $sql = implode( ' AND ', $where ); $t = Install::table( 'logs' ); $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $t WHERE $sql" ); // phpcs:ignore $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $t WHERE $sql ORDER BY id DESC LIMIT %d OFFSET %d", $a['per_page'], ( $a['page'] - 1 ) * $a['per_page'] ), ARRAY_A ); // phpcs:ignore return array( $rows, $total ); } /** Delete logs older than N days. */ public static function prune( $days = 60 ) { global $wpdb; $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . Install::table( 'logs' ) . ' WHERE created_at < %s', gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ) ) ); // phpcs:ignore } }