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

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