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

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