markdown.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 base
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "path"
  11. "path/filepath"
  12. "regexp"
  13. "strings"
  14. "github.com/russross/blackfriday"
  15. "golang.org/x/net/html"
  16. "github.com/gogits/gogs/modules/setting"
  17. )
  18. func isletter(c byte) bool {
  19. return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
  20. }
  21. func isalnum(c byte) bool {
  22. return (c >= '0' && c <= '9') || isletter(c)
  23. }
  24. var validLinks = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")}
  25. func isLink(link []byte) bool {
  26. for _, prefix := range validLinks {
  27. if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) {
  28. return true
  29. }
  30. }
  31. return false
  32. }
  33. func IsMarkdownFile(name string) bool {
  34. name = strings.ToLower(name)
  35. switch filepath.Ext(name) {
  36. case ".md", ".markdown", ".mdown", ".mkd":
  37. return true
  38. }
  39. return false
  40. }
  41. func IsTextFile(data []byte) (string, bool) {
  42. contentType := http.DetectContentType(data)
  43. if strings.Index(contentType, "text/") != -1 {
  44. return contentType, true
  45. }
  46. return contentType, false
  47. }
  48. func IsImageFile(data []byte) (string, bool) {
  49. contentType := http.DetectContentType(data)
  50. if strings.Index(contentType, "image/") != -1 {
  51. return contentType, true
  52. }
  53. return contentType, false
  54. }
  55. // IsReadmeFile returns true if given file name suppose to be a README file.
  56. func IsReadmeFile(name string) bool {
  57. name = strings.ToLower(name)
  58. if len(name) < 6 {
  59. return false
  60. } else if len(name) == 6 {
  61. if name == "readme" {
  62. return true
  63. }
  64. return false
  65. }
  66. if name[:7] == "readme." {
  67. return true
  68. }
  69. return false
  70. }
  71. type CustomRender struct {
  72. blackfriday.Renderer
  73. urlPrefix string
  74. }
  75. func (options *CustomRender) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
  76. if len(link) > 0 && !isLink(link) {
  77. if link[0] == '#' {
  78. // link = append([]byte(options.urlPrefix), link...)
  79. } else {
  80. link = []byte(path.Join(options.urlPrefix, string(link)))
  81. }
  82. }
  83. options.Renderer.Link(out, link, title, content)
  84. }
  85. func (options *CustomRender) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
  86. if len(link) > 0 && !isLink(link) {
  87. link = []byte(path.Join(strings.Replace(options.urlPrefix, "/src/", "/raw/", 1), string(link)))
  88. }
  89. options.Renderer.Image(out, link, title, alt)
  90. }
  91. var (
  92. MentionPattern = regexp.MustCompile(`(\s|^)@[0-9a-zA-Z_\.]+`)
  93. commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
  94. issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
  95. issueIndexPattern = regexp.MustCompile(`( |^)#[0-9]+\b`)
  96. sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{40}\b`)
  97. )
  98. func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
  99. ms := MentionPattern.FindAll(rawBytes, -1)
  100. for _, m := range ms {
  101. m = bytes.TrimSpace(m)
  102. rawBytes = bytes.Replace(rawBytes, m,
  103. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  104. }
  105. ms = commitPattern.FindAll(rawBytes, -1)
  106. for _, m := range ms {
  107. m = bytes.TrimSpace(m)
  108. i := strings.Index(string(m), "commit/")
  109. j := strings.Index(string(m), "#")
  110. if j == -1 {
  111. j = len(m)
  112. }
  113. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  114. ` <code><a href="%s">%s</a></code>`, m, ShortSha(string(m[i+7:j])))), -1)
  115. }
  116. ms = issueFullPattern.FindAll(rawBytes, -1)
  117. for _, m := range ms {
  118. m = bytes.TrimSpace(m)
  119. i := strings.Index(string(m), "issues/")
  120. j := strings.Index(string(m), "#")
  121. if j == -1 {
  122. j = len(m)
  123. }
  124. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  125. ` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j])))), -1)
  126. }
  127. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix)
  128. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  129. return rawBytes
  130. }
  131. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  132. ms := sha1CurrentPattern.FindAll(rawBytes, -1)
  133. for _, m := range ms {
  134. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  135. `<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, ShortSha(string(m)))), -1)
  136. }
  137. return rawBytes
  138. }
  139. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string) []byte {
  140. ms := issueIndexPattern.FindAll(rawBytes, -1)
  141. for _, m := range ms {
  142. var space string
  143. m2 := m
  144. if m2[0] == ' ' {
  145. space = " "
  146. m2 = m2[1:]
  147. }
  148. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s/issues/%s">%s</a>`,
  149. space, urlPrefix, m2[1:], m2)), 1)
  150. }
  151. return rawBytes
  152. }
  153. func RenderRawMarkdown(body []byte, urlPrefix string) []byte {
  154. htmlFlags := 0
  155. // htmlFlags |= blackfriday.HTML_USE_XHTML
  156. // htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
  157. // htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
  158. // htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
  159. // htmlFlags |= blackfriday.HTML_SKIP_HTML
  160. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  161. // htmlFlags |= blackfriday.HTML_SKIP_SCRIPT
  162. // htmlFlags |= blackfriday.HTML_GITHUB_BLOCKCODE
  163. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  164. // htmlFlags |= blackfriday.HTML_COMPLETE_PAGE
  165. renderer := &CustomRender{
  166. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  167. urlPrefix: urlPrefix,
  168. }
  169. // set up the parser
  170. extensions := 0
  171. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  172. extensions |= blackfriday.EXTENSION_TABLES
  173. extensions |= blackfriday.EXTENSION_FENCED_CODE
  174. extensions |= blackfriday.EXTENSION_AUTOLINK
  175. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  176. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  177. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  178. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  179. body = blackfriday.Markdown(body, renderer, extensions)
  180. return body
  181. }
  182. // PostProcessMarkdown treats different types of HTML differently,
  183. // and only renders special links for plain text blocks.
  184. func PostProcessMarkdown(rawHtml []byte, urlPrefix string) []byte {
  185. var buf bytes.Buffer
  186. tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml))
  187. for html.ErrorToken != tokenizer.Next() {
  188. token := tokenizer.Token()
  189. switch token.Type {
  190. case html.TextToken:
  191. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix))
  192. case html.StartTagToken:
  193. buf.WriteString(token.String())
  194. tagName := token.Data
  195. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  196. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  197. for html.ErrorToken != tokenizer.Next() {
  198. token = tokenizer.Token()
  199. // Copy the token to the output verbatim
  200. buf.WriteString(token.String())
  201. // If this is the close tag, we are done
  202. if html.EndTagToken == token.Type && strings.EqualFold(tagName, token.Data) {
  203. break
  204. }
  205. }
  206. }
  207. default:
  208. buf.WriteString(token.String())
  209. }
  210. }
  211. if io.EOF == tokenizer.Err() {
  212. return buf.Bytes()
  213. }
  214. // If we are not at the end of the input, then some other parsing error has occurred,
  215. // so return the input verbatim.
  216. return rawHtml
  217. }
  218. func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte {
  219. result := RenderRawMarkdown(rawBytes, urlPrefix)
  220. result = PostProcessMarkdown(result, urlPrefix)
  221. result = Sanitizer.SanitizeBytes(result)
  222. return result
  223. }
  224. func RenderMarkdownString(raw, urlPrefix string) string {
  225. return string(RenderMarkdown([]byte(raw), urlPrefix))
  226. }