You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

markdown.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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]{40}\b`)
  77. )
  78. // Renderer is a extended version of underlying render object.
  79. type Renderer struct {
  80. blackfriday.Renderer
  81. urlPrefix string
  82. }
  83. // Link defines how formal links should be processed to produce corresponding HTML elements.
  84. func (r *Renderer) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
  85. if len(link) > 0 && !isLink(link) {
  86. if link[0] != '#' {
  87. link = []byte(path.Join(r.urlPrefix, string(link)))
  88. }
  89. }
  90. r.Renderer.Link(out, link, title, content)
  91. }
  92. // AutoLink defines how auto-detected links should be processed to produce corresponding HTML elements.
  93. // Reference for kind: https://github.com/russross/blackfriday/blob/master/markdown.go#L69-L76
  94. func (r *Renderer) AutoLink(out *bytes.Buffer, link []byte, kind int) {
  95. if kind != blackfriday.LINK_TYPE_NORMAL {
  96. r.Renderer.AutoLink(out, link, kind)
  97. return
  98. }
  99. // Since this method could only possibly serve one link at a time,
  100. // we do not need to find all.
  101. m := CommitPattern.Find(link)
  102. if m != nil {
  103. m = bytes.TrimSpace(m)
  104. i := strings.Index(string(m), "commit/")
  105. j := strings.Index(string(m), "#")
  106. if j == -1 {
  107. j = len(m)
  108. }
  109. out.WriteString(fmt.Sprintf(` <code><a href="%s">%s</a></code>`, m, base.ShortSha(string(m[i+7:j]))))
  110. return
  111. }
  112. m = IssueFullPattern.Find(link)
  113. if m != nil {
  114. m = bytes.TrimSpace(m)
  115. i := strings.Index(string(m), "issues/")
  116. j := strings.Index(string(m), "#")
  117. if j == -1 {
  118. j = len(m)
  119. }
  120. out.WriteString(fmt.Sprintf(` <a href="%s">#%s</a>`, m, base.ShortSha(string(m[i+7:j]))))
  121. return
  122. }
  123. r.Renderer.AutoLink(out, link, kind)
  124. }
  125. // ListItem defines how list items should be processed to produce corresponding HTML elements.
  126. func (options *Renderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
  127. // Detect procedures to draw checkboxes.
  128. switch {
  129. case bytes.HasPrefix(text, []byte("[ ] ")):
  130. text = append([]byte(`<input type="checkbox" disabled="" />`), text[3:]...)
  131. case bytes.HasPrefix(text, []byte("[x] ")):
  132. text = append([]byte(`<input type="checkbox" disabled="" checked="" />`), text[3:]...)
  133. }
  134. options.Renderer.ListItem(out, text, flags)
  135. }
  136. // Note: this section is for purpose of increase performance and
  137. // reduce memory allocation at runtime since they are constant literals.
  138. var (
  139. svgSuffix = []byte(".svg")
  140. svgSuffixWithMark = []byte(".svg?")
  141. spaceBytes = []byte(" ")
  142. spaceEncodedBytes = []byte("%20")
  143. space = " "
  144. spaceEncoded = "%20"
  145. )
  146. // Image defines how images should be processed to produce corresponding HTML elements.
  147. func (r *Renderer) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
  148. prefix := strings.Replace(r.urlPrefix, "/src/", "/raw/", 1)
  149. if len(link) > 0 {
  150. if isLink(link) {
  151. // External link with .svg suffix usually means CI status.
  152. // TODO: define a keyword to allow non-svg images render as external link.
  153. if bytes.HasSuffix(link, svgSuffix) || bytes.Contains(link, svgSuffixWithMark) {
  154. r.Renderer.Image(out, link, title, alt)
  155. return
  156. }
  157. } else {
  158. if link[0] != '/' {
  159. prefix += "/"
  160. }
  161. link = bytes.Replace([]byte((prefix + string(link))), spaceBytes, spaceEncodedBytes, -1)
  162. fmt.Println(333, string(link))
  163. }
  164. }
  165. out.WriteString(`<a href="`)
  166. out.Write(link)
  167. out.WriteString(`">`)
  168. r.Renderer.Image(out, link, title, alt)
  169. out.WriteString("</a>")
  170. }
  171. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  172. // return a clean unified string of request URL path.
  173. func cutoutVerbosePrefix(prefix string) string {
  174. count := 0
  175. for i := 0; i < len(prefix); i++ {
  176. if prefix[i] == '/' {
  177. count++
  178. }
  179. if count >= 3+setting.AppSubUrlDepth {
  180. return prefix[:i]
  181. }
  182. }
  183. return prefix
  184. }
  185. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  186. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  187. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  188. pattern := IssueNumericPattern
  189. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  190. pattern = IssueAlphanumericPattern
  191. }
  192. ms := pattern.FindAll(rawBytes, -1)
  193. for _, m := range ms {
  194. if m[0] == ' ' || m[0] == '(' {
  195. m = m[1:] // ignore leading space or opening parentheses
  196. }
  197. var link string
  198. if metas == nil {
  199. link = fmt.Sprintf(`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)
  200. } else {
  201. // Support for external issue tracker
  202. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  203. metas["index"] = string(m)
  204. } else {
  205. metas["index"] = string(m[1:])
  206. }
  207. link = fmt.Sprintf(`<a href="%s">%s</a>`, com.Expand(metas["format"], metas), m)
  208. }
  209. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  210. }
  211. return rawBytes
  212. }
  213. // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  214. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  215. ms := Sha1CurrentPattern.FindAll(rawBytes, -1)
  216. for _, m := range ms {
  217. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  218. `<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, base.ShortSha(string(m)))), -1)
  219. }
  220. return rawBytes
  221. }
  222. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  223. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  224. ms := MentionPattern.FindAll(rawBytes, -1)
  225. for _, m := range ms {
  226. m = bytes.TrimSpace(m)
  227. rawBytes = bytes.Replace(rawBytes, m,
  228. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  229. }
  230. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  231. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  232. return rawBytes
  233. }
  234. // RenderRaw renders Markdown to HTML without handling special links.
  235. func RenderRaw(body []byte, urlPrefix string) []byte {
  236. htmlFlags := 0
  237. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  238. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  239. renderer := &Renderer{
  240. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  241. urlPrefix: urlPrefix,
  242. }
  243. // set up the parser
  244. extensions := 0
  245. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  246. extensions |= blackfriday.EXTENSION_TABLES
  247. extensions |= blackfriday.EXTENSION_FENCED_CODE
  248. extensions |= blackfriday.EXTENSION_AUTOLINK
  249. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  250. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  251. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  252. if setting.Markdown.EnableHardLineBreak {
  253. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  254. }
  255. body = blackfriday.Markdown(body, renderer, extensions)
  256. return body
  257. }
  258. var (
  259. leftAngleBracket = []byte("</")
  260. rightAngleBracket = []byte(">")
  261. )
  262. var noEndTags = []string{"img", "input", "br", "hr"}
  263. // PostProcess treats different types of HTML differently,
  264. // and only renders special links for plain text blocks.
  265. func PostProcess(rawHtml []byte, urlPrefix string, metas map[string]string) []byte {
  266. startTags := make([]string, 0, 5)
  267. var buf bytes.Buffer
  268. tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml))
  269. OUTER_LOOP:
  270. for html.ErrorToken != tokenizer.Next() {
  271. token := tokenizer.Token()
  272. switch token.Type {
  273. case html.TextToken:
  274. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  275. case html.StartTagToken:
  276. buf.WriteString(token.String())
  277. tagName := token.Data
  278. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  279. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  280. stackNum := 1
  281. for html.ErrorToken != tokenizer.Next() {
  282. token = tokenizer.Token()
  283. // Copy the token to the output verbatim
  284. buf.WriteString(token.String())
  285. if token.Type == html.StartTagToken {
  286. stackNum++
  287. }
  288. // If this is the close tag to the outer-most, we are done
  289. if token.Type == html.EndTagToken {
  290. stackNum--
  291. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  292. break
  293. }
  294. }
  295. }
  296. continue OUTER_LOOP
  297. }
  298. if !com.IsSliceContainsStr(noEndTags, token.Data) {
  299. startTags = append(startTags, token.Data)
  300. }
  301. case html.EndTagToken:
  302. if len(startTags) == 0 {
  303. buf.WriteString(token.String())
  304. break
  305. }
  306. buf.Write(leftAngleBracket)
  307. buf.WriteString(startTags[len(startTags)-1])
  308. buf.Write(rightAngleBracket)
  309. startTags = startTags[:len(startTags)-1]
  310. default:
  311. buf.WriteString(token.String())
  312. }
  313. }
  314. if io.EOF == tokenizer.Err() {
  315. return buf.Bytes()
  316. }
  317. // If we are not at the end of the input, then some other parsing error has occurred,
  318. // so return the input verbatim.
  319. return rawHtml
  320. }
  321. // Render renders Markdown to HTML with special links.
  322. func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  323. urlPrefix = strings.Replace(urlPrefix, space, spaceEncoded, -1)
  324. result := RenderRaw(rawBytes, urlPrefix)
  325. result = PostProcess(result, urlPrefix, metas)
  326. result = Sanitizer.SanitizeBytes(result)
  327. return result
  328. }
  329. // RenderString renders Markdown to HTML with special links and returns string type.
  330. func RenderString(raw, urlPrefix string, metas map[string]string) string {
  331. return string(Render([]byte(raw), urlPrefix, metas))
  332. }