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 17 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. "io"
  9. "net/url"
  10. "path"
  11. "path/filepath"
  12. "regexp"
  13. "strings"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/Unknwon/com"
  18. "golang.org/x/net/html"
  19. )
  20. // Issue name styles
  21. const (
  22. IssueNameStyleNumeric = "numeric"
  23. IssueNameStyleAlphanumeric = "alphanumeric"
  24. )
  25. var (
  26. // NOTE: All below regex matching do not perform any extra validation.
  27. // Thus a link is produced even if the linked entity does not exist.
  28. // While fast, this is also incorrect and lead to false positives.
  29. // TODO: fix invalid linking issue
  30. // MentionPattern matches string that mentions someone, e.g. @Unknwon
  31. MentionPattern = regexp.MustCompile(`(\s|^|\W)@[0-9a-zA-Z-_\.]+`)
  32. // IssueNumericPattern matches string that references to a numeric issue, e.g. #1287
  33. IssueNumericPattern = regexp.MustCompile(`( |^|\(|\[)#[0-9]+\b`)
  34. // IssueAlphanumericPattern matches string that references to an alphanumeric issue, e.g. ABC-1234
  35. IssueAlphanumericPattern = regexp.MustCompile(`( |^|\(|\[)[A-Z]{1,10}-[1-9][0-9]*\b`)
  36. // CrossReferenceIssueNumericPattern matches string that references a numeric issue in a different repository
  37. // e.g. gogits/gogs#12345
  38. CrossReferenceIssueNumericPattern = regexp.MustCompile(`( |^)[0-9a-zA-Z-_\.]+/[0-9a-zA-Z-_\.]+#[0-9]+\b`)
  39. // Sha1CurrentPattern matches string that represents a commit SHA, e.g. d8a994ef243349f321568f9e36d5c3f444b99cae
  40. // Although SHA1 hashes are 40 chars long, the regex matches the hash from 7 to 40 chars in length
  41. // so that abbreviated hash links can be used as well. This matches git and github useability.
  42. Sha1CurrentPattern = regexp.MustCompile(`(?:^|\s|\()([0-9a-f]{7,40})\b`)
  43. // ShortLinkPattern matches short but difficult to parse [[name|link|arg=test]] syntax
  44. ShortLinkPattern = regexp.MustCompile(`(\[\[.*?\]\]\w*)`)
  45. // AnySHA1Pattern allows to split url containing SHA into parts
  46. AnySHA1Pattern = regexp.MustCompile(`(http\S*)://(\S+)/(\S+)/(\S+)/(\S+)/([0-9a-f]{40})(?:/?([^#\s]+)?(?:#(\S+))?)?`)
  47. validLinksPattern = regexp.MustCompile(`^[a-z][\w-]+://`)
  48. )
  49. // regexp for full links to issues/pulls
  50. var issueFullPattern *regexp.Regexp
  51. // IsLink reports whether link fits valid format.
  52. func IsLink(link []byte) bool {
  53. return isLink(link)
  54. }
  55. // isLink reports whether link fits valid format.
  56. func isLink(link []byte) bool {
  57. return validLinksPattern.Match(link)
  58. }
  59. func getIssueFullPattern() *regexp.Regexp {
  60. if issueFullPattern == nil {
  61. appURL := setting.AppURL
  62. if len(appURL) > 0 && appURL[len(appURL)-1] != '/' {
  63. appURL += "/"
  64. }
  65. issueFullPattern = regexp.MustCompile(appURL +
  66. `\w+/\w+/(?:issues|pulls)/((?:\w{1,10}-)?[1-9][0-9]*)([\?|#]\S+.(\S+)?)?\b`)
  67. }
  68. return issueFullPattern
  69. }
  70. // FindAllMentions matches mention patterns in given content
  71. // and returns a list of found user names without @ prefix.
  72. func FindAllMentions(content string) []string {
  73. mentions := MentionPattern.FindAllString(content, -1)
  74. for i := range mentions {
  75. mentions[i] = mentions[i][strings.Index(mentions[i], "@")+1:] // Strip @ character
  76. }
  77. return mentions
  78. }
  79. // cutoutVerbosePrefix cutouts URL prefix including sub-path to
  80. // return a clean unified string of request URL path.
  81. func cutoutVerbosePrefix(prefix string) string {
  82. if len(prefix) == 0 || prefix[0] != '/' {
  83. return prefix
  84. }
  85. count := 0
  86. for i := 0; i < len(prefix); i++ {
  87. if prefix[i] == '/' {
  88. count++
  89. }
  90. if count >= 3+setting.AppSubURLDepth {
  91. return prefix[:i]
  92. }
  93. }
  94. return prefix
  95. }
  96. // RenderIssueIndexPatternOptions options for RenderIssueIndexPattern function
  97. type RenderIssueIndexPatternOptions struct {
  98. // url to which non-special formatting should be linked. If empty,
  99. // no such links will be added
  100. DefaultURL string
  101. URLPrefix string
  102. Metas map[string]string
  103. }
  104. // addText add text to the given buffer, adding a link to the default url
  105. // if appropriate
  106. func (opts RenderIssueIndexPatternOptions) addText(text []byte, buf *bytes.Buffer) {
  107. if len(text) == 0 {
  108. return
  109. } else if len(opts.DefaultURL) == 0 {
  110. buf.Write(text)
  111. return
  112. }
  113. buf.WriteString(`<a rel="nofollow" href="`)
  114. buf.WriteString(opts.DefaultURL)
  115. buf.WriteString(`">`)
  116. buf.Write(text)
  117. buf.WriteString(`</a>`)
  118. }
  119. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  120. func RenderIssueIndexPattern(rawBytes []byte, opts RenderIssueIndexPatternOptions) []byte {
  121. opts.URLPrefix = cutoutVerbosePrefix(opts.URLPrefix)
  122. pattern := IssueNumericPattern
  123. if opts.Metas["style"] == IssueNameStyleAlphanumeric {
  124. pattern = IssueAlphanumericPattern
  125. }
  126. var buf bytes.Buffer
  127. remainder := rawBytes
  128. for {
  129. indices := pattern.FindIndex(remainder)
  130. if indices == nil || len(indices) < 2 {
  131. opts.addText(remainder, &buf)
  132. return buf.Bytes()
  133. }
  134. startIndex := indices[0]
  135. endIndex := indices[1]
  136. opts.addText(remainder[:startIndex], &buf)
  137. if remainder[startIndex] == '(' || remainder[startIndex] == ' ' {
  138. buf.WriteByte(remainder[startIndex])
  139. startIndex++
  140. }
  141. if opts.Metas == nil {
  142. buf.WriteString(`<a href="`)
  143. buf.WriteString(util.URLJoin(
  144. opts.URLPrefix, "issues", string(remainder[startIndex+1:endIndex])))
  145. buf.WriteString(`">`)
  146. buf.Write(remainder[startIndex:endIndex])
  147. buf.WriteString(`</a>`)
  148. } else {
  149. // Support for external issue tracker
  150. buf.WriteString(`<a href="`)
  151. if opts.Metas["style"] == IssueNameStyleAlphanumeric {
  152. opts.Metas["index"] = string(remainder[startIndex:endIndex])
  153. } else {
  154. opts.Metas["index"] = string(remainder[startIndex+1 : endIndex])
  155. }
  156. buf.WriteString(com.Expand(opts.Metas["format"], opts.Metas))
  157. buf.WriteString(`">`)
  158. buf.Write(remainder[startIndex:endIndex])
  159. buf.WriteString(`</a>`)
  160. }
  161. if endIndex < len(remainder) &&
  162. (remainder[endIndex] == ')' || remainder[endIndex] == ' ') {
  163. buf.WriteByte(remainder[endIndex])
  164. endIndex++
  165. }
  166. remainder = remainder[endIndex:]
  167. }
  168. }
  169. // IsSameDomain checks if given url string has the same hostname as current Gitea instance
  170. func IsSameDomain(s string) bool {
  171. if strings.HasPrefix(s, "/") {
  172. return true
  173. }
  174. if uapp, err := url.Parse(setting.AppURL); err == nil {
  175. if u, err := url.Parse(s); err == nil {
  176. return u.Host == uapp.Host
  177. }
  178. return false
  179. }
  180. return false
  181. }
  182. // renderFullSha1Pattern renders SHA containing URLs
  183. func renderFullSha1Pattern(rawBytes []byte, urlPrefix string) []byte {
  184. ms := AnySHA1Pattern.FindAllSubmatch(rawBytes, -1)
  185. for _, m := range ms {
  186. all := m[0]
  187. protocol := string(m[1])
  188. paths := string(m[2])
  189. path := protocol + "://" + paths
  190. author := string(m[3])
  191. repoName := string(m[4])
  192. path = util.URLJoin(path, author, repoName)
  193. ltype := "src"
  194. itemType := m[5]
  195. if IsSameDomain(paths) {
  196. ltype = string(itemType)
  197. } else if string(itemType) == "commit" {
  198. ltype = "commit"
  199. }
  200. sha := m[6]
  201. var subtree string
  202. if len(m) > 7 && len(m[7]) > 0 {
  203. subtree = string(m[7])
  204. }
  205. var line []byte
  206. if len(m) > 8 && len(m[8]) > 0 {
  207. line = m[8]
  208. }
  209. urlSuffix := ""
  210. text := base.ShortSha(string(sha))
  211. if subtree != "" {
  212. urlSuffix = "/" + subtree
  213. text += urlSuffix
  214. }
  215. if line != nil {
  216. value := string(line)
  217. urlSuffix += "#"
  218. urlSuffix += value
  219. text += " ("
  220. text += value
  221. text += ")"
  222. }
  223. rawBytes = bytes.Replace(rawBytes, all, []byte(fmt.Sprintf(
  224. `<a href="%s">%s</a>`, util.URLJoin(path, ltype, string(sha))+urlSuffix, text)), -1)
  225. }
  226. return rawBytes
  227. }
  228. // RenderFullIssuePattern renders issues-like URLs
  229. func RenderFullIssuePattern(rawBytes []byte) []byte {
  230. ms := getIssueFullPattern().FindAllSubmatch(rawBytes, -1)
  231. for _, m := range ms {
  232. all := m[0]
  233. id := string(m[1])
  234. text := "#" + id
  235. // TODO if m[2] is not nil, then link is to a comment,
  236. // and we should indicate that in the text somehow
  237. rawBytes = bytes.Replace(rawBytes, all, []byte(fmt.Sprintf(
  238. `<a href="%s">%s</a>`, string(all), text)), -1)
  239. }
  240. return rawBytes
  241. }
  242. func firstIndexOfByte(sl []byte, target byte) int {
  243. for i := 0; i < len(sl); i++ {
  244. if sl[i] == target {
  245. return i
  246. }
  247. }
  248. return -1
  249. }
  250. func lastIndexOfByte(sl []byte, target byte) int {
  251. for i := len(sl) - 1; i >= 0; i-- {
  252. if sl[i] == target {
  253. return i
  254. }
  255. }
  256. return -1
  257. }
  258. // RenderShortLinks processes [[syntax]]
  259. //
  260. // noLink flag disables making link tags when set to true
  261. // so this function just replaces the whole [[...]] with the content text
  262. //
  263. // isWikiMarkdown is a flag to choose linking url prefix
  264. func RenderShortLinks(rawBytes []byte, urlPrefix string, noLink bool, isWikiMarkdown bool) []byte {
  265. ms := ShortLinkPattern.FindAll(rawBytes, -1)
  266. for _, m := range ms {
  267. orig := bytes.TrimSpace(m)
  268. m = orig[2:]
  269. tailPos := lastIndexOfByte(m, ']') + 1
  270. tail := []byte{}
  271. if tailPos < len(m) {
  272. tail = m[tailPos:]
  273. m = m[:tailPos-1]
  274. }
  275. m = m[:len(m)-2]
  276. props := map[string]string{}
  277. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  278. // It makes page handling terrible, but we prefer GitHub syntax
  279. // And fall back to MediaWiki only when it is obvious from the look
  280. // Of text and link contents
  281. sl := bytes.Split(m, []byte("|"))
  282. for _, v := range sl {
  283. switch bytes.Count(v, []byte("=")) {
  284. // Piped args without = sign, these are mandatory arguments
  285. case 0:
  286. {
  287. sv := string(v)
  288. if props["name"] == "" {
  289. if isLink(v) {
  290. // If we clearly see it is a link, we save it so
  291. // But first we need to ensure, that if both mandatory args provided
  292. // look like links, we stick to GitHub syntax
  293. if props["link"] != "" {
  294. props["name"] = props["link"]
  295. }
  296. props["link"] = strings.TrimSpace(sv)
  297. } else {
  298. props["name"] = sv
  299. }
  300. } else {
  301. props["link"] = strings.TrimSpace(sv)
  302. }
  303. }
  304. // Piped args with = sign, these are optional arguments
  305. case 1:
  306. {
  307. sep := firstIndexOfByte(v, '=')
  308. key, val := string(v[:sep]), html.UnescapeString(string(v[sep+1:]))
  309. lastCharIndex := len(val) - 1
  310. if (val[0] == '"' || val[0] == '\'') && (val[lastCharIndex] == '"' || val[lastCharIndex] == '\'') {
  311. val = val[1:lastCharIndex]
  312. }
  313. props[key] = val
  314. }
  315. }
  316. }
  317. var name string
  318. var link string
  319. if props["link"] != "" {
  320. link = props["link"]
  321. } else if props["name"] != "" {
  322. link = props["name"]
  323. }
  324. if props["title"] != "" {
  325. name = props["title"]
  326. } else if props["name"] != "" {
  327. name = props["name"]
  328. } else {
  329. name = link
  330. }
  331. name += string(tail)
  332. image := false
  333. ext := filepath.Ext(string(link))
  334. if ext != "" {
  335. switch ext {
  336. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  337. {
  338. image = true
  339. }
  340. }
  341. }
  342. absoluteLink := isLink([]byte(link))
  343. if !absoluteLink {
  344. link = strings.Replace(link, " ", "+", -1)
  345. }
  346. if image {
  347. if !absoluteLink {
  348. if IsSameDomain(urlPrefix) {
  349. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  350. }
  351. if isWikiMarkdown {
  352. link = util.URLJoin("wiki", "raw", link)
  353. }
  354. link = util.URLJoin(urlPrefix, link)
  355. }
  356. title := props["title"]
  357. if title == "" {
  358. title = props["alt"]
  359. }
  360. if title == "" {
  361. title = path.Base(string(name))
  362. }
  363. alt := props["alt"]
  364. if alt == "" {
  365. alt = name
  366. }
  367. if alt != "" {
  368. alt = `alt="` + alt + `"`
  369. }
  370. name = fmt.Sprintf(`<img src="%s" %s title="%s" />`, link, alt, title)
  371. } else if !absoluteLink {
  372. if isWikiMarkdown {
  373. link = util.URLJoin("wiki", link)
  374. }
  375. link = util.URLJoin(urlPrefix, link)
  376. }
  377. if noLink {
  378. rawBytes = bytes.Replace(rawBytes, orig, []byte(name), -1)
  379. } else {
  380. rawBytes = bytes.Replace(rawBytes, orig,
  381. []byte(fmt.Sprintf(`<a href="%s">%s</a>`, link, name)), -1)
  382. }
  383. }
  384. return rawBytes
  385. }
  386. // RenderCrossReferenceIssueIndexPattern renders issue indexes from other repositories to corresponding links.
  387. func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  388. ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
  389. for _, m := range ms {
  390. if m[0] == ' ' || m[0] == '(' {
  391. m = m[1:] // ignore leading space or opening parentheses
  392. }
  393. repo := string(bytes.Split(m, []byte("#"))[0])
  394. issue := string(bytes.Split(m, []byte("#"))[1])
  395. link := fmt.Sprintf(`<a href="%s">%s</a>`, util.URLJoin(setting.AppURL, repo, "issues", issue), m)
  396. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  397. }
  398. return rawBytes
  399. }
  400. // renderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  401. func renderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  402. ms := Sha1CurrentPattern.FindAllSubmatch(rawBytes, -1)
  403. for _, m := range ms {
  404. hash := m[1]
  405. // The regex does not lie, it matches the hash pattern.
  406. // However, a regex cannot know if a hash actually exists or not.
  407. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  408. // but that is not always the case.
  409. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  410. // as used by git and github for linking and thus we have to do similar.
  411. rawBytes = bytes.Replace(rawBytes, hash, []byte(fmt.Sprintf(
  412. `<a href="%s">%s</a>`, util.URLJoin(urlPrefix, "commit", string(hash)), base.ShortSha(string(hash)))), -1)
  413. }
  414. return rawBytes
  415. }
  416. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  417. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string, isWikiMarkdown bool) []byte {
  418. ms := MentionPattern.FindAll(rawBytes, -1)
  419. for _, m := range ms {
  420. m = m[bytes.Index(m, []byte("@")):]
  421. rawBytes = bytes.Replace(rawBytes, m,
  422. []byte(fmt.Sprintf(`<a href="%s">%s</a>`, util.URLJoin(setting.AppURL, string(m[1:])), m)), -1)
  423. }
  424. rawBytes = RenderFullIssuePattern(rawBytes)
  425. rawBytes = RenderShortLinks(rawBytes, urlPrefix, false, isWikiMarkdown)
  426. rawBytes = RenderIssueIndexPattern(rawBytes, RenderIssueIndexPatternOptions{
  427. URLPrefix: urlPrefix,
  428. Metas: metas,
  429. })
  430. rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
  431. rawBytes = renderFullSha1Pattern(rawBytes, urlPrefix)
  432. rawBytes = renderSha1CurrentPattern(rawBytes, urlPrefix)
  433. return rawBytes
  434. }
  435. var (
  436. leftAngleBracket = []byte("</")
  437. rightAngleBracket = []byte(">")
  438. )
  439. var noEndTags = []string{"img", "input", "br", "hr"}
  440. // PostProcess treats different types of HTML differently,
  441. // and only renders special links for plain text blocks.
  442. func PostProcess(rawHTML []byte, urlPrefix string, metas map[string]string, isWikiMarkdown bool) []byte {
  443. startTags := make([]string, 0, 5)
  444. var buf bytes.Buffer
  445. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  446. OUTER_LOOP:
  447. for html.ErrorToken != tokenizer.Next() {
  448. token := tokenizer.Token()
  449. switch token.Type {
  450. case html.TextToken:
  451. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas, isWikiMarkdown))
  452. case html.StartTagToken:
  453. buf.WriteString(token.String())
  454. tagName := token.Data
  455. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  456. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  457. stackNum := 1
  458. for html.ErrorToken != tokenizer.Next() {
  459. token = tokenizer.Token()
  460. // Copy the token to the output verbatim
  461. buf.Write(RenderShortLinks([]byte(token.String()), urlPrefix, true, isWikiMarkdown))
  462. if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
  463. stackNum++
  464. }
  465. // If this is the close tag to the outer-most, we are done
  466. if token.Type == html.EndTagToken {
  467. stackNum--
  468. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  469. break
  470. }
  471. }
  472. }
  473. continue OUTER_LOOP
  474. }
  475. if !com.IsSliceContainsStr(noEndTags, tagName) {
  476. startTags = append(startTags, tagName)
  477. }
  478. case html.EndTagToken:
  479. if len(startTags) == 0 {
  480. buf.WriteString(token.String())
  481. break
  482. }
  483. buf.Write(leftAngleBracket)
  484. buf.WriteString(startTags[len(startTags)-1])
  485. buf.Write(rightAngleBracket)
  486. startTags = startTags[:len(startTags)-1]
  487. default:
  488. buf.WriteString(token.String())
  489. }
  490. }
  491. if io.EOF == tokenizer.Err() {
  492. return buf.Bytes()
  493. }
  494. // If we are not at the end of the input, then some other parsing error has occurred,
  495. // so return the input verbatim.
  496. return rawHTML
  497. }