1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.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 ~= "&nbsp;";
57         break;
58       }
59 
60       case '(':
61       {
62         result ~= "&#40;";
63         break;
64       }
65 
66       case ')':
67       {
68         result ~= "&#41;";
69         break;
70       }
71 
72       default:
73       {
74         if (c < ' ')
75         {
76           result ~= format("&#%d;", c);
77         }
78         else
79         {
80           result ~= to!string(c);
81         }
82       }
83     }
84   }
85 
86   return result;
87 }
88 
89 string escapeJson(string json)
90 {
91   import std..string : format;
92   import std.conv : to;
93 
94   if (!json || !json.length)
95   {
96     return json;
97   }
98 
99   string result = "";
100 
101   foreach (c; json)
102   {
103     switch (c)
104     {
105       case '<':
106       {
107         result ~= "&lt;";
108         break;
109       }
110 
111       case '>':
112       {
113         result ~= "&gt;";
114         break;
115       }
116 
117       case '&':
118       {
119         result ~= "&amp;";
120         break;
121       }
122 
123       case '(':
124       {
125         result ~= "&#40;";
126         break;
127       }
128 
129       case ')':
130       {
131         result ~= "&#41;";
132         break;
133       }
134 
135       default:
136       {
137         result ~= to!string(c);
138       }
139     }
140   }
141 
142   return result;
143 }