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