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 11 kB

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