From 0e8e1ae74f84cb64b4b85f7015db5eeea262757d Mon Sep 17 00:00:00 2001
From: "Rob Swindell (on Debian Linux)" <rob@synchro.net>
Date: Sat, 30 Nov 2024 21:00:33 -0800
Subject: [PATCH] Create/use mimehdr encode() method for MIME/Q-encoding UTF-8
 header fields

Use it in newsutil get_news_subject() when no original (RFC822)
Subject header field exists.

This should fix issue #817.
---
 exec/load/mimehdr.js  | 37 ++++++++++++++++++++++++++++++++++++-
 exec/load/newsutil.js |  4 +++-
 2 files changed, 39 insertions(+), 2 deletions(-)

diff --git a/exec/load/mimehdr.js b/exec/load/mimehdr.js
index 0de20bb142..e88e0d0c9f 100644
--- a/exec/load/mimehdr.js
+++ b/exec/load/mimehdr.js
@@ -66,4 +66,39 @@ function to_cp437(val)
 	return result.join('');
 }
 
-this;
\ No newline at end of file
+function encode_word(word)
+{
+	var output = "=?utf-8?q?";
+	for(var i in word) {
+		var ch = word[i];
+		if(ascii(ch) < 0x80 && ch != '=')
+			output += ch;
+		else
+			output += format("=%02X", ascii(ch));
+	}
+	return output + "?=";
+}
+
+function encode(val)
+{
+	if(str_is_ascii(val))
+		return val;
+
+	var output = '';
+	var words = val.split(/\s+/g);
+	for(var i in words) {
+		if(output.length)
+			output += " ";
+		var word = words[i];
+		if(str_is_ascii(word)) {
+			output += word;
+			continue;
+		}
+		if(!str_is_utf8(word))
+			word = utf8_encode(word);
+		output += encode_word(word);
+	}
+	return output;
+}
+
+this;
diff --git a/exec/load/newsutil.js b/exec/load/newsutil.js
index 4b4d649839..af27e1e8f9 100755
--- a/exec/load/newsutil.js
+++ b/exec/load/newsutil.js
@@ -4,6 +4,8 @@
 require("mailutil.js", 'mail_get_name');
 require("smbdefs.js", 'RFC822HEADER');
 
+const mimehdr = load("mimehdr.js");
+
 function get_news_subject(hdr)
 {
 	if(hdr.field_list !== undefined)
@@ -11,7 +13,7 @@ function get_news_subject(hdr)
 			if(hdr.field_list[i].type == RFC822SUBJECT)
 				return hdr.field_list[i].data;
 		}
-	return hdr.subject;
+	return mimehdr.encode(hdr.subject);
 }
 
 function get_news_from(hdr)
-- 
GitLab