Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

html.go 15KB

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