prefix . self::TABLE; } /** * CREATE TABLE statement for dbDelta. * * @return string */ public static function schema(): string { global $wpdb; $table = self::table(); $charset = $wpdb->get_charset_collate(); return "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, created_at datetime NOT NULL, type varchar(32) NOT NULL, message text NOT NULL, PRIMARY KEY (id), KEY created_at (created_at) ) {$charset};"; } /** * Add an entry. Connection secrets are removed from the message. * * @param string $type One of self::TYPES. * @param string $message Human-readable message. * @return void */ public static function add( string $type, string $message ): void { global $wpdb; if ( ! in_array( $type, self::TYPES, true ) ) { _doing_it_wrong( __METHOD__, esc_html( 'Unknown log type: ' . $type ), '0.1.0' ); return; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- custom log table. $wpdb->insert( self::table(), array( 'created_at' => current_time( 'mysql', true ), 'type' => $type, 'message' => self::clean( $message ), ), array( '%s', '%s', '%s' ) ); } /** * Newest entries first. * * @param int $limit Maximum number of entries. * @return array */ public static function recent( int $limit = 50 ): array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom log table. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, created_at, type, message FROM {$wpdb->prefix}smsportal_connection_log ORDER BY id DESC LIMIT %d", max( 1, $limit ) ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * Strip secrets and markup, cap the length. * * @param string $message Message. * @return string */ private static function clean( string $message ): string { $secrets = array_filter( array( Connection::api_key(), Connection::webhook_secret() ) ); if ( $secrets ) { $message = str_replace( $secrets, '[redacted]', $message ); } $message = (string) preg_replace( '/txb_[A-Za-z0-9_\-]+/', '[redacted]', $message ); $message = sanitize_text_field( $message ); return mb_substr( $message, 0, self::MAX_MESSAGE_LENGTH ); } }