markup.go 11 KB

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