markup.go 11 KB

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