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

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