You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

html.go 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. // Copyright 2017 The Gitea 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. "net/url"
  8. "path"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/references"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. "github.com/unknwon/com"
  19. "golang.org/x/net/html"
  20. "golang.org/x/net/html/atom"
  21. "mvdan.cc/xurls/v2"
  22. )
  23. // Issue name styles
  24. const (
  25. IssueNameStyleNumeric = "numeric"
  26. IssueNameStyleAlphanumeric = "alphanumeric"
  27. )
  28. var (
  29. // NOTE: All below regex matching do not perform any extra validation.
  30. // Thus a link is produced even if the linked entity does not exist.
  31. // While fast, this is also incorrect and lead to false positives.
  32. // TODO: fix invalid linking issue
  33. // sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  34. // Although SHA1 hashes are 40 chars long, the regex matches the hash from 7 to 40 chars in length
  35. // so that abbreviated hash links can be used as well. This matches git and github useability.
  36. sha1CurrentPattern = regexp.MustCompile(`(?:\s|^|\(|\[)([0-9a-f]{7,40})(?:\s|$|\)|\]|\.(\s|$))`)
  37. // shortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  38. shortLinkPattern = regexp.MustCompile(`\[\[(.*?)\]\](\w*)`)
  39. // anySHA1Pattern allows to split url containing SHA into parts
  40. anySHA1Pattern = regexp.MustCompile(`https?://(?:\S+/){4}([0-9a-f]{40})(/[^#\s]+)?(#\S+)?`)
  41. validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  42. // While this email regex is definitely not perfect and I'm sure you can come up
  43. // with edge cases, it is still accepted by the CommonMark specification, as
  44. // well as the HTML5 spec:
  45. // http://spec.commonmark.org/0.28/#email-address
  46. // https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type%3Demail)
  47. emailRegex = regexp.MustCompile("(?:\\s|^|\\(|\\[)([a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[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])?)+)(?:\\s|$|\\)|\\]|\\.(\\s|$))")
  48. linkRegex, _ = xurls.StrictMatchingScheme("https?://")
  49. )
  50. // CSS class for action keywords (e.g. "closes: #1")
  51. const keywordClass = "issue-keyword"
  52. // regexp for full links to issues/pulls
  53. var issueFullPattern *regexp.Regexp
  54. // IsLink reports whether link fits valid format.
  55. func IsLink(link []byte) bool {
  56. return isLink(link)
  57. }
  58. // isLink reports whether link fits valid format.
  59. func isLink(link []byte) bool {
  60. return validLinksPattern.Match(link)
  61. }
  62. func isLinkStr(link string) bool {
  63. return validLinksPattern.MatchString(link)
  64. }
  65. func getIssueFullPattern() *regexp.Regexp {
  66. if issueFullPattern == nil {
  67. appURL := setting.AppURL
  68. if len(appURL) > 0 && appURL[len(appURL)-1] != '/' {
  69. appURL += "/"
  70. }
  71. issueFullPattern = regexp.MustCompile(appURL +
  72. `\w+/\w+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`)
  73. }
  74. return issueFullPattern
  75. }
  76. // CustomLinkURLSchemes allows for additional schemes to be detected when parsing links within text
  77. func CustomLinkURLSchemes(schemes []string) {
  78. schemes = append(schemes, "http", "https")
  79. withAuth := make([]string, 0, len(schemes))
  80. validScheme := regexp.MustCompile(`^[a-z]+$`)
  81. for _, s := range schemes {
  82. if !validScheme.MatchString(s) {
  83. continue
  84. }
  85. without := false
  86. for _, sna := range xurls.SchemesNoAuthority {
  87. if s == sna {
  88. without = true
  89. break
  90. }
  91. }
  92. if without {
  93. s += ":"
  94. } else {
  95. s += "://"
  96. }
  97. withAuth = append(withAuth, s)
  98. }
  99. linkRegex, _ = xurls.StrictMatchingScheme(strings.Join(withAuth, "|"))
  100. }
  101. // IsSameDomain checks if given url string has the same hostname as current Gitea instance
  102. func IsSameDomain(s string) bool {
  103. if strings.HasPrefix(s, "/") {
  104. return true
  105. }
  106. if uapp, err := url.Parse(setting.AppURL); err == nil {
  107. if u, err := url.Parse(s); err == nil {
  108. return u.Host == uapp.Host
  109. }
  110. return false
  111. }
  112. return false
  113. }
  114. type postProcessError struct {
  115. context string
  116. err error
  117. }
  118. func (p *postProcessError) Error() string {
  119. return "PostProcess: " + p.context + ", " + p.err.Error()
  120. }
  121. type processor func(ctx *postProcessCtx, node *html.Node)
  122. var defaultProcessors = []processor{
  123. fullIssuePatternProcessor,
  124. fullSha1PatternProcessor,
  125. shortLinkProcessor,
  126. linkProcessor,
  127. mentionProcessor,
  128. issueIndexPatternProcessor,
  129. sha1CurrentPatternProcessor,
  130. emailAddressProcessor,
  131. }
  132. type postProcessCtx struct {
  133. metas map[string]string
  134. urlPrefix string
  135. isWikiMarkdown bool
  136. // processors used by this context.
  137. procs []processor
  138. }
  139. // PostProcess does the final required transformations to the passed raw HTML
  140. // data, and ensures its validity. Transformations include: replacing links and
  141. // emails with HTML links, parsing shortlinks in the format of [[Link]], like
  142. // MediaWiki, linking issues in the format #ID, and mentions in the format
  143. // @user, and others.
  144. func PostProcess(
  145. rawHTML []byte,
  146. urlPrefix string,
  147. metas map[string]string,
  148. isWikiMarkdown bool,
  149. ) ([]byte, error) {
  150. // create the context from the parameters
  151. ctx := &postProcessCtx{
  152. metas: metas,
  153. urlPrefix: urlPrefix,
  154. isWikiMarkdown: isWikiMarkdown,
  155. procs: defaultProcessors,
  156. }
  157. return ctx.postProcess(rawHTML)
  158. }
  159. var commitMessageProcessors = []processor{
  160. fullIssuePatternProcessor,
  161. fullSha1PatternProcessor,
  162. linkProcessor,
  163. mentionProcessor,
  164. issueIndexPatternProcessor,
  165. sha1CurrentPatternProcessor,
  166. emailAddressProcessor,
  167. }
  168. // RenderCommitMessage will use the same logic as PostProcess, but will disable
  169. // the shortLinkProcessor and will add a defaultLinkProcessor if defaultLink is
  170. // set, which changes every text node into a link to the passed default link.
  171. func RenderCommitMessage(
  172. rawHTML []byte,
  173. urlPrefix, defaultLink string,
  174. metas map[string]string,
  175. ) ([]byte, error) {
  176. ctx := &postProcessCtx{
  177. metas: metas,
  178. urlPrefix: urlPrefix,
  179. procs: commitMessageProcessors,
  180. }
  181. if defaultLink != "" {
  182. // we don't have to fear data races, because being
  183. // commitMessageProcessors of fixed len and cap, every time we append
  184. // something to it the slice is realloc+copied, so append always
  185. // generates the slice ex-novo.
  186. ctx.procs = append(ctx.procs, genDefaultLinkProcessor(defaultLink))
  187. }
  188. return ctx.postProcess(rawHTML)
  189. }
  190. var commitMessageSubjectProcessors = []processor{
  191. fullIssuePatternProcessor,
  192. fullSha1PatternProcessor,
  193. linkProcessor,
  194. mentionProcessor,
  195. issueIndexPatternProcessor,
  196. sha1CurrentPatternProcessor,
  197. }
  198. // RenderCommitMessageSubject will use the same logic as PostProcess and
  199. // RenderCommitMessage, but will disable the shortLinkProcessor and
  200. // emailAddressProcessor, will add a defaultLinkProcessor if defaultLink is set,
  201. // which changes every text node into a link to the passed default link.
  202. func RenderCommitMessageSubject(
  203. rawHTML []byte,
  204. urlPrefix, defaultLink string,
  205. metas map[string]string,
  206. ) ([]byte, error) {
  207. ctx := &postProcessCtx{
  208. metas: metas,
  209. urlPrefix: urlPrefix,
  210. procs: commitMessageSubjectProcessors,
  211. }
  212. if defaultLink != "" {
  213. // we don't have to fear data races, because being
  214. // commitMessageSubjectProcessors of fixed len and cap, every time we
  215. // append something to it the slice is realloc+copied, so append always
  216. // generates the slice ex-novo.
  217. ctx.procs = append(ctx.procs, genDefaultLinkProcessor(defaultLink))
  218. }
  219. return ctx.postProcess(rawHTML)
  220. }
  221. // RenderDescriptionHTML will use similar logic as PostProcess, but will
  222. // use a single special linkProcessor.
  223. func RenderDescriptionHTML(
  224. rawHTML []byte,
  225. urlPrefix string,
  226. metas map[string]string,
  227. ) ([]byte, error) {
  228. ctx := &postProcessCtx{
  229. metas: metas,
  230. urlPrefix: urlPrefix,
  231. procs: []processor{
  232. descriptionLinkProcessor,
  233. },
  234. }
  235. return ctx.postProcess(rawHTML)
  236. }
  237. var byteBodyTag = []byte("<body>")
  238. var byteBodyTagClosing = []byte("</body>")
  239. func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) {
  240. if ctx.procs == nil {
  241. ctx.procs = defaultProcessors
  242. }
  243. // give a generous extra 50 bytes
  244. res := make([]byte, 0, len(rawHTML)+50)
  245. res = append(res, byteBodyTag...)
  246. res = append(res, rawHTML...)
  247. res = append(res, byteBodyTagClosing...)
  248. // parse the HTML
  249. nodes, err := html.ParseFragment(bytes.NewReader(res), nil)
  250. if err != nil {
  251. return nil, &postProcessError{"invalid HTML", err}
  252. }
  253. for _, node := range nodes {
  254. ctx.visitNode(node)
  255. }
  256. // Create buffer in which the data will be placed again. We know that the
  257. // length will be at least that of res; to spare a few alloc+copy, we
  258. // reuse res, resetting its length to 0.
  259. buf := bytes.NewBuffer(res[:0])
  260. // Render everything to buf.
  261. for _, node := range nodes {
  262. err = html.Render(buf, node)
  263. if err != nil {
  264. return nil, &postProcessError{"error rendering processed HTML", err}
  265. }
  266. }
  267. // remove initial parts - because Render creates a whole HTML page.
  268. res = buf.Bytes()
  269. res = res[bytes.Index(res, byteBodyTag)+len(byteBodyTag) : bytes.LastIndex(res, byteBodyTagClosing)]
  270. // Everything done successfully, return parsed data.
  271. return res, nil
  272. }
  273. func (ctx *postProcessCtx) visitNode(node *html.Node) {
  274. // We ignore code, pre and already generated links.
  275. switch node.Type {
  276. case html.TextNode:
  277. ctx.textNode(node)
  278. case html.ElementNode:
  279. if node.Data == "a" || node.Data == "code" || node.Data == "pre" {
  280. return
  281. }
  282. for n := node.FirstChild; n != nil; n = n.NextSibling {
  283. ctx.visitNode(n)
  284. }
  285. }
  286. // ignore everything else
  287. }
  288. // textNode runs the passed node through various processors, in order to handle
  289. // all kinds of special links handled by the post-processing.
  290. func (ctx *postProcessCtx) textNode(node *html.Node) {
  291. for _, processor := range ctx.procs {
  292. processor(ctx, node)
  293. }
  294. }
  295. // createKeyword() renders a highlighted version of an action keyword
  296. func createKeyword(content string) *html.Node {
  297. span := &html.Node{
  298. Type: html.ElementNode,
  299. Data: atom.Span.String(),
  300. Attr: []html.Attribute{},
  301. }
  302. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: keywordClass})
  303. text := &html.Node{
  304. Type: html.TextNode,
  305. Data: content,
  306. }
  307. span.AppendChild(text)
  308. return span
  309. }
  310. func createLink(href, content, class string) *html.Node {
  311. a := &html.Node{
  312. Type: html.ElementNode,
  313. Data: atom.A.String(),
  314. Attr: []html.Attribute{{Key: "href", Val: href}},
  315. }
  316. if class != "" {
  317. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  318. }
  319. text := &html.Node{
  320. Type: html.TextNode,
  321. Data: content,
  322. }
  323. a.AppendChild(text)
  324. return a
  325. }
  326. func createCodeLink(href, content, class string) *html.Node {
  327. a := &html.Node{
  328. Type: html.ElementNode,
  329. Data: atom.A.String(),
  330. Attr: []html.Attribute{{Key: "href", Val: href}},
  331. }
  332. if class != "" {
  333. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  334. }
  335. text := &html.Node{
  336. Type: html.TextNode,
  337. Data: content,
  338. }
  339. code := &html.Node{
  340. Type: html.ElementNode,
  341. Data: atom.Code.String(),
  342. Attr: []html.Attribute{{Key: "class", Val: "nohighlight"}},
  343. }
  344. code.AppendChild(text)
  345. a.AppendChild(code)
  346. return a
  347. }
  348. // replaceContent takes text node, and in its content it replaces a section of
  349. // it with the specified newNode.
  350. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  351. replaceContentList(node, i, j, []*html.Node{newNode})
  352. }
  353. // replaceContentList takes text node, and in its content it replaces a section of
  354. // it with the specified newNodes. An example to visualize how this can work can
  355. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  356. func replaceContentList(node *html.Node, i, j int, newNodes []*html.Node) {
  357. // get the data before and after the match
  358. before := node.Data[:i]
  359. after := node.Data[j:]
  360. // Replace in the current node the text, so that it is only what it is
  361. // supposed to have.
  362. node.Data = before
  363. // Get the current next sibling, before which we place the replaced data,
  364. // and after that we place the new text node.
  365. nextSibling := node.NextSibling
  366. for _, n := range newNodes {
  367. node.Parent.InsertBefore(n, nextSibling)
  368. }
  369. if after != "" {
  370. node.Parent.InsertBefore(&html.Node{
  371. Type: html.TextNode,
  372. Data: after,
  373. }, nextSibling)
  374. }
  375. }
  376. func mentionProcessor(ctx *postProcessCtx, node *html.Node) {
  377. // We replace only the first mention; other mentions will be addressed later
  378. found, loc := references.FindFirstMentionBytes([]byte(node.Data))
  379. if !found {
  380. return
  381. }
  382. mention := node.Data[loc.Start:loc.End]
  383. var teams string
  384. teams, ok := ctx.metas["teams"]
  385. if ok && strings.Contains(teams, ","+strings.ToLower(mention[1:])+",") {
  386. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, "org", ctx.metas["org"], "teams", mention[1:]), mention, "mention"))
  387. } else {
  388. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, mention[1:]), mention, "mention"))
  389. }
  390. }
  391. func shortLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  392. shortLinkProcessorFull(ctx, node, false)
  393. }
  394. func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
  395. m := shortLinkPattern.FindStringSubmatchIndex(node.Data)
  396. if m == nil {
  397. return
  398. }
  399. content := node.Data[m[2]:m[3]]
  400. tail := node.Data[m[4]:m[5]]
  401. props := make(map[string]string)
  402. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  403. // It makes page handling terrible, but we prefer GitHub syntax
  404. // And fall back to MediaWiki only when it is obvious from the look
  405. // Of text and link contents
  406. sl := strings.Split(content, "|")
  407. for _, v := range sl {
  408. if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
  409. // There is no equal in this argument; this is a mandatory arg
  410. if props["name"] == "" {
  411. if isLinkStr(v) {
  412. // If we clearly see it is a link, we save it so
  413. // But first we need to ensure, that if both mandatory args provided
  414. // look like links, we stick to GitHub syntax
  415. if props["link"] != "" {
  416. props["name"] = props["link"]
  417. }
  418. props["link"] = strings.TrimSpace(v)
  419. } else {
  420. props["name"] = v
  421. }
  422. } else {
  423. props["link"] = strings.TrimSpace(v)
  424. }
  425. } else {
  426. // There is an equal; optional argument.
  427. sep := strings.IndexByte(v, '=')
  428. key, val := v[:sep], html.UnescapeString(v[sep+1:])
  429. // When parsing HTML, x/net/html will change all quotes which are
  430. // not used for syntax into UTF-8 quotes. So checking val[0] won't
  431. // be enough, since that only checks a single byte.
  432. if (strings.HasPrefix(val, "“") && strings.HasSuffix(val, "”")) ||
  433. (strings.HasPrefix(val, "‘") && strings.HasSuffix(val, "’")) {
  434. const lenQuote = len("‘")
  435. val = val[lenQuote : len(val)-lenQuote]
  436. }
  437. props[key] = val
  438. }
  439. }
  440. var name, link string
  441. if props["link"] != "" {
  442. link = props["link"]
  443. } else if props["name"] != "" {
  444. link = props["name"]
  445. }
  446. if props["title"] != "" {
  447. name = props["title"]
  448. } else if props["name"] != "" {
  449. name = props["name"]
  450. } else {
  451. name = link
  452. }
  453. name += tail
  454. image := false
  455. switch ext := filepath.Ext(link); ext {
  456. // fast path: empty string, ignore
  457. case "":
  458. break
  459. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  460. image = true
  461. }
  462. childNode := &html.Node{}
  463. linkNode := &html.Node{
  464. FirstChild: childNode,
  465. LastChild: childNode,
  466. Type: html.ElementNode,
  467. Data: "a",
  468. DataAtom: atom.A,
  469. }
  470. childNode.Parent = linkNode
  471. absoluteLink := isLinkStr(link)
  472. if !absoluteLink {
  473. if image {
  474. link = strings.Replace(link, " ", "+", -1)
  475. } else {
  476. link = strings.Replace(link, " ", "-", -1)
  477. }
  478. if !strings.Contains(link, "/") {
  479. link = url.PathEscape(link)
  480. }
  481. }
  482. urlPrefix := ctx.urlPrefix
  483. if image {
  484. if !absoluteLink {
  485. if IsSameDomain(urlPrefix) {
  486. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  487. }
  488. if ctx.isWikiMarkdown {
  489. link = util.URLJoin("wiki", "raw", link)
  490. }
  491. link = util.URLJoin(urlPrefix, link)
  492. }
  493. title := props["title"]
  494. if title == "" {
  495. title = props["alt"]
  496. }
  497. if title == "" {
  498. title = path.Base(name)
  499. }
  500. alt := props["alt"]
  501. if alt == "" {
  502. alt = name
  503. }
  504. // make the childNode an image - if we can, we also place the alt
  505. childNode.Type = html.ElementNode
  506. childNode.Data = "img"
  507. childNode.DataAtom = atom.Img
  508. childNode.Attr = []html.Attribute{
  509. {Key: "src", Val: link},
  510. {Key: "title", Val: title},
  511. {Key: "alt", Val: alt},
  512. }
  513. if alt == "" {
  514. childNode.Attr = childNode.Attr[:2]
  515. }
  516. } else {
  517. if !absoluteLink {
  518. if ctx.isWikiMarkdown {
  519. link = util.URLJoin("wiki", link)
  520. }
  521. link = util.URLJoin(urlPrefix, link)
  522. }
  523. childNode.Type = html.TextNode
  524. childNode.Data = name
  525. }
  526. if noLink {
  527. linkNode = childNode
  528. } else {
  529. linkNode.Attr = []html.Attribute{{Key: "href", Val: link}}
  530. }
  531. replaceContent(node, m[0], m[1], linkNode)
  532. }
  533. func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) {
  534. if ctx.metas == nil {
  535. return
  536. }
  537. m := getIssueFullPattern().FindStringSubmatchIndex(node.Data)
  538. if m == nil {
  539. return
  540. }
  541. link := node.Data[m[0]:m[1]]
  542. id := "#" + node.Data[m[2]:m[3]]
  543. // extract repo and org name from matched link like
  544. // http://localhost:3000/gituser/myrepo/issues/1
  545. linkParts := strings.Split(path.Clean(link), "/")
  546. matchOrg := linkParts[len(linkParts)-4]
  547. matchRepo := linkParts[len(linkParts)-3]
  548. if matchOrg == ctx.metas["user"] && matchRepo == ctx.metas["repo"] {
  549. // TODO if m[4]:m[5] is not nil, then link is to a comment,
  550. // and we should indicate that in the text somehow
  551. replaceContent(node, m[0], m[1], createLink(link, id, "issue"))
  552. } else {
  553. orgRepoID := matchOrg + "/" + matchRepo + id
  554. replaceContent(node, m[0], m[1], createLink(link, orgRepoID, "issue"))
  555. }
  556. }
  557. func issueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  558. if ctx.metas == nil {
  559. return
  560. }
  561. var (
  562. found bool
  563. ref *references.RenderizableReference
  564. )
  565. _, exttrack := ctx.metas["format"]
  566. alphanum := ctx.metas["style"] == IssueNameStyleAlphanumeric
  567. // Repos with external issue trackers might still need to reference local PRs
  568. // We need to concern with the first one that shows up in the text, whichever it is
  569. found, ref = references.FindRenderizableReferenceNumeric(node.Data, exttrack && alphanum)
  570. if exttrack && alphanum {
  571. if found2, ref2 := references.FindRenderizableReferenceAlphanumeric(node.Data); found2 {
  572. if !found || ref2.RefLocation.Start < ref.RefLocation.Start {
  573. found = true
  574. ref = ref2
  575. }
  576. }
  577. }
  578. if !found {
  579. return
  580. }
  581. var link *html.Node
  582. reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End]
  583. if exttrack && !ref.IsPull {
  584. ctx.metas["index"] = ref.Issue
  585. link = createLink(com.Expand(ctx.metas["format"], ctx.metas), reftext, "issue")
  586. } else {
  587. // Path determines the type of link that will be rendered. It's unknown at this point whether
  588. // the linked item is actually a PR or an issue. Luckily it's of no real consequence because
  589. // Gitea will redirect on click as appropriate.
  590. path := "issues"
  591. if ref.IsPull {
  592. path = "pulls"
  593. }
  594. if ref.Owner == "" {
  595. link = createLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], path, ref.Issue), reftext, "issue")
  596. } else {
  597. link = createLink(util.URLJoin(setting.AppURL, ref.Owner, ref.Name, path, ref.Issue), reftext, "issue")
  598. }
  599. }
  600. if ref.Action == references.XRefActionNone {
  601. replaceContent(node, ref.RefLocation.Start, ref.RefLocation.End, link)
  602. return
  603. }
  604. // Decorate action keywords if actionable
  605. var keyword *html.Node
  606. if references.IsXrefActionable(ref, exttrack, alphanum) {
  607. keyword = createKeyword(node.Data[ref.ActionLocation.Start:ref.ActionLocation.End])
  608. } else {
  609. keyword = &html.Node{
  610. Type: html.TextNode,
  611. Data: node.Data[ref.ActionLocation.Start:ref.ActionLocation.End],
  612. }
  613. }
  614. spaces := &html.Node{
  615. Type: html.TextNode,
  616. Data: node.Data[ref.ActionLocation.End:ref.RefLocation.Start],
  617. }
  618. replaceContentList(node, ref.ActionLocation.Start, ref.RefLocation.End, []*html.Node{keyword, spaces, link})
  619. }
  620. // fullSha1PatternProcessor renders SHA containing URLs
  621. func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) {
  622. if ctx.metas == nil {
  623. return
  624. }
  625. m := anySHA1Pattern.FindStringSubmatchIndex(node.Data)
  626. if m == nil {
  627. return
  628. }
  629. urlFull := node.Data[m[0]:m[1]]
  630. text := base.ShortSha(node.Data[m[2]:m[3]])
  631. // 3rd capture group matches a optional path
  632. subpath := ""
  633. if m[5] > 0 {
  634. subpath = node.Data[m[4]:m[5]]
  635. }
  636. // 4th capture group matches a optional url hash
  637. hash := ""
  638. if m[7] > 0 {
  639. hash = node.Data[m[6]:m[7]][1:]
  640. }
  641. start := m[0]
  642. end := m[1]
  643. // If url ends in '.', it's very likely that it is not part of the
  644. // actual url but used to finish a sentence.
  645. if strings.HasSuffix(urlFull, ".") {
  646. end--
  647. urlFull = urlFull[:len(urlFull)-1]
  648. if hash != "" {
  649. hash = hash[:len(hash)-1]
  650. } else if subpath != "" {
  651. subpath = subpath[:len(subpath)-1]
  652. }
  653. }
  654. if subpath != "" {
  655. text += subpath
  656. }
  657. if hash != "" {
  658. text += " (" + hash + ")"
  659. }
  660. replaceContent(node, start, end, createCodeLink(urlFull, text, "commit"))
  661. }
  662. // sha1CurrentPatternProcessor renders SHA1 strings to corresponding links that
  663. // are assumed to be in the same repository.
  664. func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  665. if ctx.metas == nil || ctx.metas["user"] == "" || ctx.metas["repo"] == "" || ctx.metas["repoPath"] == "" {
  666. return
  667. }
  668. m := sha1CurrentPattern.FindStringSubmatchIndex(node.Data)
  669. if m == nil {
  670. return
  671. }
  672. hash := node.Data[m[2]:m[3]]
  673. // The regex does not lie, it matches the hash pattern.
  674. // However, a regex cannot know if a hash actually exists or not.
  675. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  676. // but that is not always the case.
  677. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  678. // as used by git and github for linking and thus we have to do similar.
  679. // Because of this, we check to make sure that a matched hash is actually
  680. // a commit in the repository before making it a link.
  681. if _, err := git.NewCommand("rev-parse", "--verify", hash).RunInDirBytes(ctx.metas["repoPath"]); err != nil {
  682. if !strings.Contains(err.Error(), "fatal: Needed a single revision") {
  683. log.Debug("sha1CurrentPatternProcessor git rev-parse: %v", err)
  684. }
  685. return
  686. }
  687. replaceContent(node, m[2], m[3],
  688. createCodeLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], "commit", hash), base.ShortSha(hash), "commit"))
  689. }
  690. // emailAddressProcessor replaces raw email addresses with a mailto: link.
  691. func emailAddressProcessor(ctx *postProcessCtx, node *html.Node) {
  692. m := emailRegex.FindStringSubmatchIndex(node.Data)
  693. if m == nil {
  694. return
  695. }
  696. mail := node.Data[m[2]:m[3]]
  697. replaceContent(node, m[2], m[3], createLink("mailto:"+mail, mail, "mailto"))
  698. }
  699. // linkProcessor creates links for any HTTP or HTTPS URL not captured by
  700. // markdown.
  701. func linkProcessor(ctx *postProcessCtx, node *html.Node) {
  702. m := linkRegex.FindStringIndex(node.Data)
  703. if m == nil {
  704. return
  705. }
  706. uri := node.Data[m[0]:m[1]]
  707. replaceContent(node, m[0], m[1], createLink(uri, uri, "link"))
  708. }
  709. func genDefaultLinkProcessor(defaultLink string) processor {
  710. return func(ctx *postProcessCtx, node *html.Node) {
  711. ch := &html.Node{
  712. Parent: node,
  713. Type: html.TextNode,
  714. Data: node.Data,
  715. }
  716. node.Type = html.ElementNode
  717. node.Data = "a"
  718. node.DataAtom = atom.A
  719. node.Attr = []html.Attribute{
  720. {Key: "href", Val: defaultLink},
  721. {Key: "class", Val: "default-link"},
  722. }
  723. node.FirstChild, node.LastChild = ch, ch
  724. }
  725. }
  726. // descriptionLinkProcessor creates links for DescriptionHTML
  727. func descriptionLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  728. m := linkRegex.FindStringIndex(node.Data)
  729. if m == nil {
  730. return
  731. }
  732. uri := node.Data[m[0]:m[1]]
  733. replaceContent(node, m[0], m[1], createDescriptionLink(uri, uri))
  734. }
  735. func createDescriptionLink(href, content string) *html.Node {
  736. textNode := &html.Node{
  737. Type: html.TextNode,
  738. Data: content,
  739. }
  740. linkNode := &html.Node{
  741. FirstChild: textNode,
  742. LastChild: textNode,
  743. Type: html.ElementNode,
  744. Data: "a",
  745. DataAtom: atom.A,
  746. Attr: []html.Attribute{
  747. {Key: "href", Val: href},
  748. {Key: "target", Val: "_blank"},
  749. {Key: "rel", Val: "noopener noreferrer"},
  750. },
  751. }
  752. textNode.Parent = linkNode
  753. return linkNode
  754. }