forked from Automattic/wpgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanitize.go
74 lines (61 loc) · 2.19 KB
/
sanitize.go
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
package main
import (
"bytes"
"html/template"
"strings"
)
// From: https://github.com/kennygrant/sanitize
// Strip html tags, replace common entities, and escape <>&;'" in the result.
// Note the returned text may contain entities as it is escaped by HTMLEscapeString,
// and most entities are not translated.
func scrub_html(s string) (output string) {
output = ""
// Shortcut strings with no tags in them
if !strings.ContainsAny(s, "<>") {
output = s
} else {
// First remove line breaks etc as these have no meaning outside html tags (except pre)
// this means pre sections will lose formatting... but will result in less uninentional paras.
s = strings.Replace(s, "\n", "", -1)
// Then replace line breaks with newlines, to preserve that formatting
s = strings.Replace(s, "</p>", "\n\n", -1)
s = strings.Replace(s, "<br>", "\n", -1)
s = strings.Replace(s, "</br>", "\n", -1)
s = strings.Replace(s, "<br/>", "\n", -1)
// Walk through the string removing all tags
b := bytes.NewBufferString("")
inTag := false
for _, r := range s {
switch r {
case '<':
inTag = true
case '>':
inTag = false
default:
if !inTag {
b.WriteRune(r)
}
}
}
output = b.String()
}
// remove lame things
// fix for "smart" quotes
output = strings.Replace(output, "‘", "'", -1)
output = strings.Replace(output, "’", "'", -1)
output = strings.Replace(output, "“", "\"", -1)
output = strings.Replace(output, "”", "\"", -1)
// In case we have missed any tags above, escape the text - removes <, >, &, ' and ".
output = template.HTMLEscapeString(output)
// Remove a few common harmless entities, to arrive at something more like plain text
// This relies on having removed *all* tags above
output = strings.Replace(output, " ", " ", -1)
output = strings.Replace(output, """, "\"", -1)
output = strings.Replace(output, "'", "'", -1)
output = strings.Replace(output, """, "\"", -1)
output = strings.Replace(output, "'", "'", -1)
// NB spaces here are significant - we only allow & not part of entity
output = strings.Replace(output, "& ", "& ", -1)
output = strings.Replace(output, "&amp; ", "& ", -1)
return output
}