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

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