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 25 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>
5 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>
5 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>
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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/references"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. "github.com/unknwon/com"
  19. "golang.org/x/net/html"
  20. "golang.org/x/net/html/atom"
  21. "mvdan.cc/xurls/v2"
  22. )
  23. // Issue name styles
  24. const (
  25. IssueNameStyleNumeric = "numeric"
  26. IssueNameStyleAlphanumeric = "alphanumeric"
  27. )
  28. var (
  29. // NOTE: All below regex matching do not perform any extra validation.
  30. // Thus a link is produced even if the linked entity does not exist.
  31. // While fast, this is also incorrect and lead to false positives.
  32. // TODO: fix invalid linking issue
  33. // sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  34. // Although SHA1 hashes are 40 chars long, the regex matches the hash from 7 to 40 chars in length
  35. // so that abbreviated hash links can be used as well. This matches git and github useability.
  36. sha1CurrentPattern = regexp.MustCompile(`(?:\s|^|\(|\[)([0-9a-f]{7,40})(?:\s|$|\)|\]|\.(\s|$))`)
  37. // shortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  38. shortLinkPattern = regexp.MustCompile(`\[\[(.*?)\]\](\w*)`)
  39. // anySHA1Pattern allows to split url containing SHA into parts
  40. anySHA1Pattern = regexp.MustCompile(`https?://(?:\S+/){4}([0-9a-f]{40})(/[^#\s]+)?(#\S+)?`)
  41. validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  42. // While this email regex is definitely not perfect and I'm sure you can come up
  43. // with edge cases, it is still accepted by the CommonMark specification, as
  44. // well as the HTML5 spec:
  45. // http://spec.commonmark.org/0.28/#email-address
  46. // https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type%3Demail)
  47. 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|$))")
  48. linkRegex, _ = xurls.StrictMatchingScheme("https?://")
  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. 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)
  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) {
  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. ctx.textNode(node)
  286. case html.ElementNode:
  287. if node.Data == "a" || node.Data == "code" || node.Data == "pre" {
  288. return
  289. }
  290. for n := node.FirstChild; n != nil; n = n.NextSibling {
  291. ctx.visitNode(n)
  292. }
  293. }
  294. // ignore everything else
  295. }
  296. // textNode runs the passed node through various processors, in order to handle
  297. // all kinds of special links handled by the post-processing.
  298. func (ctx *postProcessCtx) textNode(node *html.Node) {
  299. for _, processor := range ctx.procs {
  300. processor(ctx, node)
  301. }
  302. }
  303. // createKeyword() renders a highlighted version of an action keyword
  304. func createKeyword(content string) *html.Node {
  305. span := &html.Node{
  306. Type: html.ElementNode,
  307. Data: atom.Span.String(),
  308. Attr: []html.Attribute{},
  309. }
  310. span.Attr = append(span.Attr, html.Attribute{Key: "class", Val: keywordClass})
  311. text := &html.Node{
  312. Type: html.TextNode,
  313. Data: content,
  314. }
  315. span.AppendChild(text)
  316. return span
  317. }
  318. func createLink(href, content, class string) *html.Node {
  319. a := &html.Node{
  320. Type: html.ElementNode,
  321. Data: atom.A.String(),
  322. Attr: []html.Attribute{{Key: "href", Val: href}},
  323. }
  324. if class != "" {
  325. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  326. }
  327. text := &html.Node{
  328. Type: html.TextNode,
  329. Data: content,
  330. }
  331. a.AppendChild(text)
  332. return a
  333. }
  334. func createCodeLink(href, content, class string) *html.Node {
  335. a := &html.Node{
  336. Type: html.ElementNode,
  337. Data: atom.A.String(),
  338. Attr: []html.Attribute{{Key: "href", Val: href}},
  339. }
  340. if class != "" {
  341. a.Attr = append(a.Attr, html.Attribute{Key: "class", Val: class})
  342. }
  343. text := &html.Node{
  344. Type: html.TextNode,
  345. Data: content,
  346. }
  347. code := &html.Node{
  348. Type: html.ElementNode,
  349. Data: atom.Code.String(),
  350. Attr: []html.Attribute{{Key: "class", Val: "nohighlight"}},
  351. }
  352. code.AppendChild(text)
  353. a.AppendChild(code)
  354. return a
  355. }
  356. // replaceContent takes text node, and in its content it replaces a section of
  357. // it with the specified newNode.
  358. func replaceContent(node *html.Node, i, j int, newNode *html.Node) {
  359. replaceContentList(node, i, j, []*html.Node{newNode})
  360. }
  361. // replaceContentList takes text node, and in its content it replaces a section of
  362. // it with the specified newNodes. An example to visualize how this can work can
  363. // be found here: https://play.golang.org/p/5zP8NnHZ03s
  364. func replaceContentList(node *html.Node, i, j int, newNodes []*html.Node) {
  365. // get the data before and after the match
  366. before := node.Data[:i]
  367. after := node.Data[j:]
  368. // Replace in the current node the text, so that it is only what it is
  369. // supposed to have.
  370. node.Data = before
  371. // Get the current next sibling, before which we place the replaced data,
  372. // and after that we place the new text node.
  373. nextSibling := node.NextSibling
  374. for _, n := range newNodes {
  375. node.Parent.InsertBefore(n, nextSibling)
  376. }
  377. if after != "" {
  378. node.Parent.InsertBefore(&html.Node{
  379. Type: html.TextNode,
  380. Data: after,
  381. }, nextSibling)
  382. }
  383. }
  384. func mentionProcessor(ctx *postProcessCtx, node *html.Node) {
  385. // We replace only the first mention; other mentions will be addressed later
  386. found, loc := references.FindFirstMentionBytes([]byte(node.Data))
  387. if !found {
  388. return
  389. }
  390. mention := node.Data[loc.Start:loc.End]
  391. var teams string
  392. teams, ok := ctx.metas["teams"]
  393. if ok && strings.Contains(teams, ","+strings.ToLower(mention[1:])+",") {
  394. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, "org", ctx.metas["org"], "teams", mention[1:]), mention, "mention"))
  395. } else {
  396. replaceContent(node, loc.Start, loc.End, createLink(util.URLJoin(setting.AppURL, mention[1:]), mention, "mention"))
  397. }
  398. }
  399. func shortLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  400. shortLinkProcessorFull(ctx, node, false)
  401. }
  402. func shortLinkProcessorFull(ctx *postProcessCtx, node *html.Node, noLink bool) {
  403. m := shortLinkPattern.FindStringSubmatchIndex(node.Data)
  404. if m == nil {
  405. return
  406. }
  407. content := node.Data[m[2]:m[3]]
  408. tail := node.Data[m[4]:m[5]]
  409. props := make(map[string]string)
  410. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  411. // It makes page handling terrible, but we prefer GitHub syntax
  412. // And fall back to MediaWiki only when it is obvious from the look
  413. // Of text and link contents
  414. sl := strings.Split(content, "|")
  415. for _, v := range sl {
  416. if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
  417. // There is no equal in this argument; this is a mandatory arg
  418. if props["name"] == "" {
  419. if isLinkStr(v) {
  420. // If we clearly see it is a link, we save it so
  421. // But first we need to ensure, that if both mandatory args provided
  422. // look like links, we stick to GitHub syntax
  423. if props["link"] != "" {
  424. props["name"] = props["link"]
  425. }
  426. props["link"] = strings.TrimSpace(v)
  427. } else {
  428. props["name"] = v
  429. }
  430. } else {
  431. props["link"] = strings.TrimSpace(v)
  432. }
  433. } else {
  434. // There is an equal; optional argument.
  435. sep := strings.IndexByte(v, '=')
  436. key, val := v[:sep], html.UnescapeString(v[sep+1:])
  437. // When parsing HTML, x/net/html will change all quotes which are
  438. // not used for syntax into UTF-8 quotes. So checking val[0] won't
  439. // be enough, since that only checks a single byte.
  440. if (strings.HasPrefix(val, "“") && strings.HasSuffix(val, "”")) ||
  441. (strings.HasPrefix(val, "‘") && strings.HasSuffix(val, "’")) {
  442. const lenQuote = len("‘")
  443. val = val[lenQuote : len(val)-lenQuote]
  444. }
  445. props[key] = val
  446. }
  447. }
  448. var name, link string
  449. if props["link"] != "" {
  450. link = props["link"]
  451. } else if props["name"] != "" {
  452. link = props["name"]
  453. }
  454. if props["title"] != "" {
  455. name = props["title"]
  456. } else if props["name"] != "" {
  457. name = props["name"]
  458. } else {
  459. name = link
  460. }
  461. name += tail
  462. image := false
  463. switch ext := filepath.Ext(link); ext {
  464. // fast path: empty string, ignore
  465. case "":
  466. break
  467. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  468. image = true
  469. }
  470. childNode := &html.Node{}
  471. linkNode := &html.Node{
  472. FirstChild: childNode,
  473. LastChild: childNode,
  474. Type: html.ElementNode,
  475. Data: "a",
  476. DataAtom: atom.A,
  477. }
  478. childNode.Parent = linkNode
  479. absoluteLink := isLinkStr(link)
  480. if !absoluteLink {
  481. if image {
  482. link = strings.Replace(link, " ", "+", -1)
  483. } else {
  484. link = strings.Replace(link, " ", "-", -1)
  485. }
  486. if !strings.Contains(link, "/") {
  487. link = url.PathEscape(link)
  488. }
  489. }
  490. urlPrefix := ctx.urlPrefix
  491. if image {
  492. if !absoluteLink {
  493. if IsSameDomain(urlPrefix) {
  494. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  495. }
  496. if ctx.isWikiMarkdown {
  497. link = util.URLJoin("wiki", "raw", link)
  498. }
  499. link = util.URLJoin(urlPrefix, link)
  500. }
  501. title := props["title"]
  502. if title == "" {
  503. title = props["alt"]
  504. }
  505. if title == "" {
  506. title = path.Base(name)
  507. }
  508. alt := props["alt"]
  509. if alt == "" {
  510. alt = name
  511. }
  512. // make the childNode an image - if we can, we also place the alt
  513. childNode.Type = html.ElementNode
  514. childNode.Data = "img"
  515. childNode.DataAtom = atom.Img
  516. childNode.Attr = []html.Attribute{
  517. {Key: "src", Val: link},
  518. {Key: "title", Val: title},
  519. {Key: "alt", Val: alt},
  520. }
  521. if alt == "" {
  522. childNode.Attr = childNode.Attr[:2]
  523. }
  524. } else {
  525. if !absoluteLink {
  526. if ctx.isWikiMarkdown {
  527. link = util.URLJoin("wiki", link)
  528. }
  529. link = util.URLJoin(urlPrefix, link)
  530. }
  531. childNode.Type = html.TextNode
  532. childNode.Data = name
  533. }
  534. if noLink {
  535. linkNode = childNode
  536. } else {
  537. linkNode.Attr = []html.Attribute{{Key: "href", Val: link}}
  538. }
  539. replaceContent(node, m[0], m[1], linkNode)
  540. }
  541. func fullIssuePatternProcessor(ctx *postProcessCtx, node *html.Node) {
  542. if ctx.metas == nil {
  543. return
  544. }
  545. m := getIssueFullPattern().FindStringSubmatchIndex(node.Data)
  546. if m == nil {
  547. return
  548. }
  549. link := node.Data[m[0]:m[1]]
  550. id := "#" + node.Data[m[2]:m[3]]
  551. // extract repo and org name from matched link like
  552. // http://localhost:3000/gituser/myrepo/issues/1
  553. linkParts := strings.Split(path.Clean(link), "/")
  554. matchOrg := linkParts[len(linkParts)-4]
  555. matchRepo := linkParts[len(linkParts)-3]
  556. if matchOrg == ctx.metas["user"] && matchRepo == ctx.metas["repo"] {
  557. // TODO if m[4]:m[5] is not nil, then link is to a comment,
  558. // and we should indicate that in the text somehow
  559. replaceContent(node, m[0], m[1], createLink(link, id, "issue"))
  560. } else {
  561. orgRepoID := matchOrg + "/" + matchRepo + id
  562. replaceContent(node, m[0], m[1], createLink(link, orgRepoID, "issue"))
  563. }
  564. }
  565. func issueIndexPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  566. if ctx.metas == nil {
  567. return
  568. }
  569. var (
  570. found bool
  571. ref *references.RenderizableReference
  572. )
  573. _, exttrack := ctx.metas["format"]
  574. alphanum := ctx.metas["style"] == IssueNameStyleAlphanumeric
  575. // Repos with external issue trackers might still need to reference local PRs
  576. // We need to concern with the first one that shows up in the text, whichever it is
  577. found, ref = references.FindRenderizableReferenceNumeric(node.Data, exttrack && alphanum)
  578. if exttrack && alphanum {
  579. if found2, ref2 := references.FindRenderizableReferenceAlphanumeric(node.Data); found2 {
  580. if !found || ref2.RefLocation.Start < ref.RefLocation.Start {
  581. found = true
  582. ref = ref2
  583. }
  584. }
  585. }
  586. if !found {
  587. return
  588. }
  589. var link *html.Node
  590. reftext := node.Data[ref.RefLocation.Start:ref.RefLocation.End]
  591. if exttrack && !ref.IsPull {
  592. ctx.metas["index"] = ref.Issue
  593. link = createLink(com.Expand(ctx.metas["format"], ctx.metas), reftext, "issue")
  594. } else {
  595. // Path determines the type of link that will be rendered. It's unknown at this point whether
  596. // the linked item is actually a PR or an issue. Luckily it's of no real consequence because
  597. // Gitea will redirect on click as appropriate.
  598. path := "issues"
  599. if ref.IsPull {
  600. path = "pulls"
  601. }
  602. if ref.Owner == "" {
  603. link = createLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], path, ref.Issue), reftext, "issue")
  604. } else {
  605. link = createLink(util.URLJoin(setting.AppURL, ref.Owner, ref.Name, path, ref.Issue), reftext, "issue")
  606. }
  607. }
  608. if ref.Action == references.XRefActionNone {
  609. replaceContent(node, ref.RefLocation.Start, ref.RefLocation.End, link)
  610. return
  611. }
  612. // Decorate action keywords if actionable
  613. var keyword *html.Node
  614. if references.IsXrefActionable(ref, exttrack, alphanum) {
  615. keyword = createKeyword(node.Data[ref.ActionLocation.Start:ref.ActionLocation.End])
  616. } else {
  617. keyword = &html.Node{
  618. Type: html.TextNode,
  619. Data: node.Data[ref.ActionLocation.Start:ref.ActionLocation.End],
  620. }
  621. }
  622. spaces := &html.Node{
  623. Type: html.TextNode,
  624. Data: node.Data[ref.ActionLocation.End:ref.RefLocation.Start],
  625. }
  626. replaceContentList(node, ref.ActionLocation.Start, ref.RefLocation.End, []*html.Node{keyword, spaces, link})
  627. }
  628. // fullSha1PatternProcessor renders SHA containing URLs
  629. func fullSha1PatternProcessor(ctx *postProcessCtx, node *html.Node) {
  630. if ctx.metas == nil {
  631. return
  632. }
  633. m := anySHA1Pattern.FindStringSubmatchIndex(node.Data)
  634. if m == nil {
  635. return
  636. }
  637. urlFull := node.Data[m[0]:m[1]]
  638. text := base.ShortSha(node.Data[m[2]:m[3]])
  639. // 3rd capture group matches a optional path
  640. subpath := ""
  641. if m[5] > 0 {
  642. subpath = node.Data[m[4]:m[5]]
  643. }
  644. // 4th capture group matches a optional url hash
  645. hash := ""
  646. if m[7] > 0 {
  647. hash = node.Data[m[6]:m[7]][1:]
  648. }
  649. start := m[0]
  650. end := m[1]
  651. // If url ends in '.', it's very likely that it is not part of the
  652. // actual url but used to finish a sentence.
  653. if strings.HasSuffix(urlFull, ".") {
  654. end--
  655. urlFull = urlFull[:len(urlFull)-1]
  656. if hash != "" {
  657. hash = hash[:len(hash)-1]
  658. } else if subpath != "" {
  659. subpath = subpath[:len(subpath)-1]
  660. }
  661. }
  662. if subpath != "" {
  663. text += subpath
  664. }
  665. if hash != "" {
  666. text += " (" + hash + ")"
  667. }
  668. replaceContent(node, start, end, createCodeLink(urlFull, text, "commit"))
  669. }
  670. // sha1CurrentPatternProcessor renders SHA1 strings to corresponding links that
  671. // are assumed to be in the same repository.
  672. func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) {
  673. if ctx.metas == nil || ctx.metas["user"] == "" || ctx.metas["repo"] == "" || ctx.metas["repoPath"] == "" {
  674. return
  675. }
  676. m := sha1CurrentPattern.FindStringSubmatchIndex(node.Data)
  677. if m == nil {
  678. return
  679. }
  680. hash := node.Data[m[2]:m[3]]
  681. // The regex does not lie, it matches the hash pattern.
  682. // However, a regex cannot know if a hash actually exists or not.
  683. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  684. // but that is not always the case.
  685. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  686. // as used by git and github for linking and thus we have to do similar.
  687. // Because of this, we check to make sure that a matched hash is actually
  688. // a commit in the repository before making it a link.
  689. if _, err := git.NewCommand("rev-parse", "--verify", hash).RunInDirBytes(ctx.metas["repoPath"]); err != nil {
  690. if !strings.Contains(err.Error(), "fatal: Needed a single revision") {
  691. log.Debug("sha1CurrentPatternProcessor git rev-parse: %v", err)
  692. }
  693. return
  694. }
  695. replaceContent(node, m[2], m[3],
  696. createCodeLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], "commit", hash), base.ShortSha(hash), "commit"))
  697. }
  698. // emailAddressProcessor replaces raw email addresses with a mailto: link.
  699. func emailAddressProcessor(ctx *postProcessCtx, node *html.Node) {
  700. m := emailRegex.FindStringSubmatchIndex(node.Data)
  701. if m == nil {
  702. return
  703. }
  704. mail := node.Data[m[2]:m[3]]
  705. replaceContent(node, m[2], m[3], createLink("mailto:"+mail, mail, "mailto"))
  706. }
  707. // linkProcessor creates links for any HTTP or HTTPS URL not captured by
  708. // markdown.
  709. func linkProcessor(ctx *postProcessCtx, node *html.Node) {
  710. m := linkRegex.FindStringIndex(node.Data)
  711. if m == nil {
  712. return
  713. }
  714. uri := node.Data[m[0]:m[1]]
  715. replaceContent(node, m[0], m[1], createLink(uri, uri, "link"))
  716. }
  717. func genDefaultLinkProcessor(defaultLink string) processor {
  718. return func(ctx *postProcessCtx, node *html.Node) {
  719. ch := &html.Node{
  720. Parent: node,
  721. Type: html.TextNode,
  722. Data: node.Data,
  723. }
  724. node.Type = html.ElementNode
  725. node.Data = "a"
  726. node.DataAtom = atom.A
  727. node.Attr = []html.Attribute{
  728. {Key: "href", Val: defaultLink},
  729. {Key: "class", Val: "default-link"},
  730. }
  731. node.FirstChild, node.LastChild = ch, ch
  732. }
  733. }
  734. // descriptionLinkProcessor creates links for DescriptionHTML
  735. func descriptionLinkProcessor(ctx *postProcessCtx, node *html.Node) {
  736. m := linkRegex.FindStringIndex(node.Data)
  737. if m == nil {
  738. return
  739. }
  740. uri := node.Data[m[0]:m[1]]
  741. replaceContent(node, m[0], m[1], createDescriptionLink(uri, uri))
  742. }
  743. func createDescriptionLink(href, content string) *html.Node {
  744. textNode := &html.Node{
  745. Type: html.TextNode,
  746. Data: content,
  747. }
  748. linkNode := &html.Node{
  749. FirstChild: textNode,
  750. LastChild: textNode,
  751. Type: html.ElementNode,
  752. Data: "a",
  753. DataAtom: atom.A,
  754. Attr: []html.Attribute{
  755. {Key: "href", Val: href},
  756. {Key: "target", Val: "_blank"},
  757. {Key: "rel", Val: "noopener noreferrer"},
  758. },
  759. }
  760. textNode.Parent = linkNode
  761. return linkNode
  762. }