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

html.go 29KB

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