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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
|
public class NHtmlFilter { protected static readonly RegexOptions REGEX_FLAGS_SI = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled;
private static string P_COMMENTS = "<!--(.*?)-->"; private static Regex P_COMMENT = new Regex("^!--(.*)--$", REGEX_FLAGS_SI); private static string P_TAGS = "<(.*?)>"; private static Regex P_END_TAG = new Regex("^/([a-z0-9]+)", REGEX_FLAGS_SI); private static Regex P_START_TAG = new Regex("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); private static Regex P_QUOTED_ATTRIBUTES = new Regex("([a-z0-9|(a-z0-9\\-a-z0-9)]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); private static Regex P_UNQUOTED_ATTRIBUTES = new Regex("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); private static Regex P_PROTOCOL = new Regex("^([^:]+):", REGEX_FLAGS_SI); private static Regex P_ENTITY = new Regex("&#(\\d+);?"); private static Regex P_ENTITY_UNICODE = new Regex("&#x([0-9a-f]+);?"); private static Regex P_ENCODE = new Regex("%([0-9a-f]{2});?"); private static Regex P_VALID_ENTITIES = new Regex("&([^&;]*)(?=(;|&|$))"); private static Regex P_VALID_QUOTES = new Regex("(>|^)([^<]+?)(<|$)", RegexOptions.Singleline | RegexOptions.Compiled); private static string P_END_ARROW = "^>"; private static string P_BODY_TO_END = "<([^>]*?)(?=<|$)"; private static string P_XML_CONTENT = "(^|>)([^<]*?)(?=>)"; private static string P_STRAY_LEFT_ARROW = "<([^>]*?)(?=<|$)"; private static string P_STRAY_RIGHT_ARROW = "(^|>)([^<]*?)(?=>)"; private static string P_AMP = "&"; private static string P_QUOTE = "\""; private static string P_LEFT_ARROW = "<"; private static string P_RIGHT_ARROW = ">"; private static string P_BOTH_ARROWS = "<>";
private static Dictionary<string, string> P_REMOVE_PAIR_BLANKS = new Dictionary<string, string>(); private static Dictionary<string, string> P_REMOVE_SELF_BLANKS = new Dictionary<string, string>();
protected static bool alwaysMakeTags = true;
protected static bool stripComment = true;
private string[] vDisallowed { get; set; } protected Dictionary<string, List<string>> vAllowed { get; set; }
protected Dictionary<string, int> vTagCounts;
protected string[] vSelfClosingTags;
protected string[] vNeedClosingTags;
protected string[] vProtocolAtts;
protected string[] vAllowedProtocols;
protected string[] vRemoveBlanks;
protected string[] vAllowedEntities;
protected bool vDebug;
public NHtmlFilter() : this(false) { }
public NHtmlFilter(bool debug) { vAllowed = new Dictionary<string, List<string>>(); #region 允许通过数组
vAllowed.Add("a", new List<string>() { "target", "href", "title", "class", "style" }); vAllowed.Add("addr", new List<string>() { "title", "class", "style" }); vAllowed.Add("address", new List<string>() { "class", "style" }); vAllowed.Add("area", new List<string>() { "shape", "coords", "href", "alt" }); vAllowed.Add("article", new List<string>() { }); vAllowed.Add("aside", new List<string>() { }); vAllowed.Add("audio", new List<string>() { "autoplay", "controls", "loop", "preload", "src", "class", "style" }); vAllowed.Add("b", new List<string>() { "class", "style" }); vAllowed.Add("bdi", new List<string>() { "dir" }); vAllowed.Add("bdo", new List<string>() { "dir" }); vAllowed.Add("big", new List<string>() { }); vAllowed.Add("blockquote", new List<string>() { "cite", "class", "style" }); vAllowed.Add("br", new List<string>() { }); vAllowed.Add("caption", new List<string>() { "class", "style" }); vAllowed.Add("center", new List<string>() { }); vAllowed.Add("cite", new List<string>() { }); vAllowed.Add("code", new List<string>() { "class", "style" }); vAllowed.Add("col", new List<string>() { "align", "valign", "span", "width", "class", "style" }); vAllowed.Add("colgroup", new List<string>() { "align", "valign", "span", "width", "class", "style" }); vAllowed.Add("dd", new List<string>() { "class", "style" }); vAllowed.Add("del", new List<string>() { "datetime" }); vAllowed.Add("details", new List<string>() { "open" }); vAllowed.Add("div", new List<string>() { "class", "style" }); vAllowed.Add("dl", new List<string>() { "class", "style" }); vAllowed.Add("dt", new List<string>() { "class", "style" }); vAllowed.Add("em", new List<string>() { "class", "style" }); vAllowed.Add("font", new List<string>() { "color", "size", "face" }); vAllowed.Add("footer", new List<string>() { }); vAllowed.Add("h1", new List<string>() { "class", "style" }); vAllowed.Add("h2", new List<string>() { "class", "style" }); vAllowed.Add("h3", new List<string>() { "class", "style" }); vAllowed.Add("h4", new List<string>() { "class", "style" }); vAllowed.Add("h5", new List<string>() { "class", "style" }); vAllowed.Add("h6", new List<string>() { "class", "style" }); vAllowed.Add("header", new List<string>() { }); vAllowed.Add("hr", new List<string>() { }); vAllowed.Add("i", new List<string>() { "class", "style" }); vAllowed.Add("img", new List<string>() { "src", "alt", "title", "style", "width", "height", "id", "_src", "loadingclass", "class", "data-latex", "data-id", "data-type", "data-s" }); vAllowed.Add("ins", new List<string>() { "datetime" }); vAllowed.Add("li", new List<string>() { "class", "style" }); vAllowed.Add("mark", new List<string>() { }); vAllowed.Add("nav", new List<string>() { }); vAllowed.Add("ol", new List<string>() { "class", "style" }); vAllowed.Add("p", new List<string>() { "class", "style" }); vAllowed.Add("pre", new List<string>() { "class", "style" }); vAllowed.Add("s", new List<string>() { }); vAllowed.Add("section", new List<string>() { }); vAllowed.Add("small", new List<string>() { }); vAllowed.Add("span", new List<string>() { "class", "style" }); vAllowed.Add("sub", new List<string>() { "class", "style" }); vAllowed.Add("sup", new List<string>() { "class", "style" }); vAllowed.Add("strong", new List<string>() { "class", "style" }); vAllowed.Add("table", new List<string>() { "width", "border", "align", "valign", "class", "style" }); vAllowed.Add("tbody", new List<string>() { "align", "valign", "class", "style" }); vAllowed.Add("td", new List<string>() { "width", "rowspan", "colspan", "align", "valign", "class", "style" }); vAllowed.Add("tfoot", new List<string>() { "align", "valign", "class", "style" }); vAllowed.Add("th", new List<string>() { "width", "rowspan", "colspan", "align", "valign", "class", "style" }); vAllowed.Add("thead", new List<string>() { "align", "valign", "class", "style" }); vAllowed.Add("tr", new List<string>() { "rowspan", "align", "valign", "class", "style" }); vAllowed.Add("tt", new List<string>() { }); vAllowed.Add("u", new List<string>() { }); vAllowed.Add("ul", new List<string>() { "class", "style" }); vAllowed.Add("video", new List<string>() { "autoplay", "controls", "loop", "preload", "src", "height", "width", "class", "style" }); #endregion
vDebug = debug; vTagCounts = new Dictionary<string, int>();
vSelfClosingTags = new string[] { "img" }; vNeedClosingTags = new string[] { "a", "b", "strong", "i", "em" }; vDisallowed = new string[] { "script" }; vAllowedProtocols = new string[] { "http", "mailto" }; vProtocolAtts = new string[] { "src", "href" }; vRemoveBlanks = new string[] { "a", "b", "strong", "i", "em" }; vAllowedEntities = new string[] { "amp", "gt", "lt", "quot" }; stripComment = true; alwaysMakeTags = true; }
protected void reset() { vTagCounts = new Dictionary<string, int>(); }
protected void debug(string msg) { if (vDebug) System.Diagnostics.Debug.WriteLine(msg); }
public static string chr(int dec) { return "" + (char)dec; }
public static string htmlSpecialChars(string str) { str = str.Replace(P_QUOTE, "\"");
str = str.Replace(P_LEFT_ARROW, "<"); str = str.Replace(P_RIGHT_ARROW, ">"); str = str.Replace("\n", "<br>"); return str; }
public string filter(string input) { reset(); string s = input;
debug("************************************************"); debug(" INPUT: " + input);
s = escapeComments(s); debug(" escapeComments: " + s);
s = balanceHTML(s); debug(" balanceHTML: " + s);
s = checkTags(s); debug(" checkTags: " + s);
s = processRemoveBlanks(s); debug("processRemoveBlanks: " + s);
s = validateEntities(s); debug(" validateEntites: " + s);
debug("************************************************\n\n"); return s; }
protected string escapeComments(string s) { return Regex.Replace(s, P_COMMENTS, new MatchEvaluator(ConverMatchComments), RegexOptions.Singleline); }
protected string regexReplace(string regex_pattern, string replacement, string s) { return Regex.Replace(s, regex_pattern, replacement); }
protected string balanceHTML(string s) { if (alwaysMakeTags) { s = regexReplace(P_END_ARROW, "", s); s = regexReplace(P_BODY_TO_END, "<$1>", s); s = regexReplace(P_XML_CONTENT, "$1<$2", s);
} else { s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s);
s = s.Replace(P_BOTH_ARROWS, ""); } return s; }
protected string checkTags(string s) { foreach (var item in vDisallowed) { s = Regex.Replace(s, string.Format(@"<{0}\b(.)*?>(.)+?</{0}>", item), ""); } s = Regex.Replace(s, P_TAGS, new MatchEvaluator(ConverMatchTags), RegexOptions.Singleline);
foreach (string key in vTagCounts.Keys) { for (int ii = 0; ii < vTagCounts[key]; ii++) { s += "</" + key + ">"; } }
return s; }
protected string processRemoveBlanks(string s) { foreach (string tag in vRemoveBlanks) { s = regexReplace("<" + tag + "(\\s[^>]*)?></" + tag + ">", "", s); s = regexReplace("<" + tag + "(\\s[^>]*)?/>", "", s); } return s; }
private string processTag(string s) { Match m = P_END_TAG.Match(s); if (m.Success) { string name = m.Groups[1].Value.ToLower(); if (allowed(name)) { if (!inArray(name, vSelfClosingTags)) { if (vTagCounts.ContainsKey(name)) { vTagCounts[name] = vTagCounts[name] - 1; return "</" + name + ">"; } } } }
m = P_START_TAG.Match(s); if (m.Success) { string name = m.Groups[1].Value.ToLower(); string body = m.Groups[2].Value; string ending = m.Groups[3].Value;
if (allowed(name)) { string params1 = "";
MatchCollection m2 = P_QUOTED_ATTRIBUTES.Matches(body); MatchCollection m3 = P_UNQUOTED_ATTRIBUTES.Matches(body); List<string> paramNames = new List<string>(); List<string> paramValues = new List<string>(); foreach (Match match in m2) { paramNames.Add(match.Groups[1].Value); paramValues.Add(match.Groups[3].Value); } foreach (Match match in m3) { paramNames.Add(match.Groups[1].Value); paramValues.Add(match.Groups[3].Value); }
string paramName, paramValue; for (int ii = 0; ii < paramNames.Count; ii++) { paramName = paramNames[ii].ToLower(); paramValue = paramValues[ii];
if (allowedAttribute(name, paramName)) { if (inArray(paramName, vProtocolAtts)) { paramValue = processParamProtocol(paramValue); } params1 += " " + paramName + "=\"" + paramValue + "\""; } }
if (inArray(name, vSelfClosingTags)) { ending = " /"; }
if (inArray(name, vNeedClosingTags)) { ending = ""; }
if (ending == null || ending.Length < 1) { if (vTagCounts.ContainsKey(name)) { vTagCounts[name] = vTagCounts[name] + 1; } else { vTagCounts.Add(name, 1); } } else { ending = " /"; } return "<" + name + params1 + ending + ">"; } else { return ""; } }
m = P_COMMENT.Match(s); if (!stripComment && m.Success) { return "<" + m.Value + ">"; }
return ""; }
private string processParamProtocol(string s) { s = decodeEntities(s); Match m = P_PROTOCOL.Match(s); if (m.Success) { string protocol = m.Groups[1].Value; if (!inArray(protocol, vAllowedProtocols)) { s = "#" + s.Substring(protocol.Length + 1, s.Length - protocol.Length - 1); if (s.StartsWith("#//")) { s = "#" + s.Substring(3, s.Length - 3); } } } return s; }
private string decodeEntities(string s) {
s = P_ENTITY.Replace(s, new MatchEvaluator(ConverMatchEntity));
s = P_ENTITY_UNICODE.Replace(s, new MatchEvaluator(ConverMatchEntityUnicode));
s = P_ENCODE.Replace(s, new MatchEvaluator(ConverMatchEntityUnicode));
s = validateEntities(s); return s; }
private string validateEntities(string s) { s = P_VALID_ENTITIES.Replace(s, new MatchEvaluator(ConverMatchValidEntities)); s = P_VALID_QUOTES.Replace(s, new MatchEvaluator(ConverMatchValidQuotes)); return s; }
private static bool inArray(string s, string[] array) { foreach (string item in array) { if (item != null && item.Equals(s)) { return true; } } return false; }
private bool allowed(string name) { return (vAllowed.Count == 0 || vAllowed.ContainsKey(name)) && !inArray(name, vDisallowed); }
private bool allowedAttribute(string name, string paramName) { return allowed(name) && (vAllowed.Count == 0 || vAllowed[name].Contains(paramName)); }
private string checkEntity(string preamble, string term) {
return ";".Equals(term) && isValidEntity(preamble) ? '&' + preamble : "&" + preamble; } private bool isValidEntity(string entity) { return inArray(entity, vAllowedEntities); } private static string ConverMatchComments(Match match) { string matchValue = "<!--" + htmlSpecialChars(match.Groups[1].Value) + "-->"; return matchValue; }
private string ConverMatchTags(Match match) { string matchValue = processTag(match.Groups[1].Value); return matchValue; }
private string ConverMatchEntity(Match match) { string v = match.Groups[1].Value; int decimal1 = int.Parse(v); return chr(decimal1); }
private string ConverMatchEntityUnicode(Match match) { string v = match.Groups[1].Value; int decimal1 = Convert.ToInt32("0x" + v, 16); return chr(decimal1); }
private string ConverMatchValidEntities(Match match) { string one = match.Groups[1].Value; string two = match.Groups[2].Value; return checkEntity(one, two); } private string ConverMatchValidQuotes(Match match) { string one = match.Groups[1].Value; string two = match.Groups[2].Value; string three = match.Groups[3].Value; return one + regexReplace(P_QUOTE, "\"", two) + three; }
public bool isAlwaysMakeTags() { return alwaysMakeTags; }
public bool isStripComments() { return stripComment; }
class Item { public string name { get; set; } public List<string> parameter { get; set; } }
}
|