Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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