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.

402 lines
12 KiB

10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  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. // 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. ms := Sha1CurrentPattern.FindAll(rawBytes, -1)
  230. for _, m := range ms {
  231. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  232. `<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, base.ShortSha(string(m)))), -1)
  233. }
  234. return rawBytes
  235. }
  236. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  237. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  238. ms := MentionPattern.FindAll(rawBytes, -1)
  239. for _, m := range ms {
  240. m = bytes.TrimSpace(m)
  241. rawBytes = bytes.Replace(rawBytes, m,
  242. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  243. }
  244. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  245. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  246. return rawBytes
  247. }
  248. // RenderRaw renders Markdown to HTML without handling special links.
  249. func RenderRaw(body []byte, urlPrefix string) []byte {
  250. htmlFlags := 0
  251. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  252. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  253. renderer := &Renderer{
  254. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  255. urlPrefix: urlPrefix,
  256. }
  257. // set up the parser
  258. extensions := 0
  259. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  260. extensions |= blackfriday.EXTENSION_TABLES
  261. extensions |= blackfriday.EXTENSION_FENCED_CODE
  262. extensions |= blackfriday.EXTENSION_AUTOLINK
  263. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  264. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  265. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  266. if setting.Markdown.EnableHardLineBreak {
  267. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  268. }
  269. body = blackfriday.Markdown(body, renderer, extensions)
  270. return body
  271. }
  272. var (
  273. leftAngleBracket = []byte("</")
  274. rightAngleBracket = []byte(">")
  275. )
  276. var noEndTags = []string{"img", "input", "br", "hr"}
  277. // PostProcess treats different types of HTML differently,
  278. // and only renders special links for plain text blocks.
  279. func PostProcess(rawHtml []byte, urlPrefix string, metas map[string]string) []byte {
  280. startTags := make([]string, 0, 5)
  281. var buf bytes.Buffer
  282. tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml))
  283. OUTER_LOOP:
  284. for html.ErrorToken != tokenizer.Next() {
  285. token := tokenizer.Token()
  286. switch token.Type {
  287. case html.TextToken:
  288. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  289. case html.StartTagToken:
  290. buf.WriteString(token.String())
  291. tagName := token.Data
  292. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  293. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  294. stackNum := 1
  295. for html.ErrorToken != tokenizer.Next() {
  296. token = tokenizer.Token()
  297. // Copy the token to the output verbatim
  298. buf.WriteString(token.String())
  299. if token.Type == html.StartTagToken {
  300. stackNum++
  301. }
  302. // If this is the close tag to the outer-most, we are done
  303. if token.Type == html.EndTagToken {
  304. stackNum--
  305. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  306. break
  307. }
  308. }
  309. }
  310. continue OUTER_LOOP
  311. }
  312. if !com.IsSliceContainsStr(noEndTags, token.Data) {
  313. startTags = append(startTags, token.Data)
  314. }
  315. case html.EndTagToken:
  316. if len(startTags) == 0 {
  317. buf.WriteString(token.String())
  318. break
  319. }
  320. buf.Write(leftAngleBracket)
  321. buf.WriteString(startTags[len(startTags)-1])
  322. buf.Write(rightAngleBracket)
  323. startTags = startTags[:len(startTags)-1]
  324. default:
  325. buf.WriteString(token.String())
  326. }
  327. }
  328. if io.EOF == tokenizer.Err() {
  329. return buf.Bytes()
  330. }
  331. // If we are not at the end of the input, then some other parsing error has occurred,
  332. // so return the input verbatim.
  333. return rawHtml
  334. }
  335. // Render renders Markdown to HTML with special links.
  336. func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  337. urlPrefix = strings.Replace(urlPrefix, space, spaceEncoded, -1)
  338. result := RenderRaw(rawBytes, urlPrefix)
  339. result = PostProcess(result, urlPrefix, metas)
  340. result = Sanitizer.SanitizeBytes(result)
  341. return result
  342. }
  343. // RenderString renders Markdown to HTML with special links and returns string type.
  344. func RenderString(raw, urlPrefix string, metas map[string]string) string {
  345. return string(Render([]byte(raw), urlPrefix, metas))
  346. }