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 25KB

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