markup.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. // Copyright 2017 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 markup
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "regexp"
  10. "strings"
  11. "github.com/Unknwon/com"
  12. "golang.org/x/net/html"
  13. "github.com/gogits/gogs/pkg/setting"
  14. "github.com/gogits/gogs/pkg/tool"
  15. )
  16. // IsReadmeFile reports whether name looks like a README file based on its extension.
  17. func IsReadmeFile(name string) bool {
  18. return strings.HasPrefix(strings.ToLower(name), "readme")
  19. }
  20. const (
  21. ISSUE_NAME_STYLE_NUMERIC = "numeric"
  22. ISSUE_NAME_STYLE_ALPHANUMERIC = "alphanumeric"
  23. )
  24. var (
  25. // MentionPattern matches string that mentions someone, e.g. @Unknwon
  26. MentionPattern = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
  27. // CommitPattern matches link to certain commit with or without trailing hash,
  28. // e.g. https://try.gogs.io/gogs/gogs/commit/d8a994ef243349f321568f9e36d5c3f444b99cae#diff-2
  29. CommitPattern = regexp.MustCompile(`(\s|^)https?.*commit/[0-9a-zA-Z]+(#+[0-9a-zA-Z-]*)?`)
  30. // IssueFullPattern matches link to an issue with or without trailing hash,
  31. // e.g. https://try.gogs.io/gogs/gogs/issues/4#issue-685
  32. IssueFullPattern = regexp.MustCompile(`(\s|^)https?.*issues/[0-9]+(#+[0-9a-zA-Z-]*)?`)
  33. // IssueNumericPattern matches string that references to a numeric issue, e.g. #1287
  34. IssueNumericPattern = regexp.MustCompile(`( |^|\()#[0-9]+\b`)
  35. // IssueAlphanumericPattern matches string that references to an alphanumeric issue, e.g. ABC-1234
  36. IssueAlphanumericPattern = regexp.MustCompile(`( |^|\()[A-Z]{1,10}-[1-9][0-9]*\b`)
  37. // CrossReferenceIssueNumericPattern matches string that references a numeric issue in a difference repository
  38. // e.g. gogits/gogs#12345
  39. CrossReferenceIssueNumericPattern = regexp.MustCompile(`( |^)[0-9a-zA-Z-_\.]+/[0-9a-zA-Z-_\.]+#[0-9]+\b`)
  40. // Sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  41. // FIXME: this pattern matches pure numbers as well, right now we do a hack to check in RenderSha1CurrentPattern
  42. // by converting string to a number.
  43. Sha1CurrentPattern = regexp.MustCompile(`\b[0-9a-f]{40}\b`)
  44. )
  45. // FindAllMentions matches mention patterns in given content
  46. // and returns a list of found user names without @ prefix.
  47. func FindAllMentions(content string) []string {
  48. mentions := MentionPattern.FindAllString(content, -1)
  49. for i := range mentions {
  50. mentions[i] = mentions[i][strings.Index(mentions[i], "@")+1:] // Strip @ character
  51. }
  52. return mentions
  53. }
  54. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  55. // return a clean unified string of request URL path.
  56. func cutoutVerbosePrefix(prefix string) string {
  57. if len(prefix) == 0 || prefix[0] != '/' {
  58. return prefix
  59. }
  60. count := 0
  61. for i := 0; i < len(prefix); i++ {
  62. if prefix[i] == '/' {
  63. count++
  64. }
  65. if count >= 3+setting.AppSubURLDepth {
  66. return prefix[:i]
  67. }
  68. }
  69. return prefix
  70. }
  71. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  72. func RenderIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  73. urlPrefix = cutoutVerbosePrefix(urlPrefix)
  74. pattern := IssueNumericPattern
  75. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  76. pattern = IssueAlphanumericPattern
  77. }
  78. ms := pattern.FindAll(rawBytes, -1)
  79. for _, m := range ms {
  80. if m[0] == ' ' || m[0] == '(' {
  81. m = m[1:] // ignore leading space or opening parentheses
  82. }
  83. var link string
  84. if metas == nil {
  85. link = fmt.Sprintf(`<a href="%s/issues/%s">%s</a>`, urlPrefix, m[1:], m)
  86. } else {
  87. // Support for external issue tracker
  88. if metas["style"] == ISSUE_NAME_STYLE_ALPHANUMERIC {
  89. metas["index"] = string(m)
  90. } else {
  91. metas["index"] = string(m[1:])
  92. }
  93. link = fmt.Sprintf(`<a href="%s">%s</a>`, com.Expand(metas["format"], metas), m)
  94. }
  95. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  96. }
  97. return rawBytes
  98. }
  99. // Note: this section is for purpose of increase performance and
  100. // reduce memory allocation at runtime since they are constant literals.
  101. var pound = []byte("#")
  102. // RenderCrossReferenceIssueIndexPattern renders issue indexes from other repositories to corresponding links.
  103. func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  104. ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
  105. for _, m := range ms {
  106. if m[0] == ' ' || m[0] == '(' {
  107. m = m[1:] // ignore leading space or opening parentheses
  108. }
  109. delimIdx := bytes.Index(m, pound)
  110. repo := string(m[:delimIdx])
  111. index := string(m[delimIdx+1:])
  112. link := fmt.Sprintf(`<a href="%s%s/issues/%s">%s</a>`, setting.AppURL, repo, index, m)
  113. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  114. }
  115. return rawBytes
  116. }
  117. // RenderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  118. func RenderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  119. return []byte(Sha1CurrentPattern.ReplaceAllStringFunc(string(rawBytes[:]), func(m string) string {
  120. if com.StrTo(m).MustInt() > 0 {
  121. return m
  122. }
  123. return fmt.Sprintf(`<a href="%s/commit/%s"><code>%s</code></a>`, urlPrefix, m, tool.ShortSHA1(string(m)))
  124. }))
  125. }
  126. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  127. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  128. ms := MentionPattern.FindAll(rawBytes, -1)
  129. for _, m := range ms {
  130. m = m[bytes.Index(m, []byte("@")):]
  131. rawBytes = bytes.Replace(rawBytes, m,
  132. []byte(fmt.Sprintf(`<a href="%s/%s">%s</a>`, setting.AppSubURL, m[1:], m)), -1)
  133. }
  134. rawBytes = RenderIssueIndexPattern(rawBytes, urlPrefix, metas)
  135. rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
  136. rawBytes = RenderSha1CurrentPattern(rawBytes, urlPrefix)
  137. return rawBytes
  138. }
  139. var (
  140. leftAngleBracket = []byte("</")
  141. rightAngleBracket = []byte(">")
  142. )
  143. var noEndTags = []string{"input", "br", "hr", "img"}
  144. // wrapImgWithLink warps link to standalone <img> tags.
  145. func wrapImgWithLink(urlPrefix string, buf *bytes.Buffer, token html.Token) {
  146. // Extract "src" and "alt" attributes
  147. var src, alt string
  148. for i := range token.Attr {
  149. switch token.Attr[i].Key {
  150. case "src":
  151. src = token.Attr[i].Val
  152. case "alt":
  153. alt = token.Attr[i].Val
  154. }
  155. }
  156. // Skip in case the "src" is empty
  157. if len(src) == 0 {
  158. buf.WriteString(token.String())
  159. return
  160. }
  161. // Prepend repository base URL for internal links
  162. needPrepend := !isLink([]byte(src))
  163. if needPrepend {
  164. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  165. if src[0] != '/' {
  166. urlPrefix += "/"
  167. }
  168. }
  169. buf.WriteString(`<a href="`)
  170. if needPrepend {
  171. buf.WriteString(urlPrefix)
  172. buf.WriteString(src)
  173. } else {
  174. buf.WriteString(src)
  175. }
  176. buf.WriteString(`">`)
  177. if needPrepend {
  178. src = strings.Replace(urlPrefix+string(src), " ", "%20", -1)
  179. buf.WriteString(`<img src="`)
  180. buf.WriteString(src)
  181. buf.WriteString(`"`)
  182. if len(alt) > 0 {
  183. buf.WriteString(` alt="`)
  184. buf.WriteString(alt)
  185. buf.WriteString(`"`)
  186. }
  187. buf.WriteString(`>`)
  188. } else {
  189. buf.WriteString(token.String())
  190. }
  191. buf.WriteString(`</a>`)
  192. }
  193. // postProcessHTML treats different types of HTML differently,
  194. // and only renders special links for plain text blocks.
  195. func postProcessHTML(rawHTML []byte, urlPrefix string, metas map[string]string) []byte {
  196. startTags := make([]string, 0, 5)
  197. buf := bytes.NewBuffer(nil)
  198. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  199. OUTER_LOOP:
  200. for html.ErrorToken != tokenizer.Next() {
  201. token := tokenizer.Token()
  202. switch token.Type {
  203. case html.TextToken:
  204. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas))
  205. case html.StartTagToken:
  206. tagName := token.Data
  207. if tagName == "img" {
  208. wrapImgWithLink(urlPrefix, buf, token)
  209. continue OUTER_LOOP
  210. }
  211. buf.WriteString(token.String())
  212. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  213. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  214. stackNum := 1
  215. for html.ErrorToken != tokenizer.Next() {
  216. token = tokenizer.Token()
  217. // Copy the token to the output verbatim
  218. buf.WriteString(token.String())
  219. // Stack number doesn't increate for tags without end tags.
  220. if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
  221. stackNum++
  222. }
  223. // If this is the close tag to the outer-most, we are done
  224. if token.Type == html.EndTagToken {
  225. stackNum--
  226. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  227. break
  228. }
  229. }
  230. }
  231. continue OUTER_LOOP
  232. }
  233. if !com.IsSliceContainsStr(noEndTags, tagName) {
  234. startTags = append(startTags, tagName)
  235. }
  236. case html.EndTagToken:
  237. if len(startTags) == 0 {
  238. buf.WriteString(token.String())
  239. break
  240. }
  241. buf.Write(leftAngleBracket)
  242. buf.WriteString(startTags[len(startTags)-1])
  243. buf.Write(rightAngleBracket)
  244. startTags = startTags[:len(startTags)-1]
  245. default:
  246. buf.WriteString(token.String())
  247. }
  248. }
  249. if io.EOF == tokenizer.Err() {
  250. return buf.Bytes()
  251. }
  252. // If we are not at the end of the input, then some other parsing error has occurred,
  253. // so return the input verbatim.
  254. return rawHTML
  255. }
  256. type Type string
  257. const (
  258. UNRECOGNIZED Type = "unrecognized"
  259. MARKDOWN Type = "markdown"
  260. ORG_MODE Type = "orgmode"
  261. )
  262. // Render takes a string or []byte and renders to HTML in given type of syntax with special links.
  263. func Render(typ Type, input interface{}, urlPrefix string, metas map[string]string) []byte {
  264. var rawBytes []byte
  265. switch v := input.(type) {
  266. case []byte:
  267. rawBytes = v
  268. case string:
  269. rawBytes = []byte(v)
  270. default:
  271. panic(fmt.Sprintf("unrecognized input content type: %T", input))
  272. }
  273. urlPrefix = strings.TrimRight(strings.Replace(urlPrefix, " ", "%20", -1), "/")
  274. var rawHTML []byte
  275. switch typ {
  276. case MARKDOWN:
  277. rawHTML = RawMarkdown(rawBytes, urlPrefix)
  278. case ORG_MODE:
  279. default:
  280. return rawBytes // Do nothing if syntax type is not recognized
  281. }
  282. rawHTML = postProcessHTML(rawHTML, urlPrefix, metas)
  283. return SanitizeBytes(rawHTML)
  284. }