markdown.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. if setting.Smartypants.Enabled {
  259. htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
  260. if setting.Smartypants.Fractions {
  261. htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
  262. }
  263. if setting.Smartypants.Dashes {
  264. htmlFlags |= blackfriday.HTML_SMARTYPANTS_DASHES
  265. }
  266. if setting.Smartypants.LatexDashes {
  267. htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
  268. }
  269. if setting.Smartypants.AngledQuotes {
  270. htmlFlags |= blackfriday.HTML_SMARTYPANTS_ANGLED_QUOTES
  271. }
  272. }
  273. renderer := &Renderer{
  274. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  275. urlPrefix: urlPrefix,
  276. }
  277. // set up the parser
  278. extensions := 0
  279. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  280. extensions |= blackfriday.EXTENSION_TABLES
  281. extensions |= blackfriday.EXTENSION_FENCED_CODE
  282. extensions |= blackfriday.EXTENSION_AUTOLINK
  283. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  284. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  285. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  286. if setting.Markdown.EnableHardLineBreak {
  287. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  288. }
  289. body = blackfriday.Markdown(body, renderer, extensions)
  290. return body
  291. }
  292. var (
  293. leftAngleBracket = []byte("</")
  294. rightAngleBracket = []byte(">")
  295. )
  296. var noEndTags = []string{"input", "br", "hr", "img"}
  297. // wrapImgWithLink warps link to standalone <img> tags.
  298. func wrapImgWithLink(urlPrefix string, buf *bytes.Buffer, token html.Token) {
  299. var src, alt string
  300. // Extract "src" and "alt" attributes
  301. for i := range token.Attr {
  302. switch token.Attr[i].Key {
  303. case "src":
  304. src = token.Attr[i].Val
  305. case "alt":
  306. alt = token.Attr[i].Val
  307. }
  308. }
  309. // Skip in case the "src" is empty
  310. if len(src) == 0 {
  311. buf.WriteString(token.String())
  312. return
  313. }
  314. // Prepend repository base URL for internal links
  315. needPrepend := !isLink([]byte(src))
  316. if needPrepend {
  317. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  318. if src[0] != '/' {
  319. urlPrefix += "/"
  320. }
  321. }
  322. buf.WriteString(`<a href="`)
  323. if needPrepend {
  324. buf.WriteString(urlPrefix)
  325. buf.WriteString(src)
  326. } else {
  327. buf.WriteString(src)
  328. }
  329. buf.WriteString(`">`)
  330. if needPrepend {
  331. src = strings.Replace(urlPrefix+string(src), " ", "%20", -1)
  332. buf.WriteString(`<img src="`)
  333. buf.WriteString(src)
  334. buf.WriteString(`"`)
  335. if len(alt) > 0 {
  336. buf.WriteString(` alt="`)
  337. buf.WriteString(alt)
  338. buf.WriteString(`"`)
  339. }
  340. buf.WriteString(`>`)
  341. } else {
  342. buf.WriteString(token.String())
  343. }
  344. buf.WriteString(`</a>`)
  345. }
  346. // PostProcess treats different types of HTML differently,
  347. // and only renders special links for plain text blocks.
  348. func PostProcess(rawHTML []byte, urlPrefix string, metas map[string]string) []byte {
  349. startTags := make([]string, 0, 5)
  350. buf := bytes.NewBuffer(nil)
  351. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  352. OUTER_LOOP:
  353. for html.ErrorToken != tokenizer.Next() {
  354. token := tokenizer.Token()
  355. switch token.Type {
  356. case html.TextToken:
  357. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  358. case html.StartTagToken:
  359. tagName := token.Data
  360. if tagName == "img" {
  361. wrapImgWithLink(urlPrefix, buf, token)
  362. continue OUTER_LOOP
  363. }
  364. buf.WriteString(token.String())
  365. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  366. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  367. stackNum := 1
  368. for html.ErrorToken != tokenizer.Next() {
  369. token = tokenizer.Token()
  370. // Copy the token to the output verbatim
  371. buf.WriteString(token.String())
  372. // Stack number doesn't increate for tags without end tags.
  373. if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
  374. stackNum++
  375. }
  376. // If this is the close tag to the outer-most, we are done
  377. if token.Type == html.EndTagToken {
  378. stackNum--
  379. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  380. break
  381. }
  382. }
  383. }
  384. continue OUTER_LOOP
  385. }
  386. if !com.IsSliceContainsStr(noEndTags, tagName) {
  387. startTags = append(startTags, tagName)
  388. }
  389. case html.EndTagToken:
  390. if len(startTags) == 0 {
  391. buf.WriteString(token.String())
  392. break
  393. }
  394. buf.Write(leftAngleBracket)
  395. buf.WriteString(startTags[len(startTags)-1])
  396. buf.Write(rightAngleBracket)
  397. startTags = startTags[:len(startTags)-1]
  398. default:
  399. buf.WriteString(token.String())
  400. }
  401. }
  402. if io.EOF == tokenizer.Err() {
  403. return buf.Bytes()
  404. }
  405. // If we are not at the end of the input, then some other parsing error has occurred,
  406. // so return the input verbatim.
  407. return rawHTML
  408. }
  409. // Render renders Markdown to HTML with special links.
  410. func Render(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  411. urlPrefix = strings.Replace(urlPrefix, space, spaceEncoded, -1)
  412. result := RenderRaw(rawBytes, urlPrefix)
  413. result = PostProcess(result, urlPrefix, metas)
  414. result = Sanitizer.SanitizeBytes(result)
  415. return result
  416. }
  417. // RenderString renders Markdown to HTML with special links and returns string type.
  418. func RenderString(raw, urlPrefix string, metas map[string]string) string {
  419. return string(Render([]byte(raw), urlPrefix, metas))
  420. }