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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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, true)
  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, visitText bool) {
  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. if visitText {
  286. ctx.textNode(node)
  287. }
  288. case html.ElementNode:
  289. if node.Data == "img" {
  290. attrs := node.Attr
  291. for idx, attr := range attrs {
  292. if attr.Key != "src" {
  293. continue
  294. }
  295. link := []byte(attr.Val)
  296. if len(link) > 0 && !IsLink(link) {
  297. prefix := ctx.urlPrefix
  298. if ctx.isWikiMarkdown {
  299. prefix = util.URLJoin(prefix, "wiki", "raw")
  300. }
  301. prefix = strings.Replace(prefix, "/src/", "/media/", 1)
  302. lnk := string(link)
  303. lnk = util.URLJoin(prefix, lnk)
  304. link = []byte(lnk)
  305. }
  306. node.Attr[idx].Val = string(link)
  307. }
  308. } else if node.Data == "a" {
  309. visitText = false
  310. } else if node.Data == "code" || node.Data == "pre" {
  311. return
  312. }
  313. for n := node.FirstChild; n != nil; n = n.NextSibling {
  314. ctx.visitNode(n, visitText)
  315. }
  316. }
  317. // ignore everything else
  318. }
  319. // textNode runs the passed node through various processors, in order to handle
  320. // all kinds of special links handled by the post-processing.
  321. func (ctx *postProcessCtx) textNode(node *html.Node) {
  322. for _, processor := range ctx.procs {
  323. processor(ctx, node)
  324. }
  325. }
  326. // createKeyword() renders a highlighted version of an action keyword
  327. func createKeyword(content string) *html.Node {
  328. span := &html.Node{
  329. Type: html.ElementNode,
  330. Data: atom.Span.String(),
  331. Attr: []html.Attribute{},
  332. }
  333. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: keywordClass})
  334. text := &html.Node{
  335. Type: html.TextNode,
  336. Data: content,
  337. }
  338. span.AppendChild(text)
  339. return span
  340. }
  341. func createLink(href, content, class string) *html.Node {
  342. a := &html.Node{
  343. Type: html.ElementNode,
  344. Data: atom.A.String(),
  345. Attr: []html.Attribute{{Key: "href", Val: href}},
  346. }
  347. if class != "" {
  348. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  349. }
  350. text := &html.Node{
  351. Type: html.TextNode,
  352. Data: content,
  353. }
  354. a.AppendChild(text)
  355. return a
  356. }
  357. func createCodeLink(href, content, class string) *html.Node {
  358. a := &html.Node{
  359. Type: html.ElementNode,
  360. Data: atom.A.String(),
  361. Attr: []html.Attribute{{Key: "href", Val: href}},
  362. }
  363. if class != "" {
  364. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  365. }
  366. text := &html.Node{
  367. Type: html.TextNode,
  368. Data: content,
  369. }
  370. code := &html.Node{
  371. Type: html.ElementNode,
  372. Data: atom.Code.String(),
  373. Attr: []html.Attribute{{Key: "class", Val: "nohighlight"}},
  374. }
  375. code.AppendChild(text)
  376. a.AppendChild(code)
  377. return a
  378. }
  379. // replaceContent takes text node, and in its content it replaces a section of
  380. // it with the specified newNode.
  381. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  382. replaceContentList(node, i, j, []*html.Node{newNode})
  383. }
  384. // replaceContentList takes text node, and in its content it replaces a section of
  385. // it with the specified newNodes. An example to visualize how this can work can
  386. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  387. func replaceContentList(node *html.Node, i, j int, newNodes []*html.Node) {
  388. // get the data before and after the match
  389. before := node.Data[:i]
  390. after := node.Data[j:]
  391. // Replace in the current node the text, so that it is only what it is
  392. // supposed to have.
  393. node.Data = before
  394. // Get the current next sibling, before which we place the replaced data,
  395. // and after that we place the new text node.
  396. nextSibling := node.NextSibling
  397. for _, n := range newNodes {
  398. node.Parent.InsertBefore(n, nextSibling)
  399. }
  400. if after != "" {
  401. node.Parent.InsertBefore(&html.Node{
  402. Type: html.TextNode,
  403. Data: after,
  404. }, nextSibling)
  405. }
  406. }
  407. func mentionProcessor(ctx *postProcessCtx, node *html.Node) {
  408. // We replace only the first mention; other mentions will be addressed later
  409. found, loc := references.FindFirstMentionBytes([]byte(node.Data))
  410. if !found {
  411. return
  412. }
  413. mention := node.Data[loc.Start:loc.End]
  414. var teams string
  415. teams, ok := ctx.metas["teams"]
  416. if ok && strings.Contains(teams, ","+strings.ToLower(mention[1:])+",") {
  417. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, "org", ctx.metas["org"], "teams", mention[1:]), mention, "mention"))
  418. } else {
  419. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, mention[1:]), mention, "mention"))
  420. }
  421. }
  422. func shortLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  423. shortLinkProcessorFull(ctx, node, false)
  424. }
  425. func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
  426. m := shortLinkPattern.FindStringSubmatchIndex(node.Data)
  427. if m == nil {
  428. return
  429. }
  430. content := node.Data[m[2]:m[3]]
  431. tail := node.Data[m[4]:m[5]]
  432. props := make(map[string]string)
  433. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  434. // It makes page handling terrible, but we prefer GitHub syntax
  435. // And fall back to MediaWiki only when it is obvious from the look
  436. // Of text and link contents
  437. sl := strings.Split(content, "|")
  438. for _, v := range sl {
  439. if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
  440. // There is no equal in this argument; this is a mandatory arg
  441. if props["name"] == "" {
  442. if isLinkStr(v) {
  443. // If we clearly see it is a link, we save it so
  444. // But first we need to ensure, that if both mandatory args provided
  445. // look like links, we stick to GitHub syntax
  446. if props["link"] != "" {
  447. props["name"] = props["link"]
  448. }
  449. props["link"] = strings.TrimSpace(v)
  450. } else {
  451. props["name"] = v
  452. }
  453. } else {
  454. props["link"] = strings.TrimSpace(v)
  455. }
  456. } else {
  457. // There is an equal; optional argument.
  458. sep := strings.IndexByte(v, '=')
  459. key, val := v[:sep], html.UnescapeString(v[sep+1:])
  460. // When parsing HTML, x/net/html will change all quotes which are
  461. // not used for syntax into UTF-8 quotes. So checking val[0] won't
  462. // be enough, since that only checks a single byte.
  463. if (strings.HasPrefix(val, "“") && strings.HasSuffix(val, "”")) ||
  464. (strings.HasPrefix(val, "‘") && strings.HasSuffix(val, "’")) {
  465. const lenQuote = len("‘")
  466. val = val[lenQuote : len(val)-lenQuote]
  467. } else if (strings.HasPrefix(val, "\"") && strings.HasSuffix(val, "\"")) ||
  468. (strings.HasPrefix(val, "'") && strings.HasSuffix(val, "'")) {
  469. val = val[1 : len(val)-1]
  470. } else if strings.HasPrefix(val, "'") && strings.HasSuffix(val, "’") {
  471. const lenQuote = len("‘")
  472. val = val[1 : len(val)-lenQuote]
  473. }
  474. props[key] = val
  475. }
  476. }
  477. var name, link string
  478. if props["link"] != "" {
  479. link = props["link"]
  480. } else if props["name"] != "" {
  481. link = props["name"]
  482. }
  483. if props["title"] != "" {
  484. name = props["title"]
  485. } else if props["name"] != "" {
  486. name = props["name"]
  487. } else {
  488. name = link
  489. }
  490. name += tail
  491. image := false
  492. switch ext := filepath.Ext(link); ext {
  493. // fast path: empty string, ignore
  494. case "":
  495. break
  496. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  497. image = true
  498. }
  499. childNode := &html.Node{}
  500. linkNode := &html.Node{
  501. FirstChild: childNode,
  502. LastChild: childNode,
  503. Type: html.ElementNode,
  504. Data: "a",
  505. DataAtom: atom.A,
  506. }
  507. childNode.Parent = linkNode
  508. absoluteLink := isLinkStr(link)
  509. if !absoluteLink {
  510. if image {
  511. link = strings.Replace(link, " ", "+", -1)
  512. } else {
  513. link = strings.Replace(link, " ", "-", -1)
  514. }
  515. if !strings.Contains(link, "/") {
  516. link = url.PathEscape(link)
  517. }
  518. }
  519. urlPrefix := ctx.urlPrefix
  520. if image {
  521. if !absoluteLink {
  522. if IsSameDomain(urlPrefix) {
  523. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  524. }
  525. if ctx.isWikiMarkdown {
  526. link = util.URLJoin("wiki", "raw", link)
  527. }
  528. link = util.URLJoin(urlPrefix, link)
  529. }
  530. title := props["title"]
  531. if title == "" {
  532. title = props["alt"]
  533. }
  534. if title == "" {
  535. title = path.Base(name)
  536. }
  537. alt := props["alt"]
  538. if alt == "" {
  539. alt = name
  540. }
  541. // make the childNode an image - if we can, we also place the alt
  542. childNode.Type = html.ElementNode
  543. childNode.Data = "img"
  544. childNode.DataAtom = atom.Img
  545. childNode.Attr = []html.Attribute{
  546. {Key: "src", Val: link},
  547. {Key: "title", Val: title},
  548. {Key: "alt", Val: alt},
  549. }
  550. if alt == "" {
  551. childNode.Attr = childNode.Attr[:2]
  552. }
  553. } else {
  554. if !absoluteLink {
  555. if ctx.isWikiMarkdown {
  556. link = util.URLJoin("wiki", link)
  557. }
  558. link = util.URLJoin(urlPrefix, link)
  559. }
  560. childNode.Type = html.TextNode
  561. childNode.Data = name
  562. }
  563. if noLink {
  564. linkNode = childNode
  565. } else {
  566. linkNode.Attr = []html.Attribute{{Key: "href", Val: link}}
  567. }
  568. replaceContent(node, m[0], m[1], linkNode)
  569. }
  570. func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) {
  571. if ctx.metas == nil {
  572. return
  573. }
  574. m := getIssueFullPattern().FindStringSubmatchIndex(node.Data)
  575. if m == nil {
  576. return
  577. }
  578. link := node.Data[m[0]:m[1]]
  579. id := "#" + node.Data[m[2]:m[3]]
  580. // extract repo and org name from matched link like
  581. // http://localhost:3000/gituser/myrepo/issues/1
  582. linkParts := strings.Split(path.Clean(link), "/")
  583. matchOrg := linkParts[len(linkParts)-4]
  584. matchRepo := linkParts[len(linkParts)-3]
  585. if matchOrg == ctx.metas["user"] && matchRepo == ctx.metas["repo"] {
  586. // TODO if m[4]:m[5] is not nil, then link is to a comment,
  587. // and we should indicate that in the text somehow
  588. replaceContent(node, m[0], m[1], createLink(link, id, "issue"))
  589. } else {
  590. orgRepoID := matchOrg + "/" + matchRepo + id
  591. replaceContent(node, m[0], m[1], createLink(link, orgRepoID, "issue"))
  592. }
  593. }
  594. func issueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  595. if ctx.metas == nil {
  596. return
  597. }
  598. var (
  599. found bool
  600. ref *references.RenderizableReference
  601. )
  602. _, exttrack := ctx.metas["format"]
  603. alphanum := ctx.metas["style"] == IssueNameStyleAlphanumeric
  604. // Repos with external issue trackers might still need to reference local PRs
  605. // We need to concern with the first one that shows up in the text, whichever it is
  606. found, ref = references.FindRenderizableReferenceNumeric(node.Data, exttrack && alphanum)
  607. if exttrack && alphanum {
  608. if found2, ref2 := references.FindRenderizableReferenceAlphanumeric(node.Data); found2 {
  609. if !found || ref2.RefLocation.Start < ref.RefLocation.Start {
  610. found = true
  611. ref = ref2
  612. }
  613. }
  614. }
  615. if !found {
  616. return
  617. }
  618. var link *html.Node
  619. reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End]
  620. if exttrack && !ref.IsPull {
  621. ctx.metas["index"] = ref.Issue
  622. link = createLink(com.Expand(ctx.metas["format"], ctx.metas), reftext, "issue")
  623. } else {
  624. // Path determines the type of link that will be rendered. It's unknown at this point whether
  625. // the linked item is actually a PR or an issue. Luckily it's of no real consequence because
  626. // Gitea will redirect on click as appropriate.
  627. path := "issues"
  628. if ref.IsPull {
  629. path = "pulls"
  630. }
  631. if ref.Owner == "" {
  632. link = createLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], path, ref.Issue), reftext, "issue")
  633. } else {
  634. link = createLink(util.URLJoin(setting.AppURL, ref.Owner, ref.Name, path, ref.Issue), reftext, "issue")
  635. }
  636. }
  637. if ref.Action == references.XRefActionNone {
  638. replaceContent(node, ref.RefLocation.Start, ref.RefLocation.End, link)
  639. return
  640. }
  641. // Decorate action keywords if actionable
  642. var keyword *html.Node
  643. if references.IsXrefActionable(ref, exttrack, alphanum) {
  644. keyword = createKeyword(node.Data[ref.ActionLocation.Start:ref.ActionLocation.End])
  645. } else {
  646. keyword = &html.Node{
  647. Type: html.TextNode,
  648. Data: node.Data[ref.ActionLocation.Start:ref.ActionLocation.End],
  649. }
  650. }
  651. spaces := &html.Node{
  652. Type: html.TextNode,
  653. Data: node.Data[ref.ActionLocation.End:ref.RefLocation.Start],
  654. }
  655. replaceContentList(node, ref.ActionLocation.Start, ref.RefLocation.End, []*html.Node{keyword, spaces, link})
  656. }
  657. // fullSha1PatternProcessor renders SHA containing URLs
  658. func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) {
  659. if ctx.metas == nil {
  660. return
  661. }
  662. m := anySHA1Pattern.FindStringSubmatchIndex(node.Data)
  663. if m == nil {
  664. return
  665. }
  666. urlFull := node.Data[m[0]:m[1]]
  667. text := base.ShortSha(node.Data[m[2]:m[3]])
  668. // 3rd capture group matches a optional path
  669. subpath := ""
  670. if m[5] > 0 {
  671. subpath = node.Data[m[4]:m[5]]
  672. }
  673. // 4th capture group matches a optional url hash
  674. hash := ""
  675. if m[7] > 0 {
  676. hash = node.Data[m[6]:m[7]][1:]
  677. }
  678. start := m[0]
  679. end := m[1]
  680. // If url ends in '.', it's very likely that it is not part of the
  681. // actual url but used to finish a sentence.
  682. if strings.HasSuffix(urlFull, ".") {
  683. end--
  684. urlFull = urlFull[:len(urlFull)-1]
  685. if hash != "" {
  686. hash = hash[:len(hash)-1]
  687. } else if subpath != "" {
  688. subpath = subpath[:len(subpath)-1]
  689. }
  690. }
  691. if subpath != "" {
  692. text += subpath
  693. }
  694. if hash != "" {
  695. text += " (" + hash + ")"
  696. }
  697. replaceContent(node, start, end, createCodeLink(urlFull, text, "commit"))
  698. }
  699. // sha1CurrentPatternProcessor renders SHA1 strings to corresponding links that
  700. // are assumed to be in the same repository.
  701. func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  702. if ctx.metas == nil || ctx.metas["user"] == "" || ctx.metas["repo"] == "" || ctx.metas["repoPath"] == "" {
  703. return
  704. }
  705. m := sha1CurrentPattern.FindStringSubmatchIndex(node.Data)
  706. if m == nil {
  707. return
  708. }
  709. hash := node.Data[m[2]:m[3]]
  710. // The regex does not lie, it matches the hash pattern.
  711. // However, a regex cannot know if a hash actually exists or not.
  712. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  713. // but that is not always the case.
  714. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  715. // as used by git and github for linking and thus we have to do similar.
  716. // Because of this, we check to make sure that a matched hash is actually
  717. // a commit in the repository before making it a link.
  718. if _, err := git.NewCommand("rev-parse", "--verify", hash).RunInDirBytes(ctx.metas["repoPath"]); err != nil {
  719. if !strings.Contains(err.Error(), "fatal: Needed a single revision") {
  720. log.Debug("sha1CurrentPatternProcessor git rev-parse: %v", err)
  721. }
  722. return
  723. }
  724. replaceContent(node, m[2], m[3],
  725. createCodeLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], "commit", hash), base.ShortSha(hash), "commit"))
  726. }
  727. // emailAddressProcessor replaces raw email addresses with a mailto: link.
  728. func emailAddressProcessor(ctx *postProcessCtx, node *html.Node) {
  729. m := emailRegex.FindStringSubmatchIndex(node.Data)
  730. if m == nil {
  731. return
  732. }
  733. mail := node.Data[m[2]:m[3]]
  734. replaceContent(node, m[2], m[3], createLink("mailto:"+mail, mail, "mailto"))
  735. }
  736. // linkProcessor creates links for any HTTP or HTTPS URL not captured by
  737. // markdown.
  738. func linkProcessor(ctx *postProcessCtx, node *html.Node) {
  739. m := common.LinkRegex.FindStringIndex(node.Data)
  740. if m == nil {
  741. return
  742. }
  743. uri := node.Data[m[0]:m[1]]
  744. replaceContent(node, m[0], m[1], createLink(uri, uri, "link"))
  745. }
  746. func genDefaultLinkProcessor(defaultLink string) processor {
  747. return func(ctx *postProcessCtx, node *html.Node) {
  748. ch := &html.Node{
  749. Parent: node,
  750. Type: html.TextNode,
  751. Data: node.Data,
  752. }
  753. node.Type = html.ElementNode
  754. node.Data = "a"
  755. node.DataAtom = atom.A
  756. node.Attr = []html.Attribute{
  757. {Key: "href", Val: defaultLink},
  758. {Key: "class", Val: "default-link"},
  759. }
  760. node.FirstChild, node.LastChild = ch, ch
  761. }
  762. }
  763. // descriptionLinkProcessor creates links for DescriptionHTML
  764. func descriptionLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  765. m := common.LinkRegex.FindStringIndex(node.Data)
  766. if m == nil {
  767. return
  768. }
  769. uri := node.Data[m[0]:m[1]]
  770. replaceContent(node, m[0], m[1], createDescriptionLink(uri, uri))
  771. }
  772. func createDescriptionLink(href, content string) *html.Node {
  773. textNode := &html.Node{
  774. Type: html.TextNode,
  775. Data: content,
  776. }
  777. linkNode := &html.Node{
  778. FirstChild: textNode,
  779. LastChild: textNode,
  780. Type: html.ElementNode,
  781. Data: "a",
  782. DataAtom: atom.A,
  783. Attr: []html.Attribute{
  784. {Key: "href", Val: href},
  785. {Key: "target", Val: "_blank"},
  786. {Key: "rel", Val: "noopener noreferrer"},
  787. },
  788. }
  789. textNode.Parent = linkNode
  790. return linkNode
  791. }