markup.go 11 KB

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