forked from smartstore/SmartStoreNET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlUtils.cs
More file actions
284 lines (237 loc) · 9.86 KB
/
Copy pathHtmlUtils.cs
File metadata and controls
284 lines (237 loc) · 9.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Linq;
namespace SmartStore.Core.Html
{
/// <summary>
/// Represents a HTML helper
/// </summary>
public partial class HtmlUtils
{
#region Fields
private readonly static Regex paragraphStartRegex = new Regex("<p>", RegexOptions.IgnoreCase);
private readonly static Regex paragraphEndRegex = new Regex("</p>", RegexOptions.IgnoreCase);
//private static Regex ampRegex = new Regex("&(?!(?:#[0-9]{2,4};|[a-z0-9]+;))", RegexOptions.Compiled | RegexOptions.IgnoreCase);
#endregion
#region Utilities
private static string EnsureOnlyAllowedHtml(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
string allowedTags = "br,hr,b,i,u,a,div,ol,ul,li,blockquote,img,span,p,em,strong,font,pre,h1,h2,h3,h4,h5,h6,address,cite";
var m = Regex.Matches(text, "<.*?>", RegexOptions.IgnoreCase);
for (int i = m.Count - 1; i >= 0; i--)
{
string tag = text.Substring(m[i].Index + 1, m[i].Length - 1).Trim().ToLower();
if (!IsValidTag(tag, allowedTags))
{
text = text.Remove(m[i].Index, m[i].Length);
}
}
return text;
}
private static bool IsValidTag(string tag, string tags)
{
string[] allowedTags = tags.Split(',');
if (tag.IndexOf("javascript") >= 0) return false;
if (tag.IndexOf("vbscript") >= 0) return false;
if (tag.IndexOf("onclick") >= 0) return false;
var endchars = new char[] { ' ', '>', '/', '\t' };
int pos = tag.IndexOfAny(endchars, 1);
if (pos > 0) tag = tag.Substring(0, pos);
if (tag[0] == '/') tag = tag.Substring(1);
foreach (string aTag in allowedTags)
{
if (tag == aTag) return true;
}
return false;
}
#endregion
#region Methods
/// <summary>
/// Formats the text
/// </summary>
/// <param name="text">Text</param>
/// <param name="stripTags">A value indicating whether to strip tags</param>
/// <param name="convertPlainTextToHtml">A value indicating whether HTML is allowed</param>
/// <param name="allowHtml">A value indicating whether HTML is allowed</param>
/// <param name="allowBBCode">A value indicating whether BBCode is allowed</param>
/// <param name="resolveLinks">A value indicating whether to resolve links</param>
/// <param name="addNoFollowTag">A value indicating whether to add "noFollow" tag</param>
/// <returns>Formatted text</returns>
public static string FormatText(string text, bool stripTags,
bool convertPlainTextToHtml, bool allowHtml,
bool allowBBCode, bool resolveLinks, bool addNoFollowTag)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
try
{
if (stripTags)
{
text = HtmlUtils.StripTags(text);
}
if (allowHtml)
{
text = HtmlUtils.EnsureOnlyAllowedHtml(text);
}
else
{
text = HttpUtility.HtmlEncode(text);
}
if (convertPlainTextToHtml)
{
text = HtmlUtils.ConvertPlainTextToHtml(text);
}
if (allowBBCode)
{
text = BBCodeHelper.FormatText(text, true, true, true, true, true, true);
}
if (resolveLinks)
{
text = ResolveLinksHelper.FormatText(text);
}
if (addNoFollowTag)
{
//add noFollow tag. not implemented
}
}
catch (Exception exc)
{
text = string.Format("Text cannot be formatted. Error: {0}", exc.Message);
}
return text;
}
/// <summary>
/// Strips tags
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string StripTags(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, @"(>)(\r|\n)*(<)", "><");
text = Regex.Replace(text, "(<[^>]*>)([^<]*)", "$2");
text = Regex.Replace(text, "(&#x?[0-9]{2,4};|"|&| |<|>|€|©|®|‰|‡|†|‹|›|„|”|“|‚|’|‘|—|–|‏|‎|‍|‌| | | |˜|ˆ|Ÿ|š|Š)", "@");
return text;
}
/// <summary>
/// replace anchor text (remove a tag from the following url <a href="http://example.com">Name</a> and output only the string "Name")
/// </summary>
/// <param name="text">Text</param>
/// <returns>Text</returns>
public static string ReplaceAnchorTags(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, @"<a\b[^>]+>([^<]*(?:(?!</a)<[^<]*)*)</a>", "$1", RegexOptions.IgnoreCase);
return text;
}
/// <summary>
/// Converts plain text to HTML
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string ConvertPlainTextToHtml(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = text.Replace("\r\n", "<br />");
text = text.Replace("\r", "<br />");
text = text.Replace("\n", "<br />");
text = text.Replace("\t", " ");
text = text.Replace(" ", " ");
return text;
}
/// <summary>
/// Converts HTML to plain text
/// </summary>
/// <param name="text">Text</param>
/// <param name="decode">A value indicating whether to decode text</param>
/// <param name="replaceAnchorTags">A value indicating whether to replace anchor text (remove a tag from the following url <a href="http://example.com">Name</a> and output only the string "Name")</param>
/// <returns>Formatted text</returns>
public static string ConvertHtmlToPlainText(string text,
bool decode = false, bool replaceAnchorTags = false)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
if (decode)
text = HttpUtility.HtmlDecode(text);
text = text.Replace("<br>", "\n");
text = text.Replace("<br >", "\n");
text = text.Replace("<br />", "\n");
text = text.Replace(" ", "\t");
text = text.Replace(" ", " ");
if (replaceAnchorTags)
text = ReplaceAnchorTags(text);
return text;
}
/// <summary>
/// Converts an attribute string spec to a html table putting each new line in a TR and each attr name/value in a TD.
/// </summary>
/// <param name="text">The text to convert</param>
/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
/// <returns>The formatted (html) string</returns>
public static string ConvertPlainTextToTable(string text, string tableCssClass = null)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = text.Replace("\r\n", "\n").Replace("\r", "\n");
text = text + "\n\n";
var lines = text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length == 0)
{
return string.Empty;
}
var builder = new StringBuilder();
builder.AppendFormat("<table{0}>", tableCssClass.HasValue() ? "class='" + tableCssClass + "'" : "");
lines.Where(x => x.HasValue()).Each(x =>
{
builder.Append("<tr>");
var tokens = x.Split(new char[] { ':' }, 2);
if (tokens.Length > 1)
{
builder.AppendFormat("<td class='attr-caption'>{0}</td>", tokens[0]);
builder.AppendFormat("<td class='attr-value'>{0}</td>", tokens[1]);
}
else
{
builder.Append("<td> </td>");
builder.AppendFormat("<td class='attr-value'>{0}</td>",tokens[0]);
}
builder.Append("</tr>");
});
builder.Append("</table>");
return builder.ToString();
}
/// <summary>
/// Converts text to paragraph
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string ConvertPlainTextToParagraph(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = paragraphStartRegex.Replace(text, string.Empty);
text = paragraphEndRegex.Replace(text, "\n");
text = text.Replace("\r\n", "\n").Replace("\r", "\n");
text = text + "\n\n";
text = text.Replace("\n\n", "\n");
var strArray = text.Split(new char[] { '\n' });
var builder = new StringBuilder();
foreach (string str in strArray)
{
if ((str != null) && (str.Trim().Length > 0))
{
builder.AppendFormat("<p>{0}</p>\n", str);
}
}
return builder.ToString();
}
#endregion
}
}