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

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