gitea源码

html.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package markup
  4. import (
  5. "bytes"
  6. "fmt"
  7. "io"
  8. "regexp"
  9. "slices"
  10. "strings"
  11. "sync"
  12. "code.gitea.io/gitea/modules/markup/common"
  13. "golang.org/x/net/html"
  14. "golang.org/x/net/html/atom"
  15. "mvdan.cc/xurls/v2"
  16. )
  17. // Issue name styles
  18. const (
  19. IssueNameStyleNumeric = "numeric"
  20. IssueNameStyleAlphanumeric = "alphanumeric"
  21. IssueNameStyleRegexp = "regexp"
  22. )
  23. type globalVarsType struct {
  24. hashCurrentPattern *regexp.Regexp
  25. shortLinkPattern *regexp.Regexp
  26. anyHashPattern *regexp.Regexp
  27. comparePattern *regexp.Regexp
  28. fullURLPattern *regexp.Regexp
  29. emailRegex *regexp.Regexp
  30. emojiShortCodeRegex *regexp.Regexp
  31. issueFullPattern *regexp.Regexp
  32. filesChangedFullPattern *regexp.Regexp
  33. codePreviewPattern *regexp.Regexp
  34. tagCleaner *regexp.Regexp
  35. nulCleaner *strings.Replacer
  36. }
  37. var globalVars = sync.OnceValue(func() *globalVarsType {
  38. v := &globalVarsType{}
  39. // NOTE: All below regex matching do not perform any extra validation.
  40. // Thus a link is produced even if the linked entity does not exist.
  41. // While fast, this is also incorrect and lead to false positives.
  42. // TODO: fix invalid linking issue (update: stale TODO, what issues? maybe no TODO anymore)
  43. // valid chars in encoded path and parameter: [-+~_%.a-zA-Z0-9/]
  44. // hashCurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  45. // Although SHA1 hashes are 40 chars long, SHA256 are 64, the regex matches the hash from 7 to 64 chars in length
  46. // so that abbreviated hash links can be used as well. This matches git and GitHub usability.
  47. v.hashCurrentPattern = regexp.MustCompile(`(?:\s|^|\(|\[)([0-9a-f]{7,64})(?:\s|$|\)|\]|[.,:](\s|$))`)
  48. // shortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  49. v.shortLinkPattern = regexp.MustCompile(`\[\[(.*?)\]\](\w*)`)
  50. // anyHashPattern splits url containing SHA into parts
  51. v.anyHashPattern = regexp.MustCompile(`https?://(?:\S+/){4,5}([0-9a-f]{40,64})(/[-+~%./\w]+)?(\?[-+~%.\w&=]+)?(#[-+~%.\w]+)?`)
  52. // comparePattern matches "http://domain/org/repo/compare/COMMIT1...COMMIT2#hash"
  53. v.comparePattern = regexp.MustCompile(`https?://(?:\S+/){4,5}([0-9a-f]{7,64})(\.\.\.?)([0-9a-f]{7,64})?(#[-+~_%.a-zA-Z0-9]+)?`)
  54. // fullURLPattern matches full URL like "mailto:...", "https://..." and "ssh+git://..."
  55. v.fullURLPattern = regexp.MustCompile(`^[a-z][-+\w]+:`)
  56. // emailRegex is definitely not perfect with edge cases,
  57. // it is still accepted by the CommonMark specification, as well as the HTML5 spec:
  58. // http://spec.commonmark.org/0.28/#email-address
  59. // https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type%3Demail)
  60. // At the moment, we use stricter rule for rendering purpose: only allow the "name" part starting after the word boundary
  61. v.emailRegex = regexp.MustCompile(`\b([-\w.!#$%&'*+/=?^{|}~]*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9]{2,}(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+)\b`)
  62. // emojiShortCodeRegex find emoji by alias like :smile:
  63. v.emojiShortCodeRegex = regexp.MustCompile(`:[-+\w]+:`)
  64. // example: https://domain/org/repo/pulls/27#hash
  65. v.issueFullPattern = regexp.MustCompile(`https?://(?:\S+/)[\w_.-]+/[\w_.-]+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#](\S+)?)?\b`)
  66. // example: https://domain/org/repo/pulls/27/files#hash
  67. v.filesChangedFullPattern = regexp.MustCompile(`https?://(?:\S+/)[\w_.-]+/[\w_.-]+/pulls/((?:\w{1,10}-)?[1-9][0-9]*)/files([\?|#](\S+)?)?\b`)
  68. // codePreviewPattern matches "http://domain/.../{owner}/{repo}/src/commit/{commit}/{filepath}#L10-L20"
  69. v.codePreviewPattern = regexp.MustCompile(`https?://\S+/([^\s/]+)/([^\s/]+)/src/commit/([0-9a-f]{7,64})(/\S+)#(L\d+(-L\d+)?)`)
  70. // cleans: "<foo/bar", "<any words/", ("<html", "<head", "<script", "<style", "<?", "<%")
  71. v.tagCleaner = regexp.MustCompile(`(?i)<(/?\w+/\w+|/[\w ]+/|/?(html|head|script|style|%|\?)\b)`)
  72. v.nulCleaner = strings.NewReplacer("\000", "")
  73. return v
  74. })
  75. func IsFullURLString(link string) bool {
  76. return globalVars().fullURLPattern.MatchString(link)
  77. }
  78. func IsNonEmptyRelativePath(link string) bool {
  79. return link != "" && !IsFullURLString(link) && link[0] != '?' && link[0] != '#'
  80. }
  81. // CustomLinkURLSchemes allows for additional schemes to be detected when parsing links within text
  82. func CustomLinkURLSchemes(schemes []string) {
  83. schemes = append(schemes, "http", "https")
  84. withAuth := make([]string, 0, len(schemes))
  85. validScheme := regexp.MustCompile(`^[a-z]+$`)
  86. for _, s := range schemes {
  87. if !validScheme.MatchString(s) {
  88. continue
  89. }
  90. without := slices.Contains(xurls.SchemesNoAuthority, s)
  91. if without {
  92. s += ":"
  93. } else {
  94. s += "://"
  95. }
  96. withAuth = append(withAuth, s)
  97. }
  98. common.GlobalVars().LinkRegex, _ = xurls.StrictMatchingScheme(strings.Join(withAuth, "|"))
  99. }
  100. type processor func(ctx *RenderContext, node *html.Node)
  101. // PostProcessDefault does the final required transformations to the passed raw HTML
  102. // data, and ensures its validity. Transformations include: replacing links and
  103. // emails with HTML links, parsing shortlinks in the format of [[Link]], like
  104. // MediaWiki, linking issues in the format #ID, and mentions in the format
  105. // @user, and others.
  106. func PostProcessDefault(ctx *RenderContext, input io.Reader, output io.Writer) error {
  107. procs := []processor{
  108. fullIssuePatternProcessor,
  109. comparePatternProcessor,
  110. codePreviewPatternProcessor,
  111. fullHashPatternProcessor,
  112. shortLinkProcessor,
  113. linkProcessor,
  114. mentionProcessor,
  115. issueIndexPatternProcessor,
  116. commitCrossReferencePatternProcessor,
  117. hashCurrentPatternProcessor,
  118. emailAddressProcessor,
  119. emojiProcessor,
  120. emojiShortCodeProcessor,
  121. }
  122. return postProcess(ctx, procs, input, output)
  123. }
  124. // PostProcessCommitMessage will use the same logic as PostProcess, but will disable
  125. // the shortLinkProcessor.
  126. func PostProcessCommitMessage(ctx *RenderContext, content string) (string, error) {
  127. procs := []processor{
  128. fullIssuePatternProcessor,
  129. comparePatternProcessor,
  130. fullHashPatternProcessor,
  131. linkProcessor,
  132. mentionProcessor,
  133. issueIndexPatternProcessor,
  134. commitCrossReferencePatternProcessor,
  135. hashCurrentPatternProcessor,
  136. emailAddressProcessor,
  137. emojiProcessor,
  138. emojiShortCodeProcessor,
  139. }
  140. return postProcessString(ctx, procs, content)
  141. }
  142. var emojiProcessors = []processor{
  143. emojiShortCodeProcessor,
  144. emojiProcessor,
  145. }
  146. // PostProcessCommitMessageSubject will use the same logic as PostProcess and
  147. // PostProcessCommitMessage, but will disable the shortLinkProcessor and
  148. // emailAddressProcessor, will add a defaultLinkProcessor if defaultLink is set,
  149. // which changes every text node into a link to the passed default link.
  150. func PostProcessCommitMessageSubject(ctx *RenderContext, defaultLink, content string) (string, error) {
  151. procs := []processor{
  152. fullIssuePatternProcessor,
  153. comparePatternProcessor,
  154. fullHashPatternProcessor,
  155. linkProcessor,
  156. mentionProcessor,
  157. issueIndexPatternProcessor,
  158. commitCrossReferencePatternProcessor,
  159. hashCurrentPatternProcessor,
  160. emojiShortCodeProcessor,
  161. emojiProcessor,
  162. }
  163. procs = append(procs, func(ctx *RenderContext, node *html.Node) {
  164. ch := &html.Node{Parent: node, Type: html.TextNode, Data: node.Data}
  165. node.Type = html.ElementNode
  166. node.Data = "a"
  167. node.DataAtom = atom.A
  168. node.Attr = []html.Attribute{{Key: "href", Val: defaultLink}, {Key: "class", Val: "muted"}}
  169. node.FirstChild, node.LastChild = ch, ch
  170. })
  171. return postProcessString(ctx, procs, content)
  172. }
  173. // PostProcessIssueTitle to process title on individual issue/pull page
  174. func PostProcessIssueTitle(ctx *RenderContext, title string) (string, error) {
  175. return postProcessString(ctx, []processor{
  176. issueIndexPatternProcessor,
  177. commitCrossReferencePatternProcessor,
  178. hashCurrentPatternProcessor,
  179. emojiShortCodeProcessor,
  180. emojiProcessor,
  181. }, title)
  182. }
  183. // PostProcessDescriptionHTML will use similar logic as PostProcess, but will
  184. // use a single special linkProcessor.
  185. func PostProcessDescriptionHTML(ctx *RenderContext, content string) (string, error) {
  186. return postProcessString(ctx, []processor{
  187. descriptionLinkProcessor,
  188. emojiShortCodeProcessor,
  189. emojiProcessor,
  190. }, content)
  191. }
  192. // PostProcessEmoji for when we want to just process emoji and shortcodes
  193. // in various places it isn't already run through the normal markdown processor
  194. func PostProcessEmoji(ctx *RenderContext, content string) (string, error) {
  195. return postProcessString(ctx, emojiProcessors, content)
  196. }
  197. func postProcessString(ctx *RenderContext, procs []processor, content string) (string, error) {
  198. var buf strings.Builder
  199. if err := postProcess(ctx, procs, strings.NewReader(content), &buf); err != nil {
  200. return "", err
  201. }
  202. return buf.String(), nil
  203. }
  204. func postProcess(ctx *RenderContext, procs []processor, input io.Reader, output io.Writer) error {
  205. if !ctx.usedByRender && ctx.RenderHelper != nil {
  206. defer ctx.RenderHelper.CleanUp()
  207. }
  208. // FIXME: don't read all content to memory
  209. rawHTML, err := io.ReadAll(input)
  210. if err != nil {
  211. return err
  212. }
  213. // parse the HTML
  214. node, err := html.Parse(io.MultiReader(
  215. // prepend "<html><body>"
  216. strings.NewReader("<html><body>"),
  217. // strip out NULLs (they're always invalid), and escape known tags
  218. bytes.NewReader(globalVars().tagCleaner.ReplaceAll([]byte(globalVars().nulCleaner.Replace(string(rawHTML))), []byte("&lt;$1"))),
  219. // close the tags
  220. strings.NewReader("</body></html>"),
  221. ))
  222. if err != nil {
  223. return fmt.Errorf("markup.postProcess: invalid HTML: %w", err)
  224. }
  225. if node.Type == html.DocumentNode {
  226. node = node.FirstChild
  227. }
  228. visitNode(ctx, procs, node)
  229. newNodes := make([]*html.Node, 0, 5)
  230. if node.Data == "html" {
  231. node = node.FirstChild
  232. for node != nil && node.Data != "body" {
  233. node = node.NextSibling
  234. }
  235. }
  236. if node != nil {
  237. if node.Data == "body" {
  238. child := node.FirstChild
  239. for child != nil {
  240. newNodes = append(newNodes, child)
  241. child = child.NextSibling
  242. }
  243. } else {
  244. newNodes = append(newNodes, node)
  245. }
  246. }
  247. // Render everything to buf.
  248. for _, node := range newNodes {
  249. if err := html.Render(output, node); err != nil {
  250. return fmt.Errorf("markup.postProcess: html.Render: %w", err)
  251. }
  252. }
  253. return nil
  254. }
  255. func isEmojiNode(node *html.Node) bool {
  256. if node.Type == html.ElementNode && node.Data == atom.Span.String() {
  257. for _, attr := range node.Attr {
  258. if (attr.Key == "class" || attr.Key == "data-attr-class") && strings.Contains(attr.Val, "emoji") {
  259. return true
  260. }
  261. }
  262. }
  263. return false
  264. }
  265. func visitNode(ctx *RenderContext, procs []processor, node *html.Node) *html.Node {
  266. if node.Type == html.TextNode {
  267. for _, proc := range procs {
  268. proc(ctx, node) // it might add siblings
  269. }
  270. return node.NextSibling
  271. }
  272. if node.Type != html.ElementNode {
  273. return node.NextSibling
  274. }
  275. processNodeAttrID(node)
  276. processFootnoteNode(ctx, node) // FIXME: the footnote processing should be done in the "footnote.go" renderer directly
  277. if isEmojiNode(node) {
  278. // TextNode emoji will be converted to `<span class="emoji">`, then the next iteration will visit the "span"
  279. // if we don't stop it, it will go into the TextNode again and create an infinite recursion
  280. return node.NextSibling
  281. } else if node.Data == "code" || node.Data == "pre" {
  282. return node.NextSibling // ignore code and pre nodes
  283. } else if node.Data == "img" {
  284. return visitNodeImg(ctx, node)
  285. } else if node.Data == "video" {
  286. return visitNodeVideo(ctx, node)
  287. }
  288. if node.Data == "a" {
  289. processNodeA(ctx, node)
  290. // only use emoji processors for the content in the "A" tag,
  291. // because the content there is not processable, for example: the content is a commit id or a full URL.
  292. procs = emojiProcessors
  293. }
  294. for n := node.FirstChild; n != nil; {
  295. n = visitNode(ctx, procs, n)
  296. }
  297. return node.NextSibling
  298. }
  299. // createKeyword() renders a highlighted version of an action keyword
  300. func createKeyword(ctx *RenderContext, content string) *html.Node {
  301. // CSS class for action keywords (e.g. "closes: #1")
  302. const keywordClass = "issue-keyword"
  303. span := &html.Node{
  304. Type: html.ElementNode,
  305. Data: atom.Span.String(),
  306. Attr: []html.Attribute{},
  307. }
  308. span.Attr = append(span.Attr, ctx.RenderInternal.NodeSafeAttr("class", keywordClass))
  309. text := &html.Node{
  310. Type: html.TextNode,
  311. Data: content,
  312. }
  313. span.AppendChild(text)
  314. return span
  315. }
  316. func createLink(ctx *RenderContext, href, content, class string) *html.Node {
  317. a := &html.Node{
  318. Type: html.ElementNode,
  319. Data: atom.A.String(),
  320. Attr: []html.Attribute{{Key: "href", Val: href}},
  321. }
  322. if !RenderBehaviorForTesting.DisableAdditionalAttributes {
  323. a.Attr = append(a.Attr, html.Attribute{Key: "data-markdown-generated-content"})
  324. }
  325. if class != "" {
  326. a.Attr = append(a.Attr, ctx.RenderInternal.NodeSafeAttr("class", class))
  327. }
  328. text := &html.Node{
  329. Type: html.TextNode,
  330. Data: content,
  331. }
  332. a.AppendChild(text)
  333. return a
  334. }
  335. // replaceContent takes text node, and in its content it replaces a section of
  336. // it with the specified newNode.
  337. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  338. replaceContentList(node, i, j, []*html.Node{newNode})
  339. }
  340. // replaceContentList takes text node, and in its content it replaces a section of
  341. // it with the specified newNodes. An example to visualize how this can work can
  342. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  343. func replaceContentList(node *html.Node, i, j int, newNodes []*html.Node) {
  344. // get the data before and after the match
  345. before := node.Data[:i]
  346. after := node.Data[j:]
  347. // Replace in the current node the text, so that it is only what it is
  348. // supposed to have.
  349. node.Data = before
  350. // Get the current next sibling, before which we place the replaced data,
  351. // and after that we place the new text node.
  352. nextSibling := node.NextSibling
  353. for _, n := range newNodes {
  354. node.Parent.InsertBefore(n, nextSibling)
  355. }
  356. if after != "" {
  357. node.Parent.InsertBefore(&html.Node{
  358. Type: html.TextNode,
  359. Data: after,
  360. }, nextSibling)
  361. }
  362. }