markup.go 11 KB

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