markdown.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package markdown
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "path"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "github.com/Unknwon/com"
  14. "github.com/microcosm-cc/bluemonday"
  15. "github.com/russross/blackfriday"
  16. "golang.org/x/net/html"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/setting"
  19. )
  20. var Sanitizer = bluemonday.UGCPolicy()
  21. // BuildSanitizer initializes sanitizer with allowed attributes based on settings.
  22. // This function should only be called once during entire application lifecycle.
  23. func BuildSanitizer() {
  24. // Normal markdown-stuff
  25. Sanitizer.AllowAttrs("class").Matching(regexp.MustCompile(`[\p{L}\p{N}\s\-_',:\[\]!\./\\\(\)&]*`)).OnElements("code")
  26. // Checkboxes
  27. Sanitizer.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  28. Sanitizer.AllowAttrs("checked", "disabled").OnElements("input")
  29. // Custom URL-Schemes
  30. Sanitizer.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  31. }
  32. var validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  33. // isLink reports whether link fits valid format.
  34. func isLink(link []byte) bool {
  35. return validLinksPattern.Match(link)
  36. }
  37. // IsMarkdownFile reports whether name looks like a Markdown file
  38. // based on its extension.
  39. func IsMarkdownFile(name string) bool {
  40. name = strings.ToLower(name)
  41. switch filepath.Ext(name) {
  42. case ".md", ".markdown", ".mdown", ".mkd":
  43. return true
  44. }
  45. return false
  46. }
  47. // IsReadmeFile reports whether name looks like a README file
  48. // based on its extension.
  49. func IsReadmeFile(name string) bool {
  50. name = strings.ToLower(name)
  51. if len(name) < 6 {
  52. return false
  53. } else if len(name) == 6 {
  54. return name == "readme"
  55. }
  56. return name[:7] == "readme."
  57. }
  58. var (
  59. // MentionPattern matches string that mentions someone, e.g. @Unknwon
  60. MentionPattern = regexp.MustCompile(`(\s|^)@[0-9a-zA-Z_\.]+`)
  61. // CommitPattern matches link to certain commit with or without trailing hash,
  62. // e.g. https://try.gogs.io/gogs/gogs/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2
  63. CommitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
  64. // IssueFullPattern matches link to an issue with or without trailing hash,
  65. // e.g. https://try.gogs.io/gogs/gogs/issues/4#issue-685
  66. IssueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
  67. // IssueIndexPattern matches string that references to an issue, e.g. #1287
  68. IssueIndexPattern = regexp.MustCompile(`( |^|\()#[0-9]+\b`)
  69. // Sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  70. Sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{40}\b`)
  71. )
  72. // Renderer is a extended version of underlying render object.
  73. type Renderer struct {
  74. blackfriday.Renderer
  75. urlPrefix string
  76. }
  77. // Link defines how formal links should be processed to produce corresponding HTML elements.
  78. func (r *Renderer) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
  79. if len(link) > 0 && !isLink(link) {
  80. if link[0] != '#' {
  81. link = []byte(path.Join(r.urlPrefix, string(link)))
  82. }
  83. }
  84. r.Renderer.Link(out, link, title, content)
  85. }
  86. // AutoLink defines how auto-detected links should be processed to produce corresponding HTML elements.
  87. // Reference for kind: https://github.com/russross/blackfriday/blob/master/markdown.go#L69-L76
  88. func (r *Renderer) AutoLink(out *bytes.Buffer, link []byte, kind int) {
  89. if kind != blackfriday.LINK_TYPE_NORMAL {
  90. r.Renderer.AutoLink(out, link, kind)
  91. return
  92. }
  93. // Since this method could only possibly serve one link at a time,
  94. // we do not need to find all.
  95. m := CommitPattern.Find(link)
  96. if m != nil {
  97. m = bytes.TrimSpace(m)
  98. i := strings.Index(string(m), "commit/")
  99. j := strings.Index(string(m), "#")
  100. if j == -1 {
  101. j = len(m)
  102. }
  103. out.WriteString(fmt.Sprintf(` <code><a href="%s">%s</a></code>`, m, base.ShortSha(string(m[i+7:j]))))
  104. return
  105. }
  106. m = IssueFullPattern.Find(link)
  107. if m != nil {
  108. m = bytes.TrimSpace(m)
  109. i := strings.Index(string(m), "issues/")
  110. j := strings.Index(string(m), "#")
  111. if j == -1 {
  112. j = len(m)
  113. }
  114. out.WriteString(fmt.Sprintf(` <a href="%s">#%s</a>`, m, base.ShortSha(string(m[i+7:j]))))
  115. return
  116. }
  117. r.Renderer.AutoLink(out, link, kind)
  118. }
  119. // ListItem defines how list items should be processed to produce corresponding HTML elements.
  120. func (options *Renderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
  121. // Detect procedures to draw checkboxes.
  122. switch {
  123. case bytes.HasPrefix(text, []byte("[ ] ")):
  124. text = append([]byte(`<input type="checkbox" disabled="" />`), text[3:]...)
  125. case bytes.HasPrefix(text, []byte("[x] ")):
  126. text = append([]byte(`<input type="checkbox" disabled="" checked="" />`), text[3:]...)
  127. }
  128. options.Renderer.ListItem(out, text, flags)
  129. }
  130. // Note: this section is for purpose of increase performance and
  131. // reduce memory allocation at runtime since they are constant literals.
  132. var (
  133. svgSuffix = []byte(".svg")
  134. svgSuffixWithMark = []byte(".svg?")
  135. spaceBytes = []byte(" ")
  136. spaceEncodedBytes = []byte("%20")
  137. )
  138. // Image defines how images should be processed to produce corresponding HTML elements.
  139. func (r *Renderer) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
  140. prefix := strings.Replace(r.urlPrefix, "/src/", "/raw/", 1)
  141. if len(link) > 0 {
  142. if isLink(link) {
  143. // External link with .svg suffix usually means CI status.
  144. // TODO: define a keyword to allow non-svg images render as external link.
  145. if bytes.HasSuffix(link, svgSuffix) || bytes.Contains(link, svgSuffixWithMark) {
  146. r.Renderer.Image(out, link, title, alt)
  147. return
  148. }
  149. } else {
  150. if link[0] != '/' {
  151. prefix += "/"
  152. }
  153. link = bytes.Replace([]byte((prefix + string(link))), spaceBytes, spaceEncodedBytes, -1)
  154. fmt.Println(333, string(link))
  155. }
  156. }
  157. out.WriteString(`<a href="`)
  158. out.Write(link)
  159. out.WriteString(`">`)
  160. r.Renderer.Image(out, link, title, alt)
  161. out.WriteString("</a>")
  162. }
  163. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  164. // return a clean unified string of request URL path.
  165. func cutoutVerbosePrefix(prefix string) string {
  166. count := 0
  167. for i := 0; i < len(prefix); i++ {
  168. if prefix[i] == '/' {
  169. count++
  170. }
  171. if count >= 3+setting.AppSubUrlDepth {
  172. return prefix[:i]
  173. }
  174. }
  175. return prefix
  176. }
  177. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  178. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  179. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  180. ms := IssueIndexPattern.FindAll(rawBytes, -1)
  181. for _, m := range ms {
  182. var space string
  183. if m[0] != '#' {
  184. space = string(m[0])
  185. m = m[1:]
  186. }
  187. if metas == nil {
  188. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s/issues/%s">%s</a>`,
  189. space, urlPrefix, m[1:], m)), 1)
  190. } else {
  191. // Support for external issue tracker
  192. metas["index"] = string(m[1:])
  193. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s">%s</a>`,
  194. space, com.Expand(metas["format"], metas), m)), 1)
  195. }
  196. }
  197. return rawBytes
  198. }
  199. // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  200. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  201. ms := Sha1CurrentPattern.FindAll(rawBytes, -1)
  202. for _, m := range ms {
  203. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  204. `<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, base.ShortSha(string(m)))), -1)
  205. }
  206. return rawBytes
  207. }
  208. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  209. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  210. ms := MentionPattern.FindAll(rawBytes, -1)
  211. for _, m := range ms {
  212. m = bytes.TrimSpace(m)
  213. rawBytes = bytes.Replace(rawBytes, m,
  214. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  215. }
  216. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  217. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  218. return rawBytes
  219. }
  220. // RenderRaw renders Markdown to HTML without handling special links.
  221. func RenderRaw(body []byte, urlPrefix string) []byte {
  222. htmlFlags := 0
  223. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  224. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  225. renderer := &Renderer{
  226. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  227. urlPrefix: urlPrefix,
  228. }
  229. // set up the parser
  230. extensions := 0
  231. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  232. extensions |= blackfriday.EXTENSION_TABLES
  233. extensions |= blackfriday.EXTENSION_FENCED_CODE
  234. extensions |= blackfriday.EXTENSION_AUTOLINK
  235. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  236. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  237. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  238. if setting.Markdown.EnableHardLineBreak {
  239. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  240. }
  241. body = blackfriday.Markdown(body, renderer, extensions)
  242. return body
  243. }
  244. var (
  245. leftAngleBracket = []byte("</")
  246. rightAngleBracket = []byte(">")
  247. )
  248. var noEndTags = []string{"img", "input", "br", "hr"}
  249. // PostProcess treats different types of HTML differently,
  250. // and only renders special links for plain text blocks.
  251. func PostProcess(rawHtml []byte, urlPrefix string, metas map[string]string) []byte {
  252. startTags := make([]string, 0, 5)
  253. var buf bytes.Buffer
  254. tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml))
  255. OUTER_LOOP:
  256. for html.ErrorToken != tokenizer.Next() {
  257. token := tokenizer.Token()
  258. switch token.Type {
  259. case html.TextToken:
  260. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  261. case html.StartTagToken:
  262. buf.WriteString(token.String())
  263. tagName := token.Data
  264. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  265. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  266. stackNum := 1
  267. for html.ErrorToken != tokenizer.Next() {
  268. token = tokenizer.Token()
  269. // Copy the token to the output verbatim
  270. buf.WriteString(token.String())
  271. if token.Type == html.StartTagToken {
  272. stackNum++
  273. }
  274. // If this is the close tag to the outer-most, we are done
  275. if token.Type == html.EndTagToken {
  276. stackNum--
  277. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  278. break
  279. }
  280. }
  281. }
  282. continue OUTER_LOOP
  283. }
  284. if !com.IsSliceContainsStr(noEndTags, token.Data) {
  285. startTags = append(startTags, token.Data)
  286. }
  287. case html.EndTagToken:
  288. if len(startTags) == 0 {
  289. buf.WriteString(token.String())
  290. break
  291. }
  292. buf.Write(leftAngleBracket)
  293. buf.WriteString(startTags[len(startTags)-1])
  294. buf.Write(rightAngleBracket)
  295. startTags = startTags[:len(startTags)-1]
  296. default:
  297. buf.WriteString(token.String())
  298. }
  299. }
  300. if io.EOF == tokenizer.Err() {
  301. return buf.Bytes()
  302. }
  303. // If we are not at the end of the input, then some other parsing error has occurred,
  304. // so return the input verbatim.
  305. return rawHtml
  306. }
  307. // Render renders Markdown to HTML with special links.
  308. func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  309. result := RenderRaw(rawBytes, urlPrefix)
  310. result = PostProcess(result, urlPrefix, metas)
  311. result = Sanitizer.SanitizeBytes(result)
  312. return result
  313. }
  314. // RenderString renders Markdown to HTML with special links and returns string type.
  315. func RenderString(raw, urlPrefix string, metas map[string]string) string {
  316. return string(Render([]byte(raw), urlPrefix, metas))
  317. }