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.

helper.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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], str[index+1:])
  154. } else {
  155. path = append(path, str)
  156. }
  157. return path
  158. },
  159. "JsonPrettyPrint": func(in string) string {
  160. var out bytes.Buffer
  161. err := json.Indent(&out, []byte(in), "", " ")
  162. if err != nil {
  163. return ""
  164. }
  165. return out.String()
  166. },
  167. "DisableGitHooks": func() bool {
  168. return setting.DisableGitHooks
  169. },
  170. "DisableImportLocal": func() bool {
  171. return !setting.ImportLocalPaths
  172. },
  173. "TrN": TrN,
  174. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  175. if len(values)%2 != 0 {
  176. return nil, errors.New("invalid dict call")
  177. }
  178. dict := make(map[string]interface{}, len(values)/2)
  179. for i := 0; i < len(values); i += 2 {
  180. key, ok := values[i].(string)
  181. if !ok {
  182. return nil, errors.New("dict keys must be strings")
  183. }
  184. dict[key] = values[i+1]
  185. }
  186. return dict, nil
  187. },
  188. "Printf": fmt.Sprintf,
  189. "Escape": Escape,
  190. "Sec2Time": models.SecToTime,
  191. "ParseDeadline": func(deadline string) []string {
  192. return strings.Split(deadline, "|")
  193. },
  194. "DefaultTheme": func() string {
  195. return setting.UI.DefaultTheme
  196. },
  197. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  198. if len(values) == 0 {
  199. return nil, errors.New("invalid dict call")
  200. }
  201. dict := make(map[string]interface{})
  202. for i := 0; i < len(values); i++ {
  203. switch key := values[i].(type) {
  204. case string:
  205. i++
  206. if i == len(values) {
  207. return nil, errors.New("specify the key for non array values")
  208. }
  209. dict[key] = values[i]
  210. case map[string]interface{}:
  211. m := values[i].(map[string]interface{})
  212. for i, v := range m {
  213. dict[i] = v
  214. }
  215. default:
  216. return nil, errors.New("dict values must be maps")
  217. }
  218. }
  219. return dict, nil
  220. },
  221. "percentage": func(n int, values ...int) float32 {
  222. var sum = 0
  223. for i := 0; i < len(values); i++ {
  224. sum += values[i]
  225. }
  226. return float32(n) * 100 / float32(sum)
  227. },
  228. }}
  229. }
  230. // Safe render raw as HTML
  231. func Safe(raw string) template.HTML {
  232. return template.HTML(raw)
  233. }
  234. // SafeJS renders raw as JS
  235. func SafeJS(raw string) template.JS {
  236. return template.JS(raw)
  237. }
  238. // Str2html render Markdown text to HTML
  239. func Str2html(raw string) template.HTML {
  240. return template.HTML(markup.Sanitize(raw))
  241. }
  242. // Escape escapes a HTML string
  243. func Escape(raw string) string {
  244. return html.EscapeString(raw)
  245. }
  246. // List traversings the list
  247. func List(l *list.List) chan interface{} {
  248. e := l.Front()
  249. c := make(chan interface{})
  250. go func() {
  251. for e != nil {
  252. c <- e.Value
  253. e = e.Next()
  254. }
  255. close(c)
  256. }()
  257. return c
  258. }
  259. // Sha1 returns sha1 sum of string
  260. func Sha1(str string) string {
  261. return base.EncodeSha1(str)
  262. }
  263. // ToUTF8WithErr converts content to UTF8 encoding
  264. func ToUTF8WithErr(content []byte) (string, error) {
  265. charsetLabel, err := base.DetectEncoding(content)
  266. if err != nil {
  267. return "", err
  268. } else if charsetLabel == "UTF-8" {
  269. return string(base.RemoveBOMIfPresent(content)), nil
  270. }
  271. encoding, _ := charset.Lookup(charsetLabel)
  272. if encoding == nil {
  273. return string(content), fmt.Errorf("Unknown encoding: %s", charsetLabel)
  274. }
  275. // If there is an error, we concatenate the nicely decoded part and the
  276. // original left over. This way we won't lose data.
  277. result, n, err := transform.Bytes(encoding.NewDecoder(), content)
  278. if err != nil {
  279. result = append(result, content[n:]...)
  280. }
  281. result = base.RemoveBOMIfPresent(result)
  282. return string(result), err
  283. }
  284. // ToUTF8WithFallback detects the encoding of content and coverts to UTF-8 if possible
  285. func ToUTF8WithFallback(content []byte) []byte {
  286. charsetLabel, err := base.DetectEncoding(content)
  287. if err != nil || charsetLabel == "UTF-8" {
  288. return base.RemoveBOMIfPresent(content)
  289. }
  290. encoding, _ := charset.Lookup(charsetLabel)
  291. if encoding == nil {
  292. return content
  293. }
  294. // If there is an error, we concatenate the nicely decoded part and the
  295. // original left over. This way we won't lose data.
  296. result, n, err := transform.Bytes(encoding.NewDecoder(), content)
  297. if err != nil {
  298. return append(result, content[n:]...)
  299. }
  300. return base.RemoveBOMIfPresent(result)
  301. }
  302. // ToUTF8 converts content to UTF8 encoding and ignore error
  303. func ToUTF8(content string) string {
  304. res, _ := ToUTF8WithErr([]byte(content))
  305. return res
  306. }
  307. // ReplaceLeft replaces all prefixes 'oldS' in 's' with 'newS'.
  308. func ReplaceLeft(s, oldS, newS string) string {
  309. oldLen, newLen, i, n := len(oldS), len(newS), 0, 0
  310. for ; i < len(s) && strings.HasPrefix(s[i:], oldS); n++ {
  311. i += oldLen
  312. }
  313. // simple optimization
  314. if n == 0 {
  315. return s
  316. }
  317. // allocating space for the new string
  318. curLen := n*newLen + len(s[i:])
  319. replacement := make([]byte, curLen)
  320. j := 0
  321. for ; j < n*newLen; j += newLen {
  322. copy(replacement[j:j+newLen], newS)
  323. }
  324. copy(replacement[j:], s[i:])
  325. return string(replacement)
  326. }
  327. // RenderCommitMessage renders commit message with XSS-safe and special links.
  328. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  329. return RenderCommitMessageLink(msg, urlPrefix, "", metas)
  330. }
  331. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  332. // default url, handling for special links.
  333. func RenderCommitMessageLink(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  334. cleanMsg := template.HTMLEscapeString(msg)
  335. // we can safely assume that it will not return any error, since there
  336. // shouldn't be any special HTML.
  337. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, urlDefault, metas)
  338. if err != nil {
  339. log.Error("RenderCommitMessage: %v", err)
  340. return ""
  341. }
  342. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  343. if len(msgLines) == 0 {
  344. return template.HTML("")
  345. }
  346. return template.HTML(msgLines[0])
  347. }
  348. // RenderCommitBody extracts the body of a commit message without its title.
  349. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  350. cleanMsg := template.HTMLEscapeString(msg)
  351. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  352. if err != nil {
  353. log.Error("RenderCommitMessage: %v", err)
  354. return ""
  355. }
  356. body := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  357. if len(body) == 0 {
  358. return template.HTML("")
  359. }
  360. return template.HTML(strings.Join(body[1:], "\n"))
  361. }
  362. // RenderNote renders the contents of a git-notes file as a commit message.
  363. func RenderNote(msg, urlPrefix string, metas map[string]string) template.HTML {
  364. cleanMsg := template.HTMLEscapeString(msg)
  365. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  366. if err != nil {
  367. log.Error("RenderNote: %v", err)
  368. return ""
  369. }
  370. return template.HTML(string(fullMessage))
  371. }
  372. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  373. func IsMultilineCommitMessage(msg string) bool {
  374. return strings.Count(strings.TrimSpace(msg), "\n") >= 1
  375. }
  376. // Actioner describes an action
  377. type Actioner interface {
  378. GetOpType() models.ActionType
  379. GetActUserName() string
  380. GetRepoUserName() string
  381. GetRepoName() string
  382. GetRepoPath() string
  383. GetRepoLink() string
  384. GetBranch() string
  385. GetContent() string
  386. GetCreate() time.Time
  387. GetIssueInfos() []string
  388. }
  389. // ActionIcon accepts an action operation type and returns an icon class name.
  390. func ActionIcon(opType models.ActionType) string {
  391. switch opType {
  392. case models.ActionCreateRepo, models.ActionTransferRepo:
  393. return "repo"
  394. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  395. return "git-commit"
  396. case models.ActionCreateIssue:
  397. return "issue-opened"
  398. case models.ActionCreatePullRequest:
  399. return "git-pull-request"
  400. case models.ActionCommentIssue:
  401. return "comment-discussion"
  402. case models.ActionMergePullRequest:
  403. return "git-merge"
  404. case models.ActionCloseIssue, models.ActionClosePullRequest:
  405. return "issue-closed"
  406. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  407. return "issue-reopened"
  408. case models.ActionMirrorSyncPush, models.ActionMirrorSyncCreate, models.ActionMirrorSyncDelete:
  409. return "repo-clone"
  410. default:
  411. return "invalid type"
  412. }
  413. }
  414. // ActionContent2Commits converts action content to push commits
  415. func ActionContent2Commits(act Actioner) *models.PushCommits {
  416. push := models.NewPushCommits()
  417. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  418. log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  419. }
  420. return push
  421. }
  422. // DiffTypeToStr returns diff type name
  423. func DiffTypeToStr(diffType int) string {
  424. diffTypes := map[int]string{
  425. 1: "add", 2: "modify", 3: "del", 4: "rename",
  426. }
  427. return diffTypes[diffType]
  428. }
  429. // DiffLineTypeToStr returns diff line type name
  430. func DiffLineTypeToStr(diffType int) string {
  431. switch diffType {
  432. case 2:
  433. return "add"
  434. case 3:
  435. return "del"
  436. case 4:
  437. return "tag"
  438. }
  439. return "same"
  440. }
  441. // Language specific rules for translating plural texts
  442. var trNLangRules = map[string]func(int64) int{
  443. "en-US": func(cnt int64) int {
  444. if cnt == 1 {
  445. return 0
  446. }
  447. return 1
  448. },
  449. "lv-LV": func(cnt int64) int {
  450. if cnt%10 == 1 && cnt%100 != 11 {
  451. return 0
  452. }
  453. return 1
  454. },
  455. "ru-RU": func(cnt int64) int {
  456. if cnt%10 == 1 && cnt%100 != 11 {
  457. return 0
  458. }
  459. return 1
  460. },
  461. "zh-CN": func(cnt int64) int {
  462. return 0
  463. },
  464. "zh-HK": func(cnt int64) int {
  465. return 0
  466. },
  467. "zh-TW": func(cnt int64) int {
  468. return 0
  469. },
  470. "fr-FR": func(cnt int64) int {
  471. if cnt > -2 && cnt < 2 {
  472. return 0
  473. }
  474. return 1
  475. },
  476. }
  477. // TrN returns key to be used for plural text translation
  478. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  479. var c int64
  480. if t, ok := cnt.(int); ok {
  481. c = int64(t)
  482. } else if t, ok := cnt.(int16); ok {
  483. c = int64(t)
  484. } else if t, ok := cnt.(int32); ok {
  485. c = int64(t)
  486. } else if t, ok := cnt.(int64); ok {
  487. c = t
  488. } else {
  489. return keyN
  490. }
  491. ruleFunc, ok := trNLangRules[lang]
  492. if !ok {
  493. ruleFunc = trNLangRules["en-US"]
  494. }
  495. if ruleFunc(c) == 0 {
  496. return key1
  497. }
  498. return keyN
  499. }