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.

helper.go 10 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // Copyright 2014 The Gogs 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 templates
  5. import (
  6. "bytes"
  7. "container/list"
  8. "encoding/json"
  9. "fmt"
  10. "html/template"
  11. "mime"
  12. "path/filepath"
  13. "runtime"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/markup"
  20. "code.gitea.io/gitea/modules/setting"
  21. "golang.org/x/net/html/charset"
  22. "golang.org/x/text/transform"
  23. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  24. )
  25. // NewFuncMap returns functions for injecting to templates
  26. func NewFuncMap() []template.FuncMap {
  27. return []template.FuncMap{map[string]interface{}{
  28. "GoVer": func() string {
  29. return strings.Title(runtime.Version())
  30. },
  31. "UseHTTPS": func() bool {
  32. return strings.HasPrefix(setting.AppURL, "https")
  33. },
  34. "AppName": func() string {
  35. return setting.AppName
  36. },
  37. "AppSubUrl": func() string {
  38. return setting.AppSubURL
  39. },
  40. "AppUrl": func() string {
  41. return setting.AppURL
  42. },
  43. "AppVer": func() string {
  44. return setting.AppVer
  45. },
  46. "AppBuiltWith": func() string {
  47. return setting.AppBuiltWith
  48. },
  49. "AppDomain": func() string {
  50. return setting.Domain
  51. },
  52. "DisableGravatar": func() bool {
  53. return setting.DisableGravatar
  54. },
  55. "ShowFooterTemplateLoadTime": func() bool {
  56. return setting.ShowFooterTemplateLoadTime
  57. },
  58. "LoadTimes": func(startTime time.Time) string {
  59. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  60. },
  61. "AvatarLink": base.AvatarLink,
  62. "Safe": Safe,
  63. "SafeJS": SafeJS,
  64. "Str2html": Str2html,
  65. "TimeSince": base.TimeSince,
  66. "RawTimeSince": base.RawTimeSince,
  67. "FileSize": base.FileSize,
  68. "Subtract": base.Subtract,
  69. "Add": func(a, b int) int {
  70. return a + b
  71. },
  72. "ActionIcon": ActionIcon,
  73. "DateFmtLong": func(t time.Time) string {
  74. return t.Format(time.RFC1123Z)
  75. },
  76. "DateFmtShort": func(t time.Time) string {
  77. return t.Format("Jan 02, 2006")
  78. },
  79. "SizeFmt": func(s int64) string {
  80. return base.FileSize(s)
  81. },
  82. "List": List,
  83. "SubStr": func(str string, start, length int) string {
  84. if len(str) == 0 {
  85. return ""
  86. }
  87. end := start + length
  88. if length == -1 {
  89. end = len(str)
  90. }
  91. if len(str) < end {
  92. return str
  93. }
  94. return str[start:end]
  95. },
  96. "EllipsisString": base.EllipsisString,
  97. "DiffTypeToStr": DiffTypeToStr,
  98. "DiffLineTypeToStr": DiffLineTypeToStr,
  99. "Sha1": Sha1,
  100. "ShortSha": base.ShortSha,
  101. "MD5": base.EncodeMD5,
  102. "ActionContent2Commits": ActionContent2Commits,
  103. "EscapePound": func(str string) string {
  104. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  105. },
  106. "RenderCommitMessage": RenderCommitMessage,
  107. "RenderCommitMessageLink": RenderCommitMessageLink,
  108. "ThemeColorMetaTag": func() string {
  109. return setting.UI.ThemeColorMetaTag
  110. },
  111. "MetaAuthor": func() string {
  112. return setting.UI.Meta.Author
  113. },
  114. "MetaDescription": func() string {
  115. return setting.UI.Meta.Description
  116. },
  117. "MetaKeywords": func() string {
  118. return setting.UI.Meta.Keywords
  119. },
  120. "FilenameIsImage": func(filename string) bool {
  121. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  122. return strings.HasPrefix(mimeType, "image/")
  123. },
  124. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  125. if ec != nil {
  126. def := ec.GetDefinitionForFilename(filename)
  127. if def.TabWidth > 0 {
  128. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  129. }
  130. }
  131. return "tab-size-8"
  132. },
  133. "SubJumpablePath": func(str string) []string {
  134. var path []string
  135. index := strings.LastIndex(str, "/")
  136. if index != -1 && index != len(str) {
  137. path = append(path, str[0:index+1])
  138. path = append(path, str[index+1:])
  139. } else {
  140. path = append(path, str)
  141. }
  142. return path
  143. },
  144. "JsonPrettyPrint": func(in string) string {
  145. var out bytes.Buffer
  146. err := json.Indent(&out, []byte(in), "", " ")
  147. if err != nil {
  148. return ""
  149. }
  150. return out.String()
  151. },
  152. "DisableGitHooks": func() bool {
  153. return setting.DisableGitHooks
  154. },
  155. "TrN": TrN,
  156. }}
  157. }
  158. // Safe render raw as HTML
  159. func Safe(raw string) template.HTML {
  160. return template.HTML(raw)
  161. }
  162. // SafeJS renders raw as JS
  163. func SafeJS(raw string) template.JS {
  164. return template.JS(raw)
  165. }
  166. // Str2html render Markdown text to HTML
  167. func Str2html(raw string) template.HTML {
  168. return template.HTML(markup.Sanitize(raw))
  169. }
  170. // List traversings the list
  171. func List(l *list.List) chan interface{} {
  172. e := l.Front()
  173. c := make(chan interface{})
  174. go func() {
  175. for e != nil {
  176. c <- e.Value
  177. e = e.Next()
  178. }
  179. close(c)
  180. }()
  181. return c
  182. }
  183. // Sha1 returns sha1 sum of string
  184. func Sha1(str string) string {
  185. return base.EncodeSha1(str)
  186. }
  187. // ToUTF8WithErr converts content to UTF8 encoding
  188. func ToUTF8WithErr(content []byte) (string, error) {
  189. charsetLabel, err := base.DetectEncoding(content)
  190. if err != nil {
  191. return "", err
  192. } else if charsetLabel == "UTF-8" {
  193. return string(content), nil
  194. }
  195. encoding, _ := charset.Lookup(charsetLabel)
  196. if encoding == nil {
  197. return string(content), fmt.Errorf("Unknown encoding: %s", charsetLabel)
  198. }
  199. // If there is an error, we concatenate the nicely decoded part and the
  200. // original left over. This way we won't loose data.
  201. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  202. if err != nil {
  203. result = result + string(content[n:])
  204. }
  205. return result, err
  206. }
  207. // ToUTF8 converts content to UTF8 encoding and ignore error
  208. func ToUTF8(content string) string {
  209. res, _ := ToUTF8WithErr([]byte(content))
  210. return res
  211. }
  212. // ReplaceLeft replaces all prefixes 'old' in 's' with 'new'.
  213. func ReplaceLeft(s, old, new string) string {
  214. oldLen, newLen, i, n := len(old), len(new), 0, 0
  215. for ; i < len(s) && strings.HasPrefix(s[i:], old); n++ {
  216. i += oldLen
  217. }
  218. // simple optimization
  219. if n == 0 {
  220. return s
  221. }
  222. // allocating space for the new string
  223. curLen := n*newLen + len(s[i:])
  224. replacement := make([]byte, curLen, curLen)
  225. j := 0
  226. for ; j < n*newLen; j += newLen {
  227. copy(replacement[j:j+newLen], new)
  228. }
  229. copy(replacement[j:], s[i:])
  230. return string(replacement)
  231. }
  232. // RenderCommitMessage renders commit message with XSS-safe and special links.
  233. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  234. return renderCommitMessage(msg, markup.RenderIssueIndexPatternOptions{
  235. URLPrefix: urlPrefix,
  236. Metas: metas,
  237. })
  238. }
  239. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  240. // default url, handling for special links.
  241. func RenderCommitMessageLink(msg, urlPrefix string, urlDefault string, metas map[string]string) template.HTML {
  242. return renderCommitMessage(msg, markup.RenderIssueIndexPatternOptions{
  243. DefaultURL: urlDefault,
  244. URLPrefix: urlPrefix,
  245. Metas: metas,
  246. })
  247. }
  248. func renderCommitMessage(msg string, opts markup.RenderIssueIndexPatternOptions) template.HTML {
  249. cleanMsg := template.HTMLEscapeString(msg)
  250. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), opts))
  251. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  252. if len(msgLines) == 0 {
  253. return template.HTML("")
  254. }
  255. return template.HTML(msgLines[0])
  256. }
  257. // Actioner describes an action
  258. type Actioner interface {
  259. GetOpType() models.ActionType
  260. GetActUserName() string
  261. GetRepoUserName() string
  262. GetRepoName() string
  263. GetRepoPath() string
  264. GetRepoLink() string
  265. GetBranch() string
  266. GetContent() string
  267. GetCreate() time.Time
  268. GetIssueInfos() []string
  269. }
  270. // ActionIcon accepts an action operation type and returns an icon class name.
  271. func ActionIcon(opType models.ActionType) string {
  272. switch opType {
  273. case models.ActionCreateRepo, models.ActionTransferRepo:
  274. return "repo"
  275. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  276. return "git-commit"
  277. case models.ActionCreateIssue:
  278. return "issue-opened"
  279. case models.ActionCreatePullRequest:
  280. return "git-pull-request"
  281. case models.ActionCommentIssue:
  282. return "comment-discussion"
  283. case models.ActionMergePullRequest:
  284. return "git-merge"
  285. case models.ActionCloseIssue, models.ActionClosePullRequest:
  286. return "issue-closed"
  287. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  288. return "issue-reopened"
  289. default:
  290. return "invalid type"
  291. }
  292. }
  293. // ActionContent2Commits converts action content to push commits
  294. func ActionContent2Commits(act Actioner) *models.PushCommits {
  295. push := models.NewPushCommits()
  296. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  297. log.Error(4, "json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  298. }
  299. return push
  300. }
  301. // DiffTypeToStr returns diff type name
  302. func DiffTypeToStr(diffType int) string {
  303. diffTypes := map[int]string{
  304. 1: "add", 2: "modify", 3: "del", 4: "rename",
  305. }
  306. return diffTypes[diffType]
  307. }
  308. // DiffLineTypeToStr returns diff line type name
  309. func DiffLineTypeToStr(diffType int) string {
  310. switch diffType {
  311. case 2:
  312. return "add"
  313. case 3:
  314. return "del"
  315. case 4:
  316. return "tag"
  317. }
  318. return "same"
  319. }
  320. // Language specific rules for translating plural texts
  321. var trNLangRules = map[string]func(int64) int{
  322. "en-US": func(cnt int64) int {
  323. if cnt == 1 {
  324. return 0
  325. }
  326. return 1
  327. },
  328. "lv-LV": func(cnt int64) int {
  329. if cnt%10 == 1 && cnt%100 != 11 {
  330. return 0
  331. }
  332. return 1
  333. },
  334. "ru-RU": func(cnt int64) int {
  335. if cnt%10 == 1 && cnt%100 != 11 {
  336. return 0
  337. }
  338. return 1
  339. },
  340. "zh-CN": func(cnt int64) int {
  341. return 0
  342. },
  343. "zh-HK": func(cnt int64) int {
  344. return 0
  345. },
  346. "zh-TW": func(cnt int64) int {
  347. return 0
  348. },
  349. }
  350. // TrN returns key to be used for plural text translation
  351. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  352. var c int64
  353. if t, ok := cnt.(int); ok {
  354. c = int64(t)
  355. } else if t, ok := cnt.(int16); ok {
  356. c = int64(t)
  357. } else if t, ok := cnt.(int32); ok {
  358. c = int64(t)
  359. } else if t, ok := cnt.(int64); ok {
  360. c = t
  361. } else {
  362. return keyN
  363. }
  364. ruleFunc, ok := trNLangRules[lang]
  365. if !ok {
  366. ruleFunc = trNLangRules["en-US"]
  367. }
  368. if ruleFunc(c) == 0 {
  369. return key1
  370. }
  371. return keyN
  372. }