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.

270 lines
7.5 KiB

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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 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 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. prefix := strings.Replace(options.urlPrefix, "/src/", "/raw/", 1)
  87. if len(link) > 0 && !isLink(link) {
  88. if link[0] != '/' {
  89. prefix += "/"
  90. }
  91. link = []byte(prefix + string(link))
  92. }
  93. out.WriteString(`<a href="`)
  94. out.Write(link)
  95. out.WriteString(`">`)
  96. options.Renderer.Image(out, link, title, alt)
  97. out.WriteString("</a>")
  98. }
  99. var (
  100. MentionPattern = regexp.MustCompile(`(\s|^)@[0-9a-zA-Z_\.]+`)
  101. commitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
  102. issueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
  103. issueIndexPattern = regexp.MustCompile(`( |^)#[0-9]+\b`)
  104. sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{40}\b`)
  105. )
  106. func RenderSpecialLink(rawBytes []byte, urlPrefix string) []byte {
  107. ms := MentionPattern.FindAll(rawBytes, -1)
  108. for _, m := range ms {
  109. m = bytes.TrimSpace(m)
  110. rawBytes = bytes.Replace(rawBytes, m,
  111. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubUrl, m[1:], m)), -1)
  112. }
  113. ms = commitPattern.FindAll(rawBytes, -1)
  114. for _, m := range ms {
  115. m = bytes.TrimSpace(m)
  116. i := strings.Index(string(m), "commit/")
  117. j := strings.Index(string(m), "#")
  118. if j == -1 {
  119. j = len(m)
  120. }
  121. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  122. ` <code><a href="%s">%s</a></code>`, m, ShortSha(string(m[i+7:j])))), -1)
  123. }
  124. ms = issueFullPattern.FindAll(rawBytes, -1)
  125. for _, m := range ms {
  126. m = bytes.TrimSpace(m)
  127. i := strings.Index(string(m), "issues/")
  128. j := strings.Index(string(m), "#")
  129. if j == -1 {
  130. j = len(m)
  131. }
  132. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  133. ` <a href="%s">#%s</a>`, m, ShortSha(string(m[i+7:j])))), -1)
  134. }
  135. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix)
  136. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  137. return rawBytes
  138. }
  139. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  140. ms := sha1CurrentPattern.FindAll(rawBytes, -1)
  141. for _, m := range ms {
  142. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(
  143. `<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, ShortSha(string(m)))), -1)
  144. }
  145. return rawBytes
  146. }
  147. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string) []byte {
  148. ms := issueIndexPattern.FindAll(rawBytes, -1)
  149. for _, m := range ms {
  150. var space string
  151. m2 := m
  152. if m2[0] == ' ' {
  153. space = " "
  154. m2 = m2[1:]
  155. }
  156. rawBytes = bytes.Replace(rawBytes, m, []byte(fmt.Sprintf(`%s<a href="%s/issues/%s">%s</a>`,
  157. space, urlPrefix, m2[1:], m2)), 1)
  158. }
  159. return rawBytes
  160. }
  161. func RenderRawMarkdown(body []byte, urlPrefix string) []byte {
  162. htmlFlags := 0
  163. // htmlFlags |= blackfriday.HTML_USE_XHTML
  164. // htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
  165. // htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
  166. // htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
  167. // htmlFlags |= blackfriday.HTML_SKIP_HTML
  168. htmlFlags |= blackfriday.HTML_SKIP_STYLE
  169. // htmlFlags |= blackfriday.HTML_SKIP_SCRIPT
  170. // htmlFlags |= blackfriday.HTML_GITHUB_BLOCKCODE
  171. htmlFlags |= blackfriday.HTML_OMIT_CONTENTS
  172. // htmlFlags |= blackfriday.HTML_COMPLETE_PAGE
  173. renderer := &CustomRender{
  174. Renderer: blackfriday.HtmlRenderer(htmlFlags, "", ""),
  175. urlPrefix: urlPrefix,
  176. }
  177. // set up the parser
  178. extensions := 0
  179. extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
  180. extensions |= blackfriday.EXTENSION_TABLES
  181. extensions |= blackfriday.EXTENSION_FENCED_CODE
  182. extensions |= blackfriday.EXTENSION_AUTOLINK
  183. extensions |= blackfriday.EXTENSION_STRIKETHROUGH
  184. extensions |= blackfriday.EXTENSION_SPACE_HEADERS
  185. extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
  186. if setting.Markdown.EnableHardLineBreak {
  187. extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
  188. }
  189. body = blackfriday.Markdown(body, renderer, extensions)
  190. return body
  191. }
  192. // PostProcessMarkdown treats different types of HTML differently,
  193. // and only renders special links for plain text blocks.
  194. func PostProcessMarkdown(rawHtml []byte, urlPrefix string) []byte {
  195. var buf bytes.Buffer
  196. tokenizer := html.NewTokenizer(bytes.NewReader(rawHtml))
  197. for html.ErrorToken != tokenizer.Next() {
  198. token := tokenizer.Token()
  199. switch token.Type {
  200. case html.TextToken:
  201. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix))
  202. case html.StartTagToken:
  203. buf.WriteString(token.String())
  204. tagName := token.Data
  205. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  206. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  207. for html.ErrorToken != tokenizer.Next() {
  208. token = tokenizer.Token()
  209. // Copy the token to the output verbatim
  210. buf.WriteString(token.String())
  211. // If this is the close tag, we are done
  212. if html.EndTagToken == token.Type && strings.EqualFold(tagName, token.Data) {
  213. break
  214. }
  215. }
  216. }
  217. default:
  218. buf.WriteString(token.String())
  219. }
  220. }
  221. if io.EOF == tokenizer.Err() {
  222. return buf.Bytes()
  223. }
  224. // If we are not at the end of the input, then some other parsing error has occurred,
  225. // so return the input verbatim.
  226. return rawHtml
  227. }
  228. func RenderMarkdown(rawBytes []byte, urlPrefix string) []byte {
  229. result := RenderRawMarkdown(rawBytes, urlPrefix)
  230. result = PostProcessMarkdown(result, urlPrefix)
  231. result = Sanitizer.SanitizeBytes(result)
  232. return result
  233. }
  234. func RenderMarkdownString(raw, urlPrefix string) string {
  235. return string(RenderMarkdown([]byte(raw), urlPrefix))
  236. }