markdown.go 12 KB

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