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

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