markdown.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. space = " "
  138. spaceEncoded = "%20"
  139. )
  140. // Image defines how images should be processed to produce corresponding HTML elements.
  141. func (r *Renderer) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
  142. prefix := strings.Replace(r.urlPrefix, "/src/", "/raw/", 1)
  143. if len(link) > 0 {
  144. if isLink(link) {
  145. // External link with .svg suffix usually means CI status.
  146. // TODO: define a keyword to allow non-svg images render as external link.
  147. if bytes.HasSuffix(link, svgSuffix) || bytes.Contains(link, svgSuffixWithMark) {
  148. r.Renderer.Image(out, link, title, alt)
  149. return
  150. }
  151. } else {
  152. if link[0] != '/' {
  153. prefix += "/"
  154. }
  155. link = bytes.Replace([]byte((prefix + string(link))), spaceBytes, spaceEncodedBytes, -1)
  156. fmt.Println(333, string(link))
  157. }
  158. }
  159. out.WriteString(`<a href="`)
  160. out.Write(link)
  161. out.WriteString(`">`)
  162. r.Renderer.Image(out, link, title, alt)
  163. out.WriteString("</a>")
  164. }
  165. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  166. // return a clean unified string of request URL path.
  167. func cutoutVerbosePrefix(prefix string) string {
  168. count := 0
  169. for i := 0; i < len(prefix); i++ {
  170. if prefix[i] == '/' {
  171. count++
  172. }
  173. if count >= 3+setting.AppSubUrlDepth {
  174. return prefix[:i]
  175. }
  176. }
  177. return prefix
  178. }
  179. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  180. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  181. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  182. ms := IssueIndexPattern.FindAll(rawBytes, -1)
  183. for _, m := range ms {
  184. var space string
  185. if m[0] != '#' {
  186. space = string(m[0])
  187. m = m[1:]
  188. }
  189. if metas == nil {
  190. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s/issues/%s">%s</a>`,
  191. space, urlPrefix, m[1:], m)), 1)
  192. } else {
  193. // Support for external issue tracker
  194. metas["index"] = string(m[1:])
  195. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s">%s</a>`,
  196. space, com.Expand(metas["format"], metas), m)), 1)
  197. }
  198. }
  199. return rawBytes
  200. }
  201. // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  202. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  203. ms := Sha1CurrentPattern.FindAll(rawBytes, -1)
  204. for _, m := range ms {
  205. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  206. `<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, base.ShortSha(string(m)))), -1)
  207. }
  208. return rawBytes
  209. }
  210. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  211. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  212. ms := MentionPattern.FindAll(rawBytes, -1)
  213. for _, m := range ms {
  214. m = bytes.TrimSpace(m)
  215. rawBytes = bytes.Replace(rawBytes, m,
  216. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  217. }
  218. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  219. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  220. return rawBytes
  221. }
  222. // RenderRaw renders Markdown to HTML without handling special links.
  223. func RenderRaw(body []byte, urlPrefix string) []byte {
  224. htmlFlags := 0
  225. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  226. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  227. renderer := &Renderer{
  228. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  229. urlPrefix: urlPrefix,
  230. }
  231. // set up the parser
  232. extensions := 0
  233. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  234. extensions |= blackfriday.EXTENSION_TABLES
  235. extensions |= blackfriday.EXTENSION_FENCED_CODE
  236. extensions |= blackfriday.EXTENSION_AUTOLINK
  237. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  238. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  239. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  240. if setting.Markdown.EnableHardLineBreak {
  241. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  242. }
  243. body = blackfriday.Markdown(body, renderer, extensions)
  244. return body
  245. }
  246. var (
  247. leftAngleBracket = []byte("</")
  248. rightAngleBracket = []byte(">")
  249. )
  250. var noEndTags = []string{"img", "input", "br", "hr"}
  251. // PostProcess treats different types of HTML differently,
  252. // and only renders special links for plain text blocks.
  253. func PostProcess(rawHtml []byte, urlPrefix string, metas map[string]string) []byte {
  254. startTags := make([]string, 0, 5)
  255. var buf bytes.Buffer
  256. tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml))
  257. OUTER_LOOP:
  258. for html.ErrorToken != tokenizer.Next() {
  259. token := tokenizer.Token()
  260. switch token.Type {
  261. case html.TextToken:
  262. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  263. case html.StartTagToken:
  264. buf.WriteString(token.String())
  265. tagName := token.Data
  266. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  267. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  268. stackNum := 1
  269. for html.ErrorToken != tokenizer.Next() {
  270. token = tokenizer.Token()
  271. // Copy the token to the output verbatim
  272. buf.WriteString(token.String())
  273. if token.Type == html.StartTagToken {
  274. stackNum++
  275. }
  276. // If this is the close tag to the outer-most, we are done
  277. if token.Type == html.EndTagToken {
  278. stackNum--
  279. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  280. break
  281. }
  282. }
  283. }
  284. continue OUTER_LOOP
  285. }
  286. if !com.IsSliceContainsStr(noEndTags, token.Data) {
  287. startTags = append(startTags, token.Data)
  288. }
  289. case html.EndTagToken:
  290. if len(startTags) == 0 {
  291. buf.WriteString(token.String())
  292. break
  293. }
  294. buf.Write(leftAngleBracket)
  295. buf.WriteString(startTags[len(startTags)-1])
  296. buf.Write(rightAngleBracket)
  297. startTags = startTags[:len(startTags)-1]
  298. default:
  299. buf.WriteString(token.String())
  300. }
  301. }
  302. if io.EOF == tokenizer.Err() {
  303. return buf.Bytes()
  304. }
  305. // If we are not at the end of the input, then some other parsing error has occurred,
  306. // so return the input verbatim.
  307. return rawHtml
  308. }
  309. // Render renders Markdown to HTML with special links.
  310. func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  311. urlPrefix = strings.Replace(urlPrefix, space, spaceEncoded, -1)
  312. result := RenderRaw(rawBytes, urlPrefix)
  313. result = PostProcess(result, urlPrefix, metas)
  314. result = Sanitizer.SanitizeBytes(result)
  315. return result
  316. }
  317. // RenderString renders Markdown to HTML with special links and returns string type.
  318. func RenderString(raw, urlPrefix string, metas map[string]string) string {
  319. return string(Render([]byte(raw), urlPrefix, metas))
  320. }