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