markdown.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. pound = []byte("#")
  168. space = " "
  169. spaceEncoded = "%20"
  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. if len(prefix) == 0 || prefix[0] != '/' {
  175. return prefix
  176. }
  177. count := 0
  178. for i := 0; i < len(prefix); i++ {
  179. if prefix[i] == '/' {
  180. count++
  181. }
  182. if count >= 3+setting.AppSubUrlDepth {
  183. return prefix[:i]
  184. }
  185. }
  186. return prefix
  187. }
  188. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  189. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  190. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  191. pattern := IssueNumericPattern
  192. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  193. pattern = IssueAlphanumericPattern
  194. }
  195. ms := pattern.FindAll(rawBytes, -1)
  196. for _, m := range ms {
  197. if m[0] == ' ' || m[0] == '(' {
  198. m = m[1:] // ignore leading space or opening parentheses
  199. }
  200. var link string
  201. if metas == nil {
  202. link = fmt.Sprintf(`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)
  203. } else {
  204. // Support for external issue tracker
  205. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  206. metas["index"] = string(m)
  207. } else {
  208. metas["index"] = string(m[1:])
  209. }
  210. link = fmt.Sprintf(`<a href="%s">%s</a>`, com.Expand(metas["format"], metas), m)
  211. }
  212. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  213. }
  214. return rawBytes
  215. }
  216. // RenderCrossReferenceIssueIndexPattern renders issue indexes from other repositories to corresponding links.
  217. func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  218. ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
  219. for _, m := range ms {
  220. if m[0] == ' ' || m[0] == '(' {
  221. m = m[1:] // ignore leading space or opening parentheses
  222. }
  223. delimIdx := bytes.Index(m, pound)
  224. repo := string(m[:delimIdx])
  225. index := string(m[delimIdx+1:])
  226. link := fmt.Sprintf(`<a href="%s%s/issues/%s">%s</a>`, setting.AppUrl, repo, index, m)
  227. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  228. }
  229. return rawBytes
  230. }
  231. // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  232. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  233. return []byte(Sha1CurrentPattern.ReplaceAllStringFunc(string(rawBytes[:]), func(m string) string {
  234. if com.StrTo(m).MustInt() > 0 {
  235. return m
  236. }
  237. return fmt.Sprintf(`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, base.ShortSha(string(m)))
  238. }))
  239. }
  240. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  241. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  242. ms := MentionPattern.FindAll(rawBytes, -1)
  243. for _, m := range ms {
  244. m = m[bytes.Index(m, []byte("@")):]
  245. rawBytes = bytes.Replace(rawBytes, m,
  246. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  247. }
  248. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  249. rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
  250. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  251. return rawBytes
  252. }
  253. // RenderRaw renders Markdown to HTML without handling special links.
  254. func RenderRaw(body []byte, urlPrefix string) []byte {
  255. htmlFlags := 0
  256. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  257. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  258. renderer := &Renderer{
  259. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  260. urlPrefix: urlPrefix,
  261. }
  262. // set up the parser
  263. extensions := 0
  264. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  265. extensions |= blackfriday.EXTENSION_TABLES
  266. extensions |= blackfriday.EXTENSION_FENCED_CODE
  267. extensions |= blackfriday.EXTENSION_AUTOLINK
  268. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  269. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  270. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  271. if setting.Markdown.EnableHardLineBreak {
  272. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  273. }
  274. body = blackfriday.Markdown(body, renderer, extensions)
  275. return body
  276. }
  277. var (
  278. leftAngleBracket = []byte("</")
  279. rightAngleBracket = []byte(">")
  280. )
  281. var noEndTags = []string{"input", "br", "hr", "img"}
  282. // wrapImgWithLink warps link to standalone <img> tags.
  283. func wrapImgWithLink(urlPrefix string, buf *bytes.Buffer, token html.Token) {
  284. var src, alt string
  285. // Extract "src" and "alt" attributes
  286. for i := range token.Attr {
  287. switch token.Attr[i].Key {
  288. case "src":
  289. src = token.Attr[i].Val
  290. case "alt":
  291. alt = token.Attr[i].Val
  292. }
  293. }
  294. // Skip in case the "src" is empty
  295. if len(src) == 0 {
  296. buf.WriteString(token.String())
  297. return
  298. }
  299. buf.WriteString(`<a href="`)
  300. buf.WriteString(src)
  301. buf.WriteString(`">`)
  302. // Prepend repository base URL for internal links
  303. if !isLink([]byte(src)) {
  304. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  305. if src[0] != '/' {
  306. urlPrefix += "/"
  307. }
  308. src = strings.Replace(urlPrefix+string(src), " ", "%20", -1)
  309. buf.WriteString(`<img src="`)
  310. buf.WriteString(src)
  311. buf.WriteString(`"`)
  312. if len(alt) > 0 {
  313. buf.WriteString(` alt="`)
  314. buf.WriteString(alt)
  315. buf.WriteString(`"`)
  316. }
  317. buf.WriteString(`>`)
  318. } else {
  319. buf.WriteString(token.String())
  320. }
  321. buf.WriteString(`</a>`)
  322. }
  323. // PostProcess treats different types of HTML differently,
  324. // and only renders special links for plain text blocks.
  325. func PostProcess(rawHTML []byte, urlPrefix string, metas map[string]string) []byte {
  326. startTags := make([]string, 0, 5)
  327. buf := bytes.NewBuffer(nil)
  328. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  329. OUTER_LOOP:
  330. for html.ErrorToken != tokenizer.Next() {
  331. token := tokenizer.Token()
  332. switch token.Type {
  333. case html.TextToken:
  334. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  335. case html.StartTagToken:
  336. tagName := token.Data
  337. if tagName == "img" {
  338. wrapImgWithLink(urlPrefix, buf, token)
  339. continue OUTER_LOOP
  340. }
  341. buf.WriteString(token.String())
  342. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  343. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  344. stackNum := 1
  345. for html.ErrorToken != tokenizer.Next() {
  346. token = tokenizer.Token()
  347. // Copy the token to the output verbatim
  348. buf.WriteString(token.String())
  349. // Stack number doesn't increate for tags without end tags.
  350. if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
  351. stackNum++
  352. }
  353. // If this is the close tag to the outer-most, we are done
  354. if token.Type == html.EndTagToken {
  355. stackNum--
  356. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  357. break
  358. }
  359. }
  360. }
  361. continue OUTER_LOOP
  362. }
  363. if !com.IsSliceContainsStr(noEndTags, tagName) {
  364. startTags = append(startTags, tagName)
  365. }
  366. case html.EndTagToken:
  367. if len(startTags) == 0 {
  368. buf.WriteString(token.String())
  369. break
  370. }
  371. buf.Write(leftAngleBracket)
  372. buf.WriteString(startTags[len(startTags)-1])
  373. buf.Write(rightAngleBracket)
  374. startTags = startTags[:len(startTags)-1]
  375. default:
  376. buf.WriteString(token.String())
  377. }
  378. }
  379. if io.EOF == tokenizer.Err() {
  380. return buf.Bytes()
  381. }
  382. // If we are not at the end of the input, then some other parsing error has occurred,
  383. // so return the input verbatim.
  384. return rawHTML
  385. }
  386. // Render renders Markdown to HTML with special links.
  387. func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  388. urlPrefix = strings.Replace(urlPrefix, space, spaceEncoded, -1)
  389. result := RenderRaw(rawBytes, urlPrefix)
  390. result = PostProcess(result, urlPrefix, metas)
  391. result = Sanitizer.SanitizeBytes(result)
  392. return result
  393. }
  394. // RenderString renders Markdown to HTML with special links and returns string type.
  395. func RenderString(raw, urlPrefix string, metas map[string]string) string {
  396. return string(Render([]byte(raw), urlPrefix, metas))
  397. }