format.c 15 KB

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