2.74
format.c
1/* snac - A simple, minimalistic ActivityPub instance */
2/* copyright (c) 2022 - 2025 grunfink et al. / MIT license */
3
4#include "xs.h"
5#include "xs_regex.h"
6#include "xs_mime.h"
7#include "xs_html.h"
8#include "xs_json.h"
9#include "xs_time.h"
10#include "xs_match.h"
11
12#include "snac.h"
13
14/* emoticons, people laughing and such */
15const char *smileys[] = {
16 ":-)", "🙂",
17 ":-D", "😀",
18 "X-D", "😆",
19 ";-)", "😉",
20 "B-)", "😎",
21 ">:-(", "😡",
22 ":-(", "😞",
23 ":-*", "😘",
24 ":-/", "😕",
25 "8-o", "😲",
26 "%-)", "🤪",
27 ":_(", "😢",
28 ":-|", "😐",
29 "<3", "❤️",
30 ":facepalm:", "🤦",
31 ":shrug:", "🤷",
32 ":shrug2:", "¯\\_(ツ)_/¯",
33 ":eyeroll:", "🙄",
34 ":beer:", "🍺",
35 ":beers:", "🍻",
36 ":munch:", "😱",
37 ":thumb:", "👍",
38 NULL, NULL
39};
40
41
42xs_dict *emojis(void)
43/* returns a dict with the emojis */
44{
45 xs *fn = xs_fmt("%s/emojis.json", srv_basedir);
46 FILE *f;
47
48 if (mtime(fn) == 0) {
49 /* file does not exist; create it with the defaults */
50 xs *d = xs_dict_new();
51 const char **emo = smileys;
52
53 while (*emo) {
54 d = xs_dict_append(d, emo[0], emo[1]);
55 emo += 2;
56 }
57
58 if ((f = fopen(fn, "w")) != NULL) {
59 xs_json_dump(d, 4, f);
60 fclose(f);
61 }
62 else
63 srv_log(xs_fmt("Error creating '%s'", fn));
64 }
65
66 xs_dict *d = NULL;
67
68 if ((f = fopen(fn, "r")) != NULL) {
69 d = xs_json_load(f);
70 fclose(f);
71
72 if (d == NULL)
73 srv_log(xs_fmt("JSON parse error in '%s'", fn));
74 }
75 else
76 srv_log(xs_fmt("Error opening '%s'", fn));
77
78 return d;
79}
80
81/* Non-whitespace without trailing comma, period or closing paren */
82#define NOSPACE "([^[:space:],.)]+|[,.)]+[^[:space:],.)])+"
83
84static xs_str *format_line(const char *line, xs_list **attach)
85/* formats a line */
86{
87 xs_str *s = xs_str_new(NULL);
88 char *p;
89 const char *v;
90
91 /* split by markup */
92 xs *sm = xs_regex_split(line,
93 "("
94 "`[^`]+`" "|"
95 "~~[^~]+~~" "|"
96 "\\*\\*?\\*?[^\\*]+\\*?\\*?\\*" "|"
97 "__[^_]+__" "|" //anzu
98 "!\\[[^]]+\\]\\([^\\)]+\\)" "|"
99 "\\[[^]]+\\]\\([^\\)]+\\)" "|"
100 "[a-z]+:/" "/" NOSPACE "|"
101 "(mailto|xmpp):[^@[:space:]]+@" NOSPACE
102 ")");
103 int n = 0;
104
105 p = sm;
106 while (xs_list_iter(&p, &v)) {
107 if ((n & 0x1)) {
108 /* markup */
109 if (xs_startswith(v, "`")) {
110 xs *s1 = xs_strip_chars_i(xs_dup(v), "`");
111 xs *e1 = encode_html(s1);
112 xs *s2 = xs_fmt("<code>%s</code>", e1);
113 s = xs_str_cat(s, s2);
114 }
115 else
116 if (xs_startswith(v, "***")) {
117 xs *s1 = xs_strip_chars_i(xs_dup(v), "*");
118 xs *s2 = xs_fmt("<b><i>%s</i></b>", s1);
119 s = xs_str_cat(s, s2);
120 }
121 else
122 if (xs_startswith(v, "**")) {
123 xs *s1 = xs_strip_chars_i(xs_dup(v), "*");
124 xs *s2 = xs_fmt("<b>%s</b>", s1);
125 s = xs_str_cat(s, s2);
126 }
127 else
128 if (xs_startswith(v, "*")) {
129 xs *s1 = xs_strip_chars_i(xs_dup(v), "*");
130 xs *s2 = xs_fmt("<i>%s</i>", s1);
131 s = xs_str_cat(s, s2);
132 }
133 //anzu - begin
134 else
135 if (xs_startswith(v, "__")) {
136 xs *s1 = xs_strip_chars_i(xs_dup(v), "_");
137 xs *s2 = xs_fmt("<u>%s</u>", s1);
138 s = xs_str_cat(s, s2);
139 }
140 //anzu - end
141 else
142 if (xs_startswith(v, "~~")) {
143 xs *s1 = xs_strip_chars_i(xs_dup(v), "~");
144 xs *e1 = encode_html(s1);
145 xs *s2 = xs_fmt("<s>%s</s>", e1);
146 s = xs_str_cat(s, s2);
147 }
148 else
149 if (*v == '[') {
150 /* markdown-like links [label](url) */
151 xs *w = xs_strip_chars_i(
152 xs_replace_i(xs_replace(v, "#", "#"), "@", "@"),
153 ";
155
156 if (xs_list_len(l) == 2) {
157 xs *link = xs_fmt("<a href=\"%s\">%s</a>",
158 xs_list_get(l, 1), xs_list_get(l, 0));
159
160 s = xs_str_cat(s, link);
161 }
162 else
163 s = xs_str_cat(s, v);
164 }
165 else
166 if (*v == '!') {
167 /* markdown-like images  */
168 xs *w = xs_strip_chars_i(
169 xs_replace_i(xs_replace(v, "#", "#"), "@", "@"),
170 ";
172
173 if (xs_list_len(l) == 2) {
174 const char *alt_text = xs_list_get(l, 0);
175 const char *img_url = xs_list_get(l, 1);
176 const char *mime = xs_mime_by_ext(img_url);
177
178 if (attach != NULL && xs_startswith(mime, "image/")) {
179 const xs_dict *ad;
180 int add = 1;
181
182 xs_list_foreach(*attach, ad) {
183 if (strcmp(xs_dict_get_def(ad, "url", ""), img_url) == 0) {
184 add = 0;
185 break;
186 }
187 }
188
189 if (add) {
190 xs *d = xs_dict_new();
191
192 d = xs_dict_append(d, "mediaType", mime);
193 d = xs_dict_append(d, "url", img_url);
194 d = xs_dict_append(d, "name", alt_text);
195 d = xs_dict_append(d, "type", "Image");
196
197 *attach = xs_list_append(*attach, d);
198 }
199 }
200 else {
201 xs *link = xs_fmt("<a href=\"%s\">%s</a>", img_url, alt_text);
202
203 s = xs_str_cat(s, link);
204 }
205 }
206 else
207 s = xs_str_cat(s, v);
208 }
209 else
210 if (xs_str_in(v, ":/" "/") != -1) {
211 xs *u = xs_replace_i(xs_replace(v, "#", "#"), "@", "@");
212
213 xs *v2 = xs_strip_chars_i(xs_dup(u), ".,)");
214
215 const char *mime = xs_mime_by_ext(v2);
216
217 if (attach != NULL && xs_startswith(mime, "image/")) {
218 /* if it's a link to an image, insert it as an attachment */
219 const xs_dict *ad;
220 int add = 1;
221
222 xs_list_foreach(*attach, ad) {
223 if (strcmp(xs_dict_get_def(ad, "url", ""), v2) == 0) {
224 add = 0;
225 break;
226 }
227 }
228
229 if (add) {
230 xs *d = xs_dict_new();
231
232 d = xs_dict_append(d, "mediaType", mime);
233 d = xs_dict_append(d, "url", v2);
234 d = xs_dict_append(d, "name", "");
235 d = xs_dict_append(d, "type", "Image");
236
237 *attach = xs_list_append(*attach, d);
238 }
239 }
240 else {
241 xs *s1 = xs_fmt("<a href=\"%s\" target=\"_blank\">%s</a>", v2, u);
242 s = xs_str_cat(s, s1);
243 }
244 }
245 else
246 if (xs_match(v, "mailto*|xmpp*")) {
247 xs *u = xs_replace_i(xs_replace(v, "#", "#"), "@", "@");
248
249 xs *v2 = xs_strip_chars_i(xs_dup(u), ".,)");
250
251 xs *s1 = xs_fmt("<a href=\"%s\" target=\"_blank\">%s</a>", v2, u);
252 s = xs_str_cat(s, s1);
253 }
254 else
255 s = xs_str_cat(s, v);
256 }
257 else
258 /* surrounded text, copy directly */
259 s = xs_str_cat(s, v);
260
261 n++;
262 }
263
264 return s;
265}
266
267
268xs_str *not_really_markdown(const char *content, xs_list **attach, xs_list **tag)
269/* formats a content using some Markdown rules */
270{
271 xs_str *s = xs_str_new(NULL);
272 int in_pre = 0;
273 int in_blq = 0;
274 xs *list;
275 char *p;
276 const char *v;
277
278 /* work by lines */
279 list = xs_split(content, "\n");
280
281 p = list;
282 while (xs_list_iter(&p, &v)) {
283 xs *ss = NULL;
284
285 if (strcmp(v, "```") == 0) {
286 if (!in_pre)
287 s = xs_str_cat(s, "<pre>");
288 else
289 s = xs_str_cat(s, "</pre>");
290
291 in_pre = !in_pre;
292 continue;
293 }
294
295 if (in_pre) {
296 // Encode all HTML characters when we're in pre element until we are out.
297 ss = encode_html(v);
298
299 s = xs_str_cat(s, ss);
300 s = xs_str_cat(s, "<br>");
301 continue;
302 }
303
304 else
305 ss = xs_strip_i(format_line(v, attach));
306
307 if (xs_startswith(ss, "---")) {
308 /* delete the --- */
309 ss = xs_strip_i(xs_crop_i(ss, 3, 0));
310 s = xs_str_cat(s, "<hr>");
311
312 s = xs_str_cat(s, ss);
313
314 continue;
315 }
316
317 //anzu - begin
318 // h1 reserved for snac?
319 if (xs_startswith(ss, "# ")) {
320 ss = xs_strip_i(xs_crop_i(ss, 2, 0));
321 s = xs_str_cat(s, "<h2>");
322 s = xs_str_cat(s, ss);
323 s = xs_str_cat(s, "</h2>");
324 continue;
325 }
326 if (xs_startswith(ss, "## ")) {
327 ss = xs_strip_i(xs_crop_i(ss, 3, 0));
328 s = xs_str_cat(s, "<h2>");
329 s = xs_str_cat(s, ss);
330 s = xs_str_cat(s, "</h2>");
331 continue;
332 }
333 if (xs_startswith(ss, "### ")) {
334 ss = xs_strip_i(xs_crop_i(ss, 4, 0));
335 s = xs_str_cat(s, "<h3>");
336 s = xs_str_cat(s, ss);
337 s = xs_str_cat(s, "</h3>");
338 continue;
339 }
340 //anzu - end
341
342 if (xs_startswith(ss, ">")) {
343 /* delete the > and subsequent spaces */
344 ss = xs_strip_i(xs_crop_i(ss, 1, 0));
345
346 if (!in_blq) {
347 s = xs_str_cat(s, "<blockquote>");
348 in_blq = 1;
349 }
350
351 s = xs_str_cat(s, ss);
352 s = xs_str_cat(s, "<br>");
353
354 continue;
355 }
356
357 if (in_blq) {
358 s = xs_str_cat(s, "</blockquote>");
359 in_blq = 0;
360 }
361
362 s = xs_str_cat(s, ss);
363 s = xs_str_cat(s, "<br>");
364 }
365
366 if (in_blq)
367 s = xs_str_cat(s, "</blockquote>");
368 if (in_pre)
369 s = xs_str_cat(s, "</pre>");
370
371 /* some beauty fixes */
372 s = xs_replace_i(s, "<br><br><blockquote>", "<br><blockquote>");
373 s = xs_replace_i(s, "</blockquote><br>", "</blockquote>");
374 s = xs_replace_i(s, "</pre><br>", "</pre>");
375 s = xs_replace_i(s, "</h2><br>", "</h2>"); //anzu ???
376 s = xs_replace_i(s, "</h3><br>", "</h3>"); //anzu ???
377
378 {
379 /* traditional emoticons */
380 xs *d = emojis();
381 int c = 0;
382 const char *k, *v;
383
384 while (xs_dict_next(d, &k, &v, &c)) {
385 const char *t = NULL;
386
387 /* is it an URL to an image? */
388 if (xs_startswith(v, "https:/" "/") && xs_startswith((t = xs_mime_by_ext(v)), "image/")) {
389 if (tag && xs_str_in(s, k) != -1) {
390 /* add the emoji to the tag list */
391 xs *e = xs_dict_new();
392 xs *i = xs_dict_new();
393 xs *u = xs_str_utctime(0, ISO_DATE_SPEC);
394
395 e = xs_dict_append(e, "id", v);
396 e = xs_dict_append(e, "type", "Emoji");
397 e = xs_dict_append(e, "name", k);
398 e = xs_dict_append(e, "updated", u);
399
400 i = xs_dict_append(i, "type", "Image");
401 i = xs_dict_append(i, "mediaType", t);
402 i = xs_dict_append(i, "url", v);
403 e = xs_dict_append(e, "icon", i);
404
405 *tag = xs_list_append(*tag, e);
406 }
407 }
408 else
409 s = xs_replace_i(s, k, v);
410 }
411 }
412
413 return s;
414}
415
416
417const char *valid_tags[] = {
418 "a", "p", "br", "br/", "blockquote", "ul", "ol", "li", "cite", "small",
419 "span", "i", "b", "u", "s", "pre", "code", "em", "strong", "hr", "img", "del", "bdi",
420 "h2","h3", //anzu
421 NULL
422};
423
424xs_str *sanitize(const char *content)
425/* cleans dangerous HTML output */
426{
427 xs_str *s = xs_str_new(NULL);
428 xs *sl;
429 int n = 0;
430 char *p;
431 const char *v;
432
433 sl = xs_regex_split(content, "</?[^>]+>");
434
435 p = sl;
436
437 n = 0;
438 while (xs_list_iter(&p, &v)) {
439 if (n & 0x1) {
440 xs *s1 = xs_strip_i(xs_crop_i(xs_dup(v), v[1] == '/' ? 2 : 1, -1));
441 xs *l1 = xs_split_n(s1, " ", 1);
442 xs *tag = xs_tolower_i(xs_dup(xs_list_get(l1, 0)));
443 xs *s2 = NULL;
444 int i;
445
446 /* check if it's one of the valid tags */
447 for (i = 0; valid_tags[i]; i++) {
448 if (strcmp(tag, valid_tags[i]) == 0)
449 break;
450 }
451
452 if (valid_tags[i]) {
453 /* accepted tag: rebuild it with only the accepted elements */
454 xs *el = xs_regex_select(v, "(src|href|rel|class|target)=(\"[^\"]*\"|'[^']*')");
455 xs *s3 = xs_join(el, " ");
456
457 s2 = xs_fmt("<%s%s%s%s>",
458 v[1] == '/' ? "/" : "", tag, xs_list_len(el) ? " " : "", s3);
459
460 s = xs_str_cat(s, s2);
461 } else {
462 /* treat end of divs as paragraph breaks */
463 if (strcmp(v, "</div>"))
464 s = xs_str_cat(s, "<p>");
465 }
466 }
467 else {
468 /* non-tag */
469 s = xs_str_cat(s, v);
470 }
471
472 n++;
473 }
474
475 return s;
476}
477
478
479xs_str *encode_html(const char *str)
480/* escapes html characters */
481{
482 xs_str *encoded = xs_html_encode((char *)str);
483
484 /* Restore only <br>. Probably safe. Let's hope nothing goes wrong with this. */
485 encoded = xs_replace_i(encoded, "<br>", "<br>");
486
487 return encoded;
488}