Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

helper.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package templates
  6. import (
  7. "bytes"
  8. "container/list"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "html"
  13. "html/template"
  14. "mime"
  15. "net/url"
  16. "path/filepath"
  17. "runtime"
  18. "strings"
  19. "time"
  20. "code.gitea.io/gitea/modules/util"
  21. "code.gitea.io/gitea/models"
  22. "code.gitea.io/gitea/modules/base"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/markup"
  25. "code.gitea.io/gitea/modules/setting"
  26. "golang.org/x/net/html/charset"
  27. "golang.org/x/text/transform"
  28. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  29. )
  30. // NewFuncMap returns functions for injecting to templates
  31. func NewFuncMap() []template.FuncMap {
  32. return []template.FuncMap{map[string]interface{}{
  33. "GoVer": func() string {
  34. return strings.Title(runtime.Version())
  35. },
  36. "UseHTTPS": func() bool {
  37. return strings.HasPrefix(setting.AppURL, "https")
  38. },
  39. "AppName": func() string {
  40. return setting.AppName
  41. },
  42. "AppSubUrl": func() string {
  43. return setting.AppSubURL
  44. },
  45. "AppUrl": func() string {
  46. return setting.AppURL
  47. },
  48. "AppVer": func() string {
  49. return setting.AppVer
  50. },
  51. "AppBuiltWith": func() string {
  52. return setting.AppBuiltWith
  53. },
  54. "AppDomain": func() string {
  55. return setting.Domain
  56. },
  57. "DisableGravatar": func() bool {
  58. return setting.DisableGravatar
  59. },
  60. "DefaultShowFullName": func() bool {
  61. return setting.UI.DefaultShowFullName
  62. },
  63. "ShowFooterTemplateLoadTime": func() bool {
  64. return setting.ShowFooterTemplateLoadTime
  65. },
  66. "LoadTimes": func(startTime time.Time) string {
  67. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  68. },
  69. "AvatarLink": base.AvatarLink,
  70. "Safe": Safe,
  71. "SafeJS": SafeJS,
  72. "Str2html": Str2html,
  73. "TimeSince": base.TimeSince,
  74. "TimeSinceUnix": base.TimeSinceUnix,
  75. "RawTimeSince": base.RawTimeSince,
  76. "FileSize": base.FileSize,
  77. "Subtract": base.Subtract,
  78. "EntryIcon": base.EntryIcon,
  79. "Add": func(a, b int) int {
  80. return a + b
  81. },
  82. "ActionIcon": ActionIcon,
  83. "DateFmtLong": func(t time.Time) string {
  84. return t.Format(time.RFC1123Z)
  85. },
  86. "DateFmtShort": func(t time.Time) string {
  87. return t.Format("Jan 02, 2006")
  88. },
  89. "SizeFmt": func(s int64) string {
  90. return base.FileSize(s)
  91. },
  92. "List": List,
  93. "SubStr": func(str string, start, length int) string {
  94. if len(str) == 0 {
  95. return ""
  96. }
  97. end := start + length
  98. if length == -1 {
  99. end = len(str)
  100. }
  101. if len(str) < end {
  102. return str
  103. }
  104. return str[start:end]
  105. },
  106. "EllipsisString": base.EllipsisString,
  107. "DiffTypeToStr": DiffTypeToStr,
  108. "DiffLineTypeToStr": DiffLineTypeToStr,
  109. "Sha1": Sha1,
  110. "ShortSha": base.ShortSha,
  111. "MD5": base.EncodeMD5,
  112. "ActionContent2Commits": ActionContent2Commits,
  113. "PathEscape": url.PathEscape,
  114. "EscapePound": func(str string) string {
  115. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  116. },
  117. "PathEscapeSegments": util.PathEscapeSegments,
  118. "URLJoin": util.URLJoin,
  119. "RenderCommitMessage": RenderCommitMessage,
  120. "RenderCommitMessageLink": RenderCommitMessageLink,
  121. "RenderCommitBody": RenderCommitBody,
  122. "RenderNote": RenderNote,
  123. "IsMultilineCommitMessage": IsMultilineCommitMessage,
  124. "ThemeColorMetaTag": func() string {
  125. return setting.UI.ThemeColorMetaTag
  126. },
  127. "MetaAuthor": func() string {
  128. return setting.UI.Meta.Author
  129. },
  130. "MetaDescription": func() string {
  131. return setting.UI.Meta.Description
  132. },
  133. "MetaKeywords": func() string {
  134. return setting.UI.Meta.Keywords
  135. },
  136. "FilenameIsImage": func(filename string) bool {
  137. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  138. return strings.HasPrefix(mimeType, "image/")
  139. },
  140. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  141. if ec != nil {
  142. def := ec.GetDefinitionForFilename(filename)
  143. if def.TabWidth > 0 {
  144. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  145. }
  146. }
  147. return "tab-size-8"
  148. },
  149. "SubJumpablePath": func(str string) []string {
  150. var path []string
  151. index := strings.LastIndex(str, "/")
  152. if index != -1 && index != len(str) {
  153. path = append(path, str[0:index+1])
  154. path = append(path, str[index+1:])
  155. } else {
  156. path = append(path, str)
  157. }
  158. return path
  159. },
  160. "JsonPrettyPrint": func(in string) string {
  161. var out bytes.Buffer
  162. err := json.Indent(&out, []byte(in), "", " ")
  163. if err != nil {
  164. return ""
  165. }
  166. return out.String()
  167. },
  168. "DisableGitHooks": func() bool {
  169. return setting.DisableGitHooks
  170. },
  171. "DisableImportLocal": func() bool {
  172. return !setting.ImportLocalPaths
  173. },
  174. "TrN": TrN,
  175. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  176. if len(values)%2 != 0 {
  177. return nil, errors.New("invalid dict call")
  178. }
  179. dict := make(map[string]interface{}, len(values)/2)
  180. for i := 0; i < len(values); i += 2 {
  181. key, ok := values[i].(string)
  182. if !ok {
  183. return nil, errors.New("dict keys must be strings")
  184. }
  185. dict[key] = values[i+1]
  186. }
  187. return dict, nil
  188. },
  189. "Printf": fmt.Sprintf,
  190. "Escape": Escape,
  191. "Sec2Time": models.SecToTime,
  192. "ParseDeadline": func(deadline string) []string {
  193. return strings.Split(deadline, "|")
  194. },
  195. "DefaultTheme": func() string {
  196. return setting.UI.DefaultTheme
  197. },
  198. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  199. if len(values) == 0 {
  200. return nil, errors.New("invalid dict call")
  201. }
  202. dict := make(map[string]interface{})
  203. for i := 0; i < len(values); i++ {
  204. switch key := values[i].(type) {
  205. case string:
  206. i++
  207. if i == len(values) {
  208. return nil, errors.New("specify the key for non array values")
  209. }
  210. dict[key] = values[i]
  211. case map[string]interface{}:
  212. m := values[i].(map[string]interface{})
  213. for i, v := range m {
  214. dict[i] = v
  215. }
  216. default:
  217. return nil, errors.New("dict values must be maps")
  218. }
  219. }
  220. return dict, nil
  221. },
  222. "percentage": func(n int, values ...int) float32 {
  223. var sum = 0
  224. for i := 0; i < len(values); i++ {
  225. sum += values[i]
  226. }
  227. return float32(n) * 100 / float32(sum)
  228. },
  229. }}
  230. }
  231. // Safe render raw as HTML
  232. func Safe(raw string) template.HTML {
  233. return template.HTML(raw)
  234. }
  235. // SafeJS renders raw as JS
  236. func SafeJS(raw string) template.JS {
  237. return template.JS(raw)
  238. }
  239. // Str2html render Markdown text to HTML
  240. func Str2html(raw string) template.HTML {
  241. return template.HTML(markup.Sanitize(raw))
  242. }
  243. // Escape escapes a HTML string
  244. func Escape(raw string) string {
  245. return html.EscapeString(raw)
  246. }
  247. // List traversings the list
  248. func List(l *list.List) chan interface{} {
  249. e := l.Front()
  250. c := make(chan interface{})
  251. go func() {
  252. for e != nil {
  253. c <- e.Value
  254. e = e.Next()
  255. }
  256. close(c)
  257. }()
  258. return c
  259. }
  260. // Sha1 returns sha1 sum of string
  261. func Sha1(str string) string {
  262. return base.EncodeSha1(str)
  263. }
  264. // ToUTF8WithErr converts content to UTF8 encoding
  265. func ToUTF8WithErr(content []byte) (string, error) {
  266. charsetLabel, err := base.DetectEncoding(content)
  267. if err != nil {
  268. return "", err
  269. } else if charsetLabel == "UTF-8" {
  270. return string(base.RemoveBOMIfPresent(content)), nil
  271. }
  272. encoding, _ := charset.Lookup(charsetLabel)
  273. if encoding == nil {
  274. return string(content), fmt.Errorf("Unknown encoding: %s", charsetLabel)
  275. }
  276. // If there is an error, we concatenate the nicely decoded part and the
  277. // original left over. This way we won't lose data.
  278. result, n, err := transform.Bytes(encoding.NewDecoder(), content)
  279. if err != nil {
  280. result = append(result, content[n:]...)
  281. }
  282. result = base.RemoveBOMIfPresent(result)
  283. return string(result), err
  284. }
  285. // ToUTF8WithFallback detects the encoding of content and coverts to UTF-8 if possible
  286. func ToUTF8WithFallback(content []byte) []byte {
  287. charsetLabel, err := base.DetectEncoding(content)
  288. if err != nil || charsetLabel == "UTF-8" {
  289. return base.RemoveBOMIfPresent(content)
  290. }
  291. encoding, _ := charset.Lookup(charsetLabel)
  292. if encoding == nil {
  293. return content
  294. }
  295. // If there is an error, we concatenate the nicely decoded part and the
  296. // original left over. This way we won't lose data.
  297. result, n, err := transform.Bytes(encoding.NewDecoder(), content)
  298. if err != nil {
  299. return append(result, content[n:]...)
  300. }
  301. return base.RemoveBOMIfPresent(result)
  302. }
  303. // ToUTF8 converts content to UTF8 encoding and ignore error
  304. func ToUTF8(content string) string {
  305. res, _ := ToUTF8WithErr([]byte(content))
  306. return res
  307. }
  308. // ReplaceLeft replaces all prefixes 'old' in 's' with 'new'.
  309. func ReplaceLeft(s, old, new string) string {
  310. oldLen, newLen, i, n := len(old), len(new), 0, 0
  311. for ; i < len(s) && strings.HasPrefix(s[i:], old); n++ {
  312. i += oldLen
  313. }
  314. // simple optimization
  315. if n == 0 {
  316. return s
  317. }
  318. // allocating space for the new string
  319. curLen := n*newLen + len(s[i:])
  320. replacement := make([]byte, curLen, curLen)
  321. j := 0
  322. for ; j < n*newLen; j += newLen {
  323. copy(replacement[j:j+newLen], new)
  324. }
  325. copy(replacement[j:], s[i:])
  326. return string(replacement)
  327. }
  328. // RenderCommitMessage renders commit message with XSS-safe and special links.
  329. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  330. return RenderCommitMessageLink(msg, urlPrefix, "", metas)
  331. }
  332. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  333. // default url, handling for special links.
  334. func RenderCommitMessageLink(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  335. cleanMsg := template.HTMLEscapeString(msg)
  336. // we can safely assume that it will not return any error, since there
  337. // shouldn't be any special HTML.
  338. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, urlDefault, metas)
  339. if err != nil {
  340. log.Error("RenderCommitMessage: %v", err)
  341. return ""
  342. }
  343. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  344. if len(msgLines) == 0 {
  345. return template.HTML("")
  346. }
  347. return template.HTML(msgLines[0])
  348. }
  349. // RenderCommitBody extracts the body of a commit message without its title.
  350. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  351. cleanMsg := template.HTMLEscapeString(msg)
  352. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  353. if err != nil {
  354. log.Error("RenderCommitMessage: %v", err)
  355. return ""
  356. }
  357. body := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  358. if len(body) == 0 {
  359. return template.HTML("")
  360. }
  361. return template.HTML(strings.Join(body[1:], "\n"))
  362. }
  363. // RenderNote renders the contents of a git-notes file as a commit message.
  364. func RenderNote(msg, urlPrefix string, metas map[string]string) template.HTML {
  365. cleanMsg := template.HTMLEscapeString(msg)
  366. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  367. if err != nil {
  368. log.Error("RenderNote: %v", err)
  369. return ""
  370. }
  371. return template.HTML(string(fullMessage))
  372. }
  373. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  374. func IsMultilineCommitMessage(msg string) bool {
  375. return strings.Count(strings.TrimSpace(msg), "\n") >= 1
  376. }
  377. // Actioner describes an action
  378. type Actioner interface {
  379. GetOpType() models.ActionType
  380. GetActUserName() string
  381. GetRepoUserName() string
  382. GetRepoName() string
  383. GetRepoPath() string
  384. GetRepoLink() string
  385. GetBranch() string
  386. GetContent() string
  387. GetCreate() time.Time
  388. GetIssueInfos() []string
  389. }
  390. // ActionIcon accepts an action operation type and returns an icon class name.
  391. func ActionIcon(opType models.ActionType) string {
  392. switch opType {
  393. case models.ActionCreateRepo, models.ActionTransferRepo:
  394. return "repo"
  395. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  396. return "git-commit"
  397. case models.ActionCreateIssue:
  398. return "issue-opened"
  399. case models.ActionCreatePullRequest:
  400. return "git-pull-request"
  401. case models.ActionCommentIssue:
  402. return "comment-discussion"
  403. case models.ActionMergePullRequest:
  404. return "git-merge"
  405. case models.ActionCloseIssue, models.ActionClosePullRequest:
  406. return "issue-closed"
  407. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  408. return "issue-reopened"
  409. case models.ActionMirrorSyncPush, models.ActionMirrorSyncCreate, models.ActionMirrorSyncDelete:
  410. return "repo-clone"
  411. default:
  412. return "invalid type"
  413. }
  414. }
  415. // ActionContent2Commits converts action content to push commits
  416. func ActionContent2Commits(act Actioner) *models.PushCommits {
  417. push := models.NewPushCommits()
  418. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  419. log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  420. }
  421. return push
  422. }
  423. // DiffTypeToStr returns diff type name
  424. func DiffTypeToStr(diffType int) string {
  425. diffTypes := map[int]string{
  426. 1: "add", 2: "modify", 3: "del", 4: "rename",
  427. }
  428. return diffTypes[diffType]
  429. }
  430. // DiffLineTypeToStr returns diff line type name
  431. func DiffLineTypeToStr(diffType int) string {
  432. switch diffType {
  433. case 2:
  434. return "add"
  435. case 3:
  436. return "del"
  437. case 4:
  438. return "tag"
  439. }
  440. return "same"
  441. }
  442. // Language specific rules for translating plural texts
  443. var trNLangRules = map[string]func(int64) int{
  444. "en-US": func(cnt int64) int {
  445. if cnt == 1 {
  446. return 0
  447. }
  448. return 1
  449. },
  450. "lv-LV": func(cnt int64) int {
  451. if cnt%10 == 1 && cnt%100 != 11 {
  452. return 0
  453. }
  454. return 1
  455. },
  456. "ru-RU": func(cnt int64) int {
  457. if cnt%10 == 1 && cnt%100 != 11 {
  458. return 0
  459. }
  460. return 1
  461. },
  462. "zh-CN": func(cnt int64) int {
  463. return 0
  464. },
  465. "zh-HK": func(cnt int64) int {
  466. return 0
  467. },
  468. "zh-TW": func(cnt int64) int {
  469. return 0
  470. },
  471. "fr-FR": func(cnt int64) int {
  472. if cnt > -2 && cnt < 2 {
  473. return 0
  474. }
  475. return 1
  476. },
  477. }
  478. // TrN returns key to be used for plural text translation
  479. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  480. var c int64
  481. if t, ok := cnt.(int); ok {
  482. c = int64(t)
  483. } else if t, ok := cnt.(int16); ok {
  484. c = int64(t)
  485. } else if t, ok := cnt.(int32); ok {
  486. c = int64(t)
  487. } else if t, ok := cnt.(int64); ok {
  488. c = t
  489. } else {
  490. return keyN
  491. }
  492. ruleFunc, ok := trNLangRules[lang]
  493. if !ok {
  494. ruleFunc = trNLangRules["en-US"]
  495. }
  496. if ruleFunc(c) == 0 {
  497. return key1
  498. }
  499. return keyN
  500. }