markdown.go 14 KB

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