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

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