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

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