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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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/log"
  16. "code.gitea.io/gitea/modules/setting"
  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. // URLJoin joins url components, like path.Join, but preserving contents
  97. func URLJoin(base string, elems ...string) string {
  98. u, err := url.Parse(base)
  99. if err != nil {
  100. log.Error(4, "URLJoin: Invalid base URL %s", base)
  101. return ""
  102. }
  103. joinArgs := make([]string, 0, len(elems)+1)
  104. joinArgs = append(joinArgs, u.Path)
  105. joinArgs = append(joinArgs, elems...)
  106. u.Path = path.Join(joinArgs...)
  107. return u.String()
  108. }
  109. // RenderIssueIndexPatternOptions options for RenderIssueIndexPattern function
  110. type RenderIssueIndexPatternOptions struct {
  111. // url to which non-special formatting should be linked. If empty,
  112. // no such links will be added
  113. DefaultURL string
  114. URLPrefix string
  115. Metas map[string]string
  116. }
  117. // addText add text to the given buffer, adding a link to the default url
  118. // if appropriate
  119. func (opts RenderIssueIndexPatternOptions) addText(text []byte, buf *bytes.Buffer) {
  120. if len(text) == 0 {
  121. return
  122. } else if len(opts.DefaultURL) == 0 {
  123. buf.Write(text)
  124. return
  125. }
  126. buf.WriteString(`<a rel="nofollow" href="`)
  127. buf.WriteString(opts.DefaultURL)
  128. buf.WriteString(`">`)
  129. buf.Write(text)
  130. buf.WriteString(`</a>`)
  131. }
  132. // RenderIssueIndexPattern renders issue indexes to corresponding links.
  133. func RenderIssueIndexPattern(rawBytes []byte, opts RenderIssueIndexPatternOptions) []byte {
  134. opts.URLPrefix = cutoutVerbosePrefix(opts.URLPrefix)
  135. pattern := IssueNumericPattern
  136. if opts.Metas["style"] == IssueNameStyleAlphanumeric {
  137. pattern = IssueAlphanumericPattern
  138. }
  139. var buf bytes.Buffer
  140. remainder := rawBytes
  141. for {
  142. indices := pattern.FindIndex(remainder)
  143. if indices == nil || len(indices) < 2 {
  144. opts.addText(remainder, &buf)
  145. return buf.Bytes()
  146. }
  147. startIndex := indices[0]
  148. endIndex := indices[1]
  149. opts.addText(remainder[:startIndex], &buf)
  150. if remainder[startIndex] == '(' || remainder[startIndex] == ' ' {
  151. buf.WriteByte(remainder[startIndex])
  152. startIndex++
  153. }
  154. if opts.Metas == nil {
  155. buf.WriteString(`<a href="`)
  156. buf.WriteString(URLJoin(
  157. opts.URLPrefix, "issues", string(remainder[startIndex+1:endIndex])))
  158. buf.WriteString(`">`)
  159. buf.Write(remainder[startIndex:endIndex])
  160. buf.WriteString(`</a>`)
  161. } else {
  162. // Support for external issue tracker
  163. buf.WriteString(`<a href="`)
  164. if opts.Metas["style"] == IssueNameStyleAlphanumeric {
  165. opts.Metas["index"] = string(remainder[startIndex:endIndex])
  166. } else {
  167. opts.Metas["index"] = string(remainder[startIndex+1 : endIndex])
  168. }
  169. buf.WriteString(com.Expand(opts.Metas["format"], opts.Metas))
  170. buf.WriteString(`">`)
  171. buf.Write(remainder[startIndex:endIndex])
  172. buf.WriteString(`</a>`)
  173. }
  174. if endIndex < len(remainder) &&
  175. (remainder[endIndex] == ')' || remainder[endIndex] == ' ') {
  176. buf.WriteByte(remainder[endIndex])
  177. endIndex++
  178. }
  179. remainder = remainder[endIndex:]
  180. }
  181. }
  182. // IsSameDomain checks if given url string has the same hostname as current Gitea instance
  183. func IsSameDomain(s string) bool {
  184. if strings.HasPrefix(s, "/") {
  185. return true
  186. }
  187. if uapp, err := url.Parse(setting.AppURL); err == nil {
  188. if u, err := url.Parse(s); err == nil {
  189. return u.Host == uapp.Host
  190. }
  191. return false
  192. }
  193. return false
  194. }
  195. // renderFullSha1Pattern renders SHA containing URLs
  196. func renderFullSha1Pattern(rawBytes []byte, urlPrefix string) []byte {
  197. ms := AnySHA1Pattern.FindAllSubmatch(rawBytes, -1)
  198. for _, m := range ms {
  199. all := m[0]
  200. protocol := string(m[1])
  201. paths := string(m[2])
  202. path := protocol + "://" + paths
  203. author := string(m[3])
  204. repoName := string(m[4])
  205. path = URLJoin(path, author, repoName)
  206. ltype := "src"
  207. itemType := m[5]
  208. if IsSameDomain(paths) {
  209. ltype = string(itemType)
  210. } else if string(itemType) == "commit" {
  211. ltype = "commit"
  212. }
  213. sha := m[6]
  214. var subtree string
  215. if len(m) > 7 && len(m[7]) > 0 {
  216. subtree = string(m[7])
  217. }
  218. var line []byte
  219. if len(m) > 8 && len(m[8]) > 0 {
  220. line = m[8]
  221. }
  222. urlSuffix := ""
  223. text := base.ShortSha(string(sha))
  224. if subtree != "" {
  225. urlSuffix = "/" + subtree
  226. text += urlSuffix
  227. }
  228. if line != nil {
  229. value := string(line)
  230. urlSuffix += "#"
  231. urlSuffix += value
  232. text += " ("
  233. text += value
  234. text += ")"
  235. }
  236. rawBytes = bytes.Replace(rawBytes, all, []byte(fmt.Sprintf(
  237. `<a href="%s">%s</a>`, URLJoin(path, ltype, string(sha))+urlSuffix, text)), -1)
  238. }
  239. return rawBytes
  240. }
  241. // RenderFullIssuePattern renders issues-like URLs
  242. func RenderFullIssuePattern(rawBytes []byte) []byte {
  243. ms := getIssueFullPattern().FindAllSubmatch(rawBytes, -1)
  244. for _, m := range ms {
  245. all := m[0]
  246. id := string(m[1])
  247. text := "#" + id
  248. // TODO if m[2] is not nil, then link is to a comment,
  249. // and we should indicate that in the text somehow
  250. rawBytes = bytes.Replace(rawBytes, all, []byte(fmt.Sprintf(
  251. `<a href="%s">%s</a>`, string(all), text)), -1)
  252. }
  253. return rawBytes
  254. }
  255. func firstIndexOfByte(sl []byte, target byte) int {
  256. for i := 0; i < len(sl); i++ {
  257. if sl[i] == target {
  258. return i
  259. }
  260. }
  261. return -1
  262. }
  263. func lastIndexOfByte(sl []byte, target byte) int {
  264. for i := len(sl) - 1; i >= 0; i-- {
  265. if sl[i] == target {
  266. return i
  267. }
  268. }
  269. return -1
  270. }
  271. // RenderShortLinks processes [[syntax]]
  272. //
  273. // noLink flag disables making link tags when set to true
  274. // so this function just replaces the whole [[...]] with the content text
  275. //
  276. // isWikiMarkdown is a flag to choose linking url prefix
  277. func RenderShortLinks(rawBytes []byte, urlPrefix string, noLink bool, isWikiMarkdown bool) []byte {
  278. ms := ShortLinkPattern.FindAll(rawBytes, -1)
  279. for _, m := range ms {
  280. orig := bytes.TrimSpace(m)
  281. m = orig[2:]
  282. tailPos := lastIndexOfByte(m, ']') + 1
  283. tail := []byte{}
  284. if tailPos < len(m) {
  285. tail = m[tailPos:]
  286. m = m[:tailPos-1]
  287. }
  288. m = m[:len(m)-2]
  289. props := map[string]string{}
  290. // MediaWiki uses [[link|text]], while GitHub uses [[text|link]]
  291. // It makes page handling terrible, but we prefer GitHub syntax
  292. // And fall back to MediaWiki only when it is obvious from the look
  293. // Of text and link contents
  294. sl := bytes.Split(m, []byte("|"))
  295. for _, v := range sl {
  296. switch bytes.Count(v, []byte("=")) {
  297. // Piped args without = sign, these are mandatory arguments
  298. case 0:
  299. {
  300. sv := string(v)
  301. if props["name"] == "" {
  302. if isLink(v) {
  303. // If we clearly see it is a link, we save it so
  304. // But first we need to ensure, that if both mandatory args provided
  305. // look like links, we stick to GitHub syntax
  306. if props["link"] != "" {
  307. props["name"] = props["link"]
  308. }
  309. props["link"] = strings.TrimSpace(sv)
  310. } else {
  311. props["name"] = sv
  312. }
  313. } else {
  314. props["link"] = strings.TrimSpace(sv)
  315. }
  316. }
  317. // Piped args with = sign, these are optional arguments
  318. case 1:
  319. {
  320. sep := firstIndexOfByte(v, '=')
  321. key, val := string(v[:sep]), html.UnescapeString(string(v[sep+1:]))
  322. lastCharIndex := len(val) - 1
  323. if (val[0] == '"' || val[0] == '\'') && (val[lastCharIndex] == '"' || val[lastCharIndex] == '\'') {
  324. val = val[1:lastCharIndex]
  325. }
  326. props[key] = val
  327. }
  328. }
  329. }
  330. var name string
  331. var link string
  332. if props["link"] != "" {
  333. link = props["link"]
  334. } else if props["name"] != "" {
  335. link = props["name"]
  336. }
  337. if props["title"] != "" {
  338. name = props["title"]
  339. } else if props["name"] != "" {
  340. name = props["name"]
  341. } else {
  342. name = link
  343. }
  344. name += string(tail)
  345. image := false
  346. ext := filepath.Ext(string(link))
  347. if ext != "" {
  348. switch ext {
  349. case ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".gif", ".bmp", ".ico", ".svg":
  350. {
  351. image = true
  352. }
  353. }
  354. }
  355. absoluteLink := isLink([]byte(link))
  356. if !absoluteLink {
  357. link = strings.Replace(link, " ", "+", -1)
  358. }
  359. if image {
  360. if !absoluteLink {
  361. if IsSameDomain(urlPrefix) {
  362. urlPrefix = strings.Replace(urlPrefix, "/src/", "/raw/", 1)
  363. }
  364. if isWikiMarkdown {
  365. link = URLJoin("wiki", "raw", link)
  366. }
  367. link = URLJoin(urlPrefix, link)
  368. }
  369. title := props["title"]
  370. if title == "" {
  371. title = props["alt"]
  372. }
  373. if title == "" {
  374. title = path.Base(string(name))
  375. }
  376. alt := props["alt"]
  377. if alt == "" {
  378. alt = name
  379. }
  380. if alt != "" {
  381. alt = `alt="` + alt + `"`
  382. }
  383. name = fmt.Sprintf(`<img src="%s" %s title="%s" />`, link, alt, title)
  384. } else if !absoluteLink {
  385. if isWikiMarkdown {
  386. link = URLJoin("wiki", link)
  387. }
  388. link = URLJoin(urlPrefix, link)
  389. }
  390. if noLink {
  391. rawBytes = bytes.Replace(rawBytes, orig, []byte(name), -1)
  392. } else {
  393. rawBytes = bytes.Replace(rawBytes, orig,
  394. []byte(fmt.Sprintf(`<a href="%s">%s</a>`, link, name)), -1)
  395. }
  396. }
  397. return rawBytes
  398. }
  399. // RenderCrossReferenceIssueIndexPattern renders issue indexes from other repositories to corresponding links.
  400. func RenderCrossReferenceIssueIndexPattern(rawBytes []byte, urlPrefix string, metas map[string]string) []byte {
  401. ms := CrossReferenceIssueNumericPattern.FindAll(rawBytes, -1)
  402. for _, m := range ms {
  403. if m[0] == ' ' || m[0] == '(' {
  404. m = m[1:] // ignore leading space or opening parentheses
  405. }
  406. repo := string(bytes.Split(m, []byte("#"))[0])
  407. issue := string(bytes.Split(m, []byte("#"))[1])
  408. link := fmt.Sprintf(`<a href="%s">%s</a>`, URLJoin(setting.AppURL, repo, "issues", issue), m)
  409. rawBytes = bytes.Replace(rawBytes, m, []byte(link), 1)
  410. }
  411. return rawBytes
  412. }
  413. // renderSha1CurrentPattern renders SHA1 strings to corresponding links that assumes in the same repository.
  414. func renderSha1CurrentPattern(rawBytes []byte, urlPrefix string) []byte {
  415. ms := Sha1CurrentPattern.FindAllSubmatch(rawBytes, -1)
  416. for _, m := range ms {
  417. hash := m[1]
  418. // The regex does not lie, it matches the hash pattern.
  419. // However, a regex cannot know if a hash actually exists or not.
  420. // We could assume that a SHA1 hash should probably contain alphas AND numerics
  421. // but that is not always the case.
  422. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash
  423. // as used by git and github for linking and thus we have to do similar.
  424. rawBytes = bytes.Replace(rawBytes, hash, []byte(fmt.Sprintf(
  425. `<a href="%s">%s</a>`, URLJoin(urlPrefix, "commit", string(hash)), base.ShortSha(string(hash)))), -1)
  426. }
  427. return rawBytes
  428. }
  429. // RenderSpecialLink renders mentions, indexes and SHA1 strings to corresponding links.
  430. func RenderSpecialLink(rawBytes []byte, urlPrefix string, metas map[string]string, isWikiMarkdown bool) []byte {
  431. ms := MentionPattern.FindAll(rawBytes, -1)
  432. for _, m := range ms {
  433. m = m[bytes.Index(m, []byte("@")):]
  434. rawBytes = bytes.Replace(rawBytes, m,
  435. []byte(fmt.Sprintf(`<a href="%s">%s</a>`, URLJoin(setting.AppURL, string(m[1:])), m)), -1)
  436. }
  437. rawBytes = RenderFullIssuePattern(rawBytes)
  438. rawBytes = RenderShortLinks(rawBytes, urlPrefix, false, isWikiMarkdown)
  439. rawBytes = RenderIssueIndexPattern(rawBytes, RenderIssueIndexPatternOptions{
  440. URLPrefix: urlPrefix,
  441. Metas: metas,
  442. })
  443. rawBytes = RenderCrossReferenceIssueIndexPattern(rawBytes, urlPrefix, metas)
  444. rawBytes = renderFullSha1Pattern(rawBytes, urlPrefix)
  445. rawBytes = renderSha1CurrentPattern(rawBytes, urlPrefix)
  446. return rawBytes
  447. }
  448. var (
  449. leftAngleBracket = []byte("</")
  450. rightAngleBracket = []byte(">")
  451. )
  452. var noEndTags = []string{"img", "input", "br", "hr"}
  453. // PostProcess treats different types of HTML differently,
  454. // and only renders special links for plain text blocks.
  455. func PostProcess(rawHTML []byte, urlPrefix string, metas map[string]string, isWikiMarkdown bool) []byte {
  456. startTags := make([]string, 0, 5)
  457. var buf bytes.Buffer
  458. tokenizer := html.NewTokenizer(bytes.NewReader(rawHTML))
  459. OUTER_LOOP:
  460. for html.ErrorToken != tokenizer.Next() {
  461. token := tokenizer.Token()
  462. switch token.Type {
  463. case html.TextToken:
  464. buf.Write(RenderSpecialLink([]byte(token.String()), urlPrefix, metas, isWikiMarkdown))
  465. case html.StartTagToken:
  466. buf.WriteString(token.String())
  467. tagName := token.Data
  468. // If this is an excluded tag, we skip processing all output until a close tag is encountered.
  469. if strings.EqualFold("a", tagName) || strings.EqualFold("code", tagName) || strings.EqualFold("pre", tagName) {
  470. stackNum := 1
  471. for html.ErrorToken != tokenizer.Next() {
  472. token = tokenizer.Token()
  473. // Copy the token to the output verbatim
  474. buf.Write(RenderShortLinks([]byte(token.String()), urlPrefix, true, isWikiMarkdown))
  475. if token.Type == html.StartTagToken && !com.IsSliceContainsStr(noEndTags, token.Data) {
  476. stackNum++
  477. }
  478. // If this is the close tag to the outer-most, we are done
  479. if token.Type == html.EndTagToken {
  480. stackNum--
  481. if stackNum <= 0 && strings.EqualFold(tagName, token.Data) {
  482. break
  483. }
  484. }
  485. }
  486. continue OUTER_LOOP
  487. }
  488. if !com.IsSliceContainsStr(noEndTags, tagName) {
  489. startTags = append(startTags, tagName)
  490. }
  491. case html.EndTagToken:
  492. if len(startTags) == 0 {
  493. buf.WriteString(token.String())
  494. break
  495. }
  496. buf.Write(leftAngleBracket)
  497. buf.WriteString(startTags[len(startTags)-1])
  498. buf.Write(rightAngleBracket)
  499. startTags = startTags[:len(startTags)-1]
  500. default:
  501. buf.WriteString(token.String())
  502. }
  503. }
  504. if io.EOF == tokenizer.Err() {
  505. return buf.Bytes()
  506. }
  507. // If we are not at the end of the input, then some other parsing error has occurred,
  508. // so return the input verbatim.
  509. return rawHTML
  510. }