prefix . 'rtkt_log'; } /** * CREATE TABLE statement. * * @param string $collate Charset/collation clause. * @return string */ public static function schema( $collate ) { $table = self::table(); return "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, request_id bigint(20) unsigned NOT NULL DEFAULT 0, created_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00', actor varchar(20) NOT NULL DEFAULT 'system', user_id bigint(20) unsigned NOT NULL DEFAULT 0, event varchar(40) NOT NULL DEFAULT '', message text NULL, data longtext NULL, PRIMARY KEY (id), KEY request_id (request_id), KEY created_at (created_at) ) {$collate};"; } /** * Add an entry. * * @param int $request_id Request ID. * @param string $event Event key (created, approved, refunded, email_sent …). * @param string $message Human text (already translated; stored as written). * @param string $actor customer | admin | system. * @param array $data Extra structured data. * @return int Entry ID. */ public static function add( $request_id, $event, $message = '', $actor = 'system', array $data = array() ) { global $wpdb; $wpdb->insert( self::table(), array( 'request_id' => absint( $request_id ), 'created_at' => current_time( 'mysql', true ), 'actor' => sanitize_key( $actor ), 'user_id' => get_current_user_id(), 'event' => sanitize_key( $event ), 'message' => wp_strip_all_tags( (string) $message ), 'data' => $data ? wp_json_encode( $data ) : null, ) ); return (int) $wpdb->insert_id; } /** * Entries of a request, oldest first. * * @param int $request_id Request ID. * @return array[] */ public static function for_request( $request_id ) { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE request_id = %d ORDER BY id ASC', self::table(), absint( $request_id ) ), ARRAY_A ); return array_map( array( __CLASS__, 'decode' ), $rows ? $rows : array() ); } /** * Latest entries across all requests. * * @param int $limit Rows. * @return array[] */ public static function recent( $limit = 10 ) { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY id DESC LIMIT %d', self::table(), max( 1, (int) $limit ) ), ARRAY_A ); return array_map( array( __CLASS__, 'decode' ), $rows ? $rows : array() ); } /** * Whether a request has an entry for an event. * * @param int $request_id Request ID. * @param string $event Event key. * @return bool */ public static function has( $request_id, $event ) { global $wpdb; return (bool) $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE request_id = %d AND event = %s LIMIT 1', self::table(), absint( $request_id ), sanitize_key( $event ) ) ); } /** * Decode the data column. * * @param array $row Row. * @return array */ private static function decode( $row ) { $data = isset( $row['data'] ) ? json_decode( (string) $row['data'], true ) : null; $row['data'] = is_array( $data ) ? $data : array(); return $row; } }