選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

helper.go 13KB

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