You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

html.go 26 kB

Check commit message hashes before making links (#7713) * Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim <gary@garykim.dev> * Use gogit to check if commit exists This commit modifies the commit hash check in the render for commit messages to use gogit for better performance. Signed-off-by: Gary Kim <gary@garykim.dev> * Make code cleaner Signed-off-by: Gary Kim <gary@garykim.dev> * Use rev-parse to check if commit exists Signed-off-by: Gary Kim <gary@garykim.dev> * Add and modify tests for checking hashes in html link rendering Signed-off-by: Gary Kim <gary@garykim.dev> * Return error in sha1CurrentPatternProcessor Co-Authored-By: mrsdizzie <info@mrsdizzie.com> * Import Gitea log module Signed-off-by: Gary Kim <gary@garykim.dev> * Revert "Return error in sha1CurrentPatternProcessor" This reverts commit 28f561cac46ef7e51aa26aefcbe9aca4671366a6. Signed-off-by: Gary Kim <gary@garykim.dev> * Add debug logging to sha1CurrentPatternProcessor This will log errors by the git command run in sha1CurrentPatternProcessor if the error is one that was unexpected. Signed-off-by: Gary Kim <gary@garykim.dev>
6 years ago
Check commit message hashes before making links (#7713) * Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim <gary@garykim.dev> * Use gogit to check if commit exists This commit modifies the commit hash check in the render for commit messages to use gogit for better performance. Signed-off-by: Gary Kim <gary@garykim.dev> * Make code cleaner Signed-off-by: Gary Kim <gary@garykim.dev> * Use rev-parse to check if commit exists Signed-off-by: Gary Kim <gary@garykim.dev> * Add and modify tests for checking hashes in html link rendering Signed-off-by: Gary Kim <gary@garykim.dev> * Return error in sha1CurrentPatternProcessor Co-Authored-By: mrsdizzie <info@mrsdizzie.com> * Import Gitea log module Signed-off-by: Gary Kim <gary@garykim.dev> * Revert "Return error in sha1CurrentPatternProcessor" This reverts commit 28f561cac46ef7e51aa26aefcbe9aca4671366a6. Signed-off-by: Gary Kim <gary@garykim.dev> * Add debug logging to sha1CurrentPatternProcessor This will log errors by the git command run in sha1CurrentPatternProcessor if the error is one that was unexpected. Signed-off-by: Gary Kim <gary@garykim.dev>
6 years ago
Check commit message hashes before making links (#7713) * Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim <gary@garykim.dev> * Use gogit to check if commit exists This commit modifies the commit hash check in the render for commit messages to use gogit for better performance. Signed-off-by: Gary Kim <gary@garykim.dev> * Make code cleaner Signed-off-by: Gary Kim <gary@garykim.dev> * Use rev-parse to check if commit exists Signed-off-by: Gary Kim <gary@garykim.dev> * Add and modify tests for checking hashes in html link rendering Signed-off-by: Gary Kim <gary@garykim.dev> * Return error in sha1CurrentPatternProcessor Co-Authored-By: mrsdizzie <info@mrsdizzie.com> * Import Gitea log module Signed-off-by: Gary Kim <gary@garykim.dev> * Revert "Return error in sha1CurrentPatternProcessor" This reverts commit 28f561cac46ef7e51aa26aefcbe9aca4671366a6. Signed-off-by: Gary Kim <gary@garykim.dev> * Add debug logging to sha1CurrentPatternProcessor This will log errors by the git command run in sha1CurrentPatternProcessor if the error is one that was unexpected. Signed-off-by: Gary Kim <gary@garykim.dev>
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package markup
  5. import (
  6. "bytes"
  7. "net/url"
  8. "path"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/markup/common"
  16. "code.gitea.io/gitea/modules/references"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/util"
  19. "github.com/unknwon/com"
  20. "golang.org/x/net/html"
  21. "golang.org/x/net/html/atom"
  22. "mvdan.cc/xurls/v2"
  23. )
  24. // Issue name styles
  25. const (
  26. IssueNameStyleNumeric = "numeric"
  27. IssueNameStyleAlphanumeric = "alphanumeric"
  28. )
  29. var (
  30. // NOTE: All below regex matching do not perform any extra validation.
  31. // Thus a link is produced even if the linked entity does not exist.
  32. // While fast, this is also incorrect and lead to false positives.
  33. // TODO: fix invalid linking issue
  34. // sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  35. // Although SHA1 hashes are 40 chars long, the regex matches the hash from 7 to 40 chars in length
  36. // so that abbreviated hash links can be used as well. This matches git and github useability.
  37. sha1CurrentPattern = regexp.MustCompile(`(?:\s|^|\(|\[)([0-9a-f]{7,40})(?:\s|$|\)|\]|\.(\s|$))`)
  38. // shortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  39. shortLinkPattern = regexp.MustCompile(`\[\[(.*?)\]\](\w*)`)
  40. // anySHA1Pattern allows to split url containing SHA into parts
  41. anySHA1Pattern = regexp.MustCompile(`https?://(?:\S+/){4}([0-9a-f]{40})(/[^#\s]+)?(#\S+)?`)
  42. validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  43. // While this email regex is definitely not perfect and I'm sure you can come up
  44. // with edge cases, it is still accepted by the CommonMark specification, as
  45. // well as the HTML5 spec:
  46. // http://spec.commonmark.org/0.28/#email-address
  47. // https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type%3Demail)
  48. emailRegex = regexp.MustCompile("(?:\\s|^|\\(|\\[)([a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9]{2,}(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+)(?:\\s|$|\\)|\\]|\\.(\\s|$))")
  49. // blackfriday extensions create IDs like fn:user-content-footnote
  50. blackfridayExtRegex = regexp.MustCompile(`[^:]*:user-content-`)
  51. )
  52. // CSS class for action keywords (e.g. "closes: #1")
  53. const keywordClass = "issue-keyword"
  54. // regexp for full links to issues/pulls
  55. var issueFullPattern *regexp.Regexp
  56. // IsLink reports whether link fits valid format.
  57. func IsLink(link []byte) bool {
  58. return isLink(link)
  59. }
  60. // isLink reports whether link fits valid format.
  61. func isLink(link []byte) bool {
  62. return validLinksPattern.Match(link)
  63. }
  64. func isLinkStr(link string) bool {
  65. return validLinksPattern.MatchString(link)
  66. }
  67. func getIssueFullPattern() *regexp.Regexp {
  68. if issueFullPattern == nil {
  69. appURL := setting.AppURL
  70. if len(appURL) > 0 && appURL[len(appURL)-1] != '/' {
  71. appURL += "/"
  72. }
  73. issueFullPattern = regexp.MustCompile(appURL +
  74. `\w+/\w+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`)
  75. }
  76. return issueFullPattern
  77. }
  78. // CustomLinkURLSchemes allows for additional schemes to be detected when parsing links within text
  79. func CustomLinkURLSchemes(schemes []string) {
  80. schemes = append(schemes, "http", "https")
  81. withAuth := make([]string, 0, len(schemes))
  82. validScheme := regexp.MustCompile(`^[a-z]+$`)
  83. for _, s := range schemes {
  84. if !validScheme.MatchString(s) {
  85. continue
  86. }
  87. without := false
  88. for _, sna := range xurls.SchemesNoAuthority {
  89. if s == sna {
  90. without = true
  91. break
  92. }
  93. }
  94. if without {
  95. s += ":"
  96. } else {
  97. s += "://"
  98. }
  99. withAuth = append(withAuth, s)
  100. }
  101. common.LinkRegex, _ = xurls.StrictMatchingScheme(strings.Join(withAuth, "|"))
  102. }
  103. // IsSameDomain checks if given url string has the same hostname as current Gitea instance
  104. func IsSameDomain(s string) bool {
  105. if strings.HasPrefix(s, "/") {
  106. return true
  107. }
  108. if uapp, err := url.Parse(setting.AppURL); err == nil {
  109. if u, err := url.Parse(s); err == nil {
  110. return u.Host == uapp.Host
  111. }
  112. return false
  113. }
  114. return false
  115. }
  116. type postProcessError struct {
  117. context string
  118. err error
  119. }
  120. func (p *postProcessError) Error() string {
  121. return "PostProcess: " + p.context + ", " + p.err.Error()
  122. }
  123. type processor func(ctx *postProcessCtx, node *html.Node)
  124. var defaultProcessors = []processor{
  125. fullIssuePatternProcessor,
  126. fullSha1PatternProcessor,
  127. shortLinkProcessor,
  128. linkProcessor,
  129. mentionProcessor,
  130. issueIndexPatternProcessor,
  131. sha1CurrentPatternProcessor,
  132. emailAddressProcessor,
  133. }
  134. type postProcessCtx struct {
  135. metas map[string]string
  136. urlPrefix string
  137. isWikiMarkdown bool
  138. // processors used by this context.
  139. procs []processor
  140. }
  141. // PostProcess does the final required transformations to the passed raw HTML
  142. // data, and ensures its validity. Transformations include: replacing links and
  143. // emails with HTML links, parsing shortlinks in the format of [[Link]], like
  144. // MediaWiki, linking issues in the format #ID, and mentions in the format
  145. // @user, and others.
  146. func PostProcess(
  147. rawHTML []byte,
  148. urlPrefix string,
  149. metas map[string]string,
  150. isWikiMarkdown bool,
  151. ) ([]byte, error) {
  152. // create the context from the parameters
  153. ctx := &postProcessCtx{
  154. metas: metas,
  155. urlPrefix: urlPrefix,
  156. isWikiMarkdown: isWikiMarkdown,
  157. procs: defaultProcessors,
  158. }
  159. return ctx.postProcess(rawHTML)
  160. }
  161. var commitMessageProcessors = []processor{
  162. fullIssuePatternProcessor,
  163. fullSha1PatternProcessor,
  164. linkProcessor,
  165. mentionProcessor,
  166. issueIndexPatternProcessor,
  167. sha1CurrentPatternProcessor,
  168. emailAddressProcessor,
  169. }
  170. // RenderCommitMessage will use the same logic as PostProcess, but will disable
  171. // the shortLinkProcessor and will add a defaultLinkProcessor if defaultLink is
  172. // set, which changes every text node into a link to the passed default link.
  173. func RenderCommitMessage(
  174. rawHTML []byte,
  175. urlPrefix, defaultLink string,
  176. metas map[string]string,
  177. ) ([]byte, error) {
  178. ctx := &postProcessCtx{
  179. metas: metas,
  180. urlPrefix: urlPrefix,
  181. procs: commitMessageProcessors,
  182. }
  183. if defaultLink != "" {
  184. // we don't have to fear data races, because being
  185. // commitMessageProcessors of fixed len and cap, every time we append
  186. // something to it the slice is realloc+copied, so append always
  187. // generates the slice ex-novo.
  188. ctx.procs = append(ctx.procs, genDefaultLinkProcessor(defaultLink))
  189. }
  190. return ctx.postProcess(rawHTML)
  191. }
  192. var commitMessageSubjectProcessors = []processor{
  193. fullIssuePatternProcessor,
  194. fullSha1PatternProcessor,
  195. linkProcessor,
  196. mentionProcessor,
  197. issueIndexPatternProcessor,
  198. sha1CurrentPatternProcessor,
  199. }
  200. // RenderCommitMessageSubject will use the same logic as PostProcess and
  201. // RenderCommitMessage, but will disable the shortLinkProcessor and
  202. // emailAddressProcessor, will add a defaultLinkProcessor if defaultLink is set,
  203. // which changes every text node into a link to the passed default link.
  204. func RenderCommitMessageSubject(
  205. rawHTML []byte,
  206. urlPrefix, defaultLink string,
  207. metas map[string]string,
  208. ) ([]byte, error) {
  209. ctx := &postProcessCtx{
  210. metas: metas,
  211. urlPrefix: urlPrefix,
  212. procs: commitMessageSubjectProcessors,
  213. }
  214. if defaultLink != "" {
  215. // we don't have to fear data races, because being
  216. // commitMessageSubjectProcessors of fixed len and cap, every time we
  217. // append something to it the slice is realloc+copied, so append always
  218. // generates the slice ex-novo.
  219. ctx.procs = append(ctx.procs, genDefaultLinkProcessor(defaultLink))
  220. }
  221. return ctx.postProcess(rawHTML)
  222. }
  223. // RenderDescriptionHTML will use similar logic as PostProcess, but will
  224. // use a single special linkProcessor.
  225. func RenderDescriptionHTML(
  226. rawHTML []byte,
  227. urlPrefix string,
  228. metas map[string]string,
  229. ) ([]byte, error) {
  230. ctx := &postProcessCtx{
  231. metas: metas,
  232. urlPrefix: urlPrefix,
  233. procs: []processor{
  234. descriptionLinkProcessor,
  235. },
  236. }
  237. return ctx.postProcess(rawHTML)
  238. }
  239. var byteBodyTag = []byte("<body>")
  240. var byteBodyTagClosing = []byte("</body>")
  241. func (ctx *postProcessCtx) postProcess(rawHTML []byte) ([]byte, error) {
  242. if ctx.procs == nil {
  243. ctx.procs = defaultProcessors
  244. }
  245. // give a generous extra 50 bytes
  246. res := make([]byte, 0, len(rawHTML)+50)
  247. res = append(res, byteBodyTag...)
  248. res = append(res, rawHTML...)
  249. res = append(res, byteBodyTagClosing...)
  250. // parse the HTML
  251. nodes, err := html.ParseFragment(bytes.NewReader(res), nil)
  252. if err != nil {
  253. return nil, &postProcessError{"invalid HTML", err}
  254. }
  255. for _, node := range nodes {
  256. ctx.visitNode(node, true)
  257. }
  258. // Create buffer in which the data will be placed again. We know that the
  259. // length will be at least that of res; to spare a few alloc+copy, we
  260. // reuse res, resetting its length to 0.
  261. buf := bytes.NewBuffer(res[:0])
  262. // Render everything to buf.
  263. for _, node := range nodes {
  264. err = html.Render(buf, node)
  265. if err != nil {
  266. return nil, &postProcessError{"error rendering processed HTML", err}
  267. }
  268. }
  269. // remove initial parts - because Render creates a whole HTML page.
  270. res = buf.Bytes()
  271. res = res[bytes.Index(res, byteBodyTag)+len(byteBodyTag) : bytes.LastIndex(res, byteBodyTagClosing)]
  272. // Everything done successfully, return parsed data.
  273. return res, nil
  274. }
  275. func (ctx *postProcessCtx) visitNode(node *html.Node, visitText bool) {
  276. // Add user-content- to IDs if they don't already have them
  277. for idx, attr := range node.Attr {
  278. if attr.Key == "id" && !(strings.HasPrefix(attr.Val, "user-content-") || blackfridayExtRegex.MatchString(attr.Val)) {
  279. node.Attr[idx].Val = "user-content-" + attr.Val
  280. }
  281. }
  282. // We ignore code, pre and already generated links.
  283. switch node.Type {
  284. case html.TextNode:
  285. if visitText {
  286. ctx.textNode(node)
  287. }
  288. case html.ElementNode:
  289. if node.Data == "img" {
  290. attrs := node.Attr
  291. for idx, attr := range attrs {
  292. if attr.Key != "src" {
  293. continue
  294. }
  295. link := []byte(attr.Val)
  296. if len(link) > 0 && !IsLink(link) {
  297. prefix := ctx.urlPrefix
  298. if ctx.isWikiMarkdown {
  299. prefix = util.URLJoin(prefix, "wiki", "raw")
  300. }
  301. prefix = strings.Replace(prefix, "/src/", "/media/", 1)
  302. lnk := string(link)
  303. lnk = util.URLJoin(prefix, lnk)
  304. link = []byte(lnk)
  305. }
  306. node.Attr[idx].Val = string(link)
  307. }
  308. } else if node.Data == "a" {
  309. visitText = false
  310. } else if node.Data == "code" || node.Data == "pre" {
  311. return
  312. } else if node.Data == "i" {
  313. for _, attr := range node.Attr {
  314. if attr.Key != "class" {
  315. continue
  316. }
  317. classes := strings.Split(attr.Val, " ")
  318. for i, class := range classes {
  319. if class == "icon" {
  320. classes[0], classes[i] = classes[i], classes[0]
  321. attr.Val = strings.Join(classes, " ")
  322. // Remove all children of icons
  323. child := node.FirstChild
  324. for child != nil {
  325. node.RemoveChild(child)
  326. child = node.FirstChild
  327. }
  328. break
  329. }
  330. }
  331. }
  332. }
  333. for n := node.FirstChild; n != nil; n = n.NextSibling {
  334. ctx.visitNode(n, visitText)
  335. }
  336. }
  337. // ignore everything else
  338. }
  339. // textNode runs the passed node through various processors, in order to handle
  340. // all kinds of special links handled by the post-processing.
  341. func (ctx *postProcessCtx) textNode(node *html.Node) {
  342. for _, processor := range ctx.procs {
  343. processor(ctx, node)
  344. }
  345. }
  346. // createKeyword() renders a highlighted version of an action keyword
  347. func createKeyword(content string) *html.Node {
  348. span := &html.Node{
  349. Type: html.ElementNode,
  350. Data: atom.Span.String(),
  351. Attr: []html.Attribute{},
  352. }
  353. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: keywordClass})
  354. text := &html.Node{
  355. Type: html.TextNode,
  356. Data: content,
  357. }
  358. span.AppendChild(text)
  359. return span
  360. }
  361. func createLink(href, content, class string) *html.Node {
  362. a := &html.Node{
  363. Type: html.ElementNode,
  364. Data: atom.A.String(),
  365. Attr: []html.Attribute{{Key: "href", Val: href}},
  366. }
  367. if class != "" {
  368. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  369. }
  370. text := &html.Node{
  371. Type: html.TextNode,
  372. Data: content,
  373. }
  374. a.AppendChild(text)
  375. return a
  376. }
  377. func createCodeLink(href, content, class string) *html.Node {
  378. a := &html.Node{
  379. Type: html.ElementNode,
  380. Data: atom.A.String(),
  381. Attr: []html.Attribute{{Key: "href", Val: href}},
  382. }
  383. if class != "" {
  384. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  385. }
  386. text := &html.Node{
  387. Type: html.TextNode,
  388. Data: content,
  389. }
  390. code := &html.Node{
  391. Type: html.ElementNode,
  392. Data: atom.Code.String(),
  393. Attr: []html.Attribute{{Key: "class", Val: "nohighlight"}},
  394. }
  395. code.AppendChild(text)
  396. a.AppendChild(code)
  397. return a
  398. }
  399. // replaceContent takes text node, and in its content it replaces a section of
  400. // it with the specified newNode.
  401. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  402. replaceContentList(node, i, j, []*html.Node{newNode})
  403. }
  404. // replaceContentList takes text node, and in its content it replaces a section of
  405. // it with the specified newNodes. An example to visualize how this can work can
  406. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  407. func replaceContentList(node *html.Node, i, j int, newNodes []*html.Node) {
  408. // get the data before and after the match
  409. before := node.Data[:i]
  410. after := node.Data[j:]
  411. // Replace in the current node the text, so that it is only what it is
  412. // supposed to have.
  413. node.Data = before
  414. // Get the current next sibling, before which we place the replaced data,
  415. // and after that we place the new text node.
  416. nextSibling := node.NextSibling
  417. for _, n := range newNodes {
  418. node.Parent.InsertBefore(n, nextSibling)
  419. }
  420. if after != "" {
  421. node.Parent.InsertBefore(&html.Node{
  422. Type: html.TextNode,
  423. Data: after,
  424. }, nextSibling)
  425. }
  426. }
  427. func mentionProcessor(ctx *postProcessCtx, node *html.Node) {
  428. // We replace only the first mention; other mentions will be addressed later
  429. found, loc := references.FindFirstMentionBytes([]byte(node.Data))
  430. if !found {
  431. return
  432. }
  433. mention := node.Data[loc.Start:loc.End]
  434. var teams string
  435. teams, ok := ctx.metas["teams"]
  436. if ok && strings.Contains(teams, ","+strings.ToLower(mention[1:])+",") {
  437. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, "org", ctx.metas["org"], "teams", mention[1:]), mention, "mention"))
  438. } else {
  439. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, mention[1:]), mention, "mention"))
  440. }
  441. }
  442. func shortLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  443. shortLinkProcessorFull(ctx, node, false)
  444. }
  445. func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
  446. m := shortLinkPattern.FindStringSubmatchIndex(node.Data)
  447. if m == nil {
  448. return
  449. }
  450. content := node.Data[m[2]:m[3]]
  451. tail := node.Data[m[4]:m[5]]
  452. props := make(map[string]string)
  453. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  454. // It makes page handling terrible, but we prefer GitHub syntax
  455. // And fall back to MediaWiki only when it is obvious from the look
  456. // Of text and link contents
  457. sl := strings.Split(content, "|")
  458. for _, v := range sl {
  459. if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
  460. // There is no equal in this argument; this is a mandatory arg
  461. if props["name"] == "" {
  462. if isLinkStr(v) {
  463. // If we clearly see it is a link, we save it so
  464. // But first we need to ensure, that if both mandatory args provided
  465. // look like links, we stick to GitHub syntax
  466. if props["link"] != "" {
  467. props["name"] = props["link"]
  468. }
  469. props["link"] = strings.TrimSpace(v)
  470. } else {
  471. props["name"] = v
  472. }
  473. } else {
  474. props["link"] = strings.TrimSpace(v)
  475. }
  476. } else {
  477. // There is an equal; optional argument.
  478. sep := strings.IndexByte(v, '=')
  479. key, val := v[:sep], html.UnescapeString(v[sep+1:])
  480. // When parsing HTML, x/net/html will change all quotes which are
  481. // not used for syntax into UTF-8 quotes. So checking val[0] won't
  482. // be enough, since that only checks a single byte.
  483. if (strings.HasPrefix(val, "“") && strings.HasSuffix(val, "”")) ||
  484. (strings.HasPrefix(val, "‘") && strings.HasSuffix(val, "’")) {
  485. const lenQuote = len("‘")
  486. val = val[lenQuote : len(val)-lenQuote]
  487. } else if (strings.HasPrefix(val, "\"") && strings.HasSuffix(val, "\"")) ||
  488. (strings.HasPrefix(val, "'") && strings.HasSuffix(val, "'")) {
  489. val = val[1 : len(val)-1]
  490. } else if strings.HasPrefix(val, "'") && strings.HasSuffix(val, "’") {
  491. const lenQuote = len("‘")
  492. val = val[1 : len(val)-lenQuote]
  493. }
  494. props[key] = val
  495. }
  496. }
  497. var name, link string
  498. if props["link"] != "" {
  499. link = props["link"]
  500. } else if props["name"] != "" {
  501. link = props["name"]
  502. }
  503. if props["title"] != "" {
  504. name = props["title"]
  505. } else if props["name"] != "" {
  506. name = props["name"]
  507. } else {
  508. name = link
  509. }
  510. name += tail
  511. image := false
  512. switch ext := filepath.Ext(link); ext {
  513. // fast path: empty string, ignore
  514. case "":
  515. break
  516. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  517. image = true
  518. }
  519. childNode := &html.Node{}
  520. linkNode := &html.Node{
  521. FirstChild: childNode,
  522. LastChild: childNode,
  523. Type: html.ElementNode,
  524. Data: "a",
  525. DataAtom: atom.A,
  526. }
  527. childNode.Parent = linkNode
  528. absoluteLink := isLinkStr(link)
  529. if !absoluteLink {
  530. if image {
  531. link = strings.Replace(link, " ", "+", -1)
  532. } else {
  533. link = strings.Replace(link, " ", "-", -1)
  534. }
  535. if !strings.Contains(link, "/") {
  536. link = url.PathEscape(link)
  537. }
  538. }
  539. urlPrefix := ctx.urlPrefix
  540. if image {
  541. if !absoluteLink {
  542. if IsSameDomain(urlPrefix) {
  543. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  544. }
  545. if ctx.isWikiMarkdown {
  546. link = util.URLJoin("wiki", "raw", link)
  547. }
  548. link = util.URLJoin(urlPrefix, link)
  549. }
  550. title := props["title"]
  551. if title == "" {
  552. title = props["alt"]
  553. }
  554. if title == "" {
  555. title = path.Base(name)
  556. }
  557. alt := props["alt"]
  558. if alt == "" {
  559. alt = name
  560. }
  561. // make the childNode an image - if we can, we also place the alt
  562. childNode.Type = html.ElementNode
  563. childNode.Data = "img"
  564. childNode.DataAtom = atom.Img
  565. childNode.Attr = []html.Attribute{
  566. {Key: "src", Val: link},
  567. {Key: "title", Val: title},
  568. {Key: "alt", Val: alt},
  569. }
  570. if alt == "" {
  571. childNode.Attr = childNode.Attr[:2]
  572. }
  573. } else {
  574. if !absoluteLink {
  575. if ctx.isWikiMarkdown {
  576. link = util.URLJoin("wiki", link)
  577. }
  578. link = util.URLJoin(urlPrefix, link)
  579. }
  580. childNode.Type = html.TextNode
  581. childNode.Data = name
  582. }
  583. if noLink {
  584. linkNode = childNode
  585. } else {
  586. linkNode.Attr = []html.Attribute{{Key: "href", Val: link}}
  587. }
  588. replaceContent(node, m[0], m[1], linkNode)
  589. }
  590. func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) {
  591. if ctx.metas == nil {
  592. return
  593. }
  594. m := getIssueFullPattern().FindStringSubmatchIndex(node.Data)
  595. if m == nil {
  596. return
  597. }
  598. link := node.Data[m[0]:m[1]]
  599. id := "#" + node.Data[m[2]:m[3]]
  600. // extract repo and org name from matched link like
  601. // http://localhost:3000/gituser/myrepo/issues/1
  602. linkParts := strings.Split(path.Clean(link), "/")
  603. matchOrg := linkParts[len(linkParts)-4]
  604. matchRepo := linkParts[len(linkParts)-3]
  605. if matchOrg == ctx.metas["user"] && matchRepo == ctx.metas["repo"] {
  606. // TODO if m[4]:m[5] is not nil, then link is to a comment,
  607. // and we should indicate that in the text somehow
  608. replaceContent(node, m[0], m[1], createLink(link, id, "ref-issue"))
  609. } else {
  610. orgRepoID := matchOrg + "/" + matchRepo + id
  611. replaceContent(node, m[0], m[1], createLink(link, orgRepoID, "ref-issue"))
  612. }
  613. }
  614. func issueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  615. if ctx.metas == nil {
  616. return
  617. }
  618. var (
  619. found bool
  620. ref *references.RenderizableReference
  621. )
  622. _, exttrack := ctx.metas["format"]
  623. alphanum := ctx.metas["style"] == IssueNameStyleAlphanumeric
  624. // Repos with external issue trackers might still need to reference local PRs
  625. // We need to concern with the first one that shows up in the text, whichever it is
  626. found, ref = references.FindRenderizableReferenceNumeric(node.Data, exttrack && alphanum)
  627. if exttrack && alphanum {
  628. if found2, ref2 := references.FindRenderizableReferenceAlphanumeric(node.Data); found2 {
  629. if !found || ref2.RefLocation.Start < ref.RefLocation.Start {
  630. found = true
  631. ref = ref2
  632. }
  633. }
  634. }
  635. if !found {
  636. return
  637. }
  638. var link *html.Node
  639. reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End]
  640. if exttrack && !ref.IsPull {
  641. ctx.metas["index"] = ref.Issue
  642. link = createLink(com.Expand(ctx.metas["format"], ctx.metas), reftext, "ref-issue")
  643. } else {
  644. // Path determines the type of link that will be rendered. It's unknown at this point whether
  645. // the linked item is actually a PR or an issue. Luckily it's of no real consequence because
  646. // Gitea will redirect on click as appropriate.
  647. path := "issues"
  648. if ref.IsPull {
  649. path = "pulls"
  650. }
  651. if ref.Owner == "" {
  652. link = createLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], path, ref.Issue), reftext, "ref-issue")
  653. } else {
  654. link = createLink(util.URLJoin(setting.AppURL, ref.Owner, ref.Name, path, ref.Issue), reftext, "ref-issue")
  655. }
  656. }
  657. if ref.Action == references.XRefActionNone {
  658. replaceContent(node, ref.RefLocation.Start, ref.RefLocation.End, link)
  659. return
  660. }
  661. // Decorate action keywords if actionable
  662. var keyword *html.Node
  663. if references.IsXrefActionable(ref, exttrack, alphanum) {
  664. keyword = createKeyword(node.Data[ref.ActionLocation.Start:ref.ActionLocation.End])
  665. } else {
  666. keyword = &html.Node{
  667. Type: html.TextNode,
  668. Data: node.Data[ref.ActionLocation.Start:ref.ActionLocation.End],
  669. }
  670. }
  671. spaces := &html.Node{
  672. Type: html.TextNode,
  673. Data: node.Data[ref.ActionLocation.End:ref.RefLocation.Start],
  674. }
  675. replaceContentList(node, ref.ActionLocation.Start, ref.RefLocation.End, []*html.Node{keyword, spaces, link})
  676. }
  677. // fullSha1PatternProcessor renders SHA containing URLs
  678. func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) {
  679. if ctx.metas == nil {
  680. return
  681. }
  682. m := anySHA1Pattern.FindStringSubmatchIndex(node.Data)
  683. if m == nil {
  684. return
  685. }
  686. urlFull := node.Data[m[0]:m[1]]
  687. text := base.ShortSha(node.Data[m[2]:m[3]])
  688. // 3rd capture group matches a optional path
  689. subpath := ""
  690. if m[5] > 0 {
  691. subpath = node.Data[m[4]:m[5]]
  692. }
  693. // 4th capture group matches a optional url hash
  694. hash := ""
  695. if m[7] > 0 {
  696. hash = node.Data[m[6]:m[7]][1:]
  697. }
  698. start := m[0]
  699. end := m[1]
  700. // If url ends in '.', it's very likely that it is not part of the
  701. // actual url but used to finish a sentence.
  702. if strings.HasSuffix(urlFull, ".") {
  703. end--
  704. urlFull = urlFull[:len(urlFull)-1]
  705. if hash != "" {
  706. hash = hash[:len(hash)-1]
  707. } else if subpath != "" {
  708. subpath = subpath[:len(subpath)-1]
  709. }
  710. }
  711. if subpath != "" {
  712. text += subpath
  713. }
  714. if hash != "" {
  715. text += " (" + hash + ")"
  716. }
  717. replaceContent(node, start, end, createCodeLink(urlFull, text, "commit"))
  718. }
  719. // sha1CurrentPatternProcessor renders SHA1 strings to corresponding links that
  720. // are assumed to be in the same repository.
  721. func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  722. if ctx.metas == nil || ctx.metas["user"] == "" || ctx.metas["repo"] == "" || ctx.metas["repoPath"] == "" {
  723. return
  724. }
  725. m := sha1CurrentPattern.FindStringSubmatchIndex(node.Data)
  726. if m == nil {
  727. return
  728. }
  729. hash := node.Data[m[2]:m[3]]
  730. // The regex does not lie, it matches the hash pattern.
  731. // However, a regex cannot know if a hash actually exists or not.
  732. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  733. // but that is not always the case.
  734. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  735. // as used by git and github for linking and thus we have to do similar.
  736. // Because of this, we check to make sure that a matched hash is actually
  737. // a commit in the repository before making it a link.
  738. if _, err := git.NewCommand("rev-parse", "--verify", hash).RunInDirBytes(ctx.metas["repoPath"]); err != nil {
  739. if !strings.Contains(err.Error(), "fatal: Needed a single revision") {
  740. log.Debug("sha1CurrentPatternProcessor git rev-parse: %v", err)
  741. }
  742. return
  743. }
  744. replaceContent(node, m[2], m[3],
  745. createCodeLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], "commit", hash), base.ShortSha(hash), "commit"))
  746. }
  747. // emailAddressProcessor replaces raw email addresses with a mailto: link.
  748. func emailAddressProcessor(ctx *postProcessCtx, node *html.Node) {
  749. m := emailRegex.FindStringSubmatchIndex(node.Data)
  750. if m == nil {
  751. return
  752. }
  753. mail := node.Data[m[2]:m[3]]
  754. replaceContent(node, m[2], m[3], createLink("mailto:"+mail, mail, "mailto"))
  755. }
  756. // linkProcessor creates links for any HTTP or HTTPS URL not captured by
  757. // markdown.
  758. func linkProcessor(ctx *postProcessCtx, node *html.Node) {
  759. m := common.LinkRegex.FindStringIndex(node.Data)
  760. if m == nil {
  761. return
  762. }
  763. uri := node.Data[m[0]:m[1]]
  764. replaceContent(node, m[0], m[1], createLink(uri, uri, "link"))
  765. }
  766. func genDefaultLinkProcessor(defaultLink string) processor {
  767. return func(ctx *postProcessCtx, node *html.Node) {
  768. ch := &html.Node{
  769. Parent: node,
  770. Type: html.TextNode,
  771. Data: node.Data,
  772. }
  773. node.Type = html.ElementNode
  774. node.Data = "a"
  775. node.DataAtom = atom.A
  776. node.Attr = []html.Attribute{
  777. {Key: "href", Val: defaultLink},
  778. {Key: "class", Val: "default-link"},
  779. }
  780. node.FirstChild, node.LastChild = ch, ch
  781. }
  782. }
  783. // descriptionLinkProcessor creates links for DescriptionHTML
  784. func descriptionLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  785. m := common.LinkRegex.FindStringIndex(node.Data)
  786. if m == nil {
  787. return
  788. }
  789. uri := node.Data[m[0]:m[1]]
  790. replaceContent(node, m[0], m[1], createDescriptionLink(uri, uri))
  791. }
  792. func createDescriptionLink(href, content string) *html.Node {
  793. textNode := &html.Node{
  794. Type: html.TextNode,
  795. Data: content,
  796. }
  797. linkNode := &html.Node{
  798. FirstChild: textNode,
  799. LastChild: textNode,
  800. Type: html.ElementNode,
  801. Data: "a",
  802. DataAtom: atom.A,
  803. Attr: []html.Attribute{
  804. {Key: "href", Val: href},
  805. {Key: "target", Val: "_blank"},
  806. {Key: "rel", Val: "noopener noreferrer"},
  807. },
  808. }
  809. textNode.Parent = linkNode
  810. return linkNode
  811. }