1 /**
2 * Copyright © Yurai Web Framework 2021
3 * License: MIT (https://github.com/YuraiWeb/yurai/blob/main/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module yurai.security.html;
7 
8 string escapeHtml(string html)
9 {
10   import std.string : format;
11   import std.conv : to;
12 
13   if (!html || !html.length)
14   {
15     return html;
16   }
17 
18   string result = "";
19 
20   foreach (c; html)
21   {
22     switch (c)
23     {
24       case '<':
25       {
26         result ~= "&lt;";
27         break;
28       }
29 
30       case '>':
31       {
32         result ~= "&gt;";
33         break;
34       }
35 
36       case '"':
37       {
38         result ~= "&quot;";
39         break;
40       }
41 
42       case '\'':
43       {
44         result ~= "&#39;";
45         break;
46       }
47 
48       case '&':
49       {
50         result ~= "&amp;";
51         break;
52       }
53 
54       case '/':
55       {
56         result ~= "&#47;";
57         break;
58       }
59 
60       default:
61       {
62         if (c < ' ' && c != '\r' && c != '\n' && c != '\t')
63         {
64           result ~= format("&#%d;", c);
65         }
66         else
67         {
68           result ~= to!string(c);
69         }
70       }
71     }
72   }
73 
74   return result;
75 }