THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

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

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