template.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package template
  5. import (
  6. "container/list"
  7. "fmt"
  8. "html/template"
  9. "mime"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/editorconfig/editorconfig-core-go/v2"
  16. jsoniter "github.com/json-iterator/go"
  17. "github.com/microcosm-cc/bluemonday"
  18. "golang.org/x/net/html/charset"
  19. "golang.org/x/text/transform"
  20. log "gopkg.in/clog.v1"
  21. "gogs.io/gogs/internal/db"
  22. "gogs.io/gogs/internal/markup"
  23. "gogs.io/gogs/internal/setting"
  24. "gogs.io/gogs/internal/tool"
  25. )
  26. var (
  27. funcMap []template.FuncMap
  28. funcMapOnce sync.Once
  29. )
  30. // FuncMap returns a list of user-defined template functions.
  31. func FuncMap() []template.FuncMap {
  32. funcMapOnce.Do(func() {
  33. funcMap = []template.FuncMap{map[string]interface{}{
  34. "GoVer": func() string {
  35. return strings.Title(runtime.Version())
  36. },
  37. "Year": func() int {
  38. return time.Now().Year()
  39. },
  40. "UseHTTPS": func() bool {
  41. return strings.HasPrefix(setting.AppURL, "https")
  42. },
  43. "AppName": func() string {
  44. return setting.AppName
  45. },
  46. "AppSubURL": func() string {
  47. return setting.AppSubURL
  48. },
  49. "AppURL": func() string {
  50. return setting.AppURL
  51. },
  52. "AppVer": func() string {
  53. return setting.AppVer
  54. },
  55. "AppDomain": func() string {
  56. return setting.Domain
  57. },
  58. "DisableGravatar": func() bool {
  59. return setting.DisableGravatar
  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": tool.AvatarLink,
  68. "AppendAvatarSize": tool.AppendAvatarSize,
  69. "Safe": Safe,
  70. "Sanitize": bluemonday.UGCPolicy().Sanitize,
  71. "Str2HTML": Str2HTML,
  72. "NewLine2br": NewLine2br,
  73. "TimeSince": tool.TimeSince,
  74. "RawTimeSince": tool.RawTimeSince,
  75. "FileSize": tool.FileSize,
  76. "Subtract": tool.Subtract,
  77. "Add": func(a, b int) int {
  78. return a + b
  79. },
  80. "ActionIcon": ActionIcon,
  81. "DateFmtLong": func(t time.Time) string {
  82. return t.Format(time.RFC1123Z)
  83. },
  84. "DateFmtShort": func(t time.Time) string {
  85. return t.Format("Jan 02, 2006")
  86. },
  87. "List": List,
  88. "SubStr": func(str string, start, length int) string {
  89. if len(str) == 0 {
  90. return ""
  91. }
  92. end := start + length
  93. if length == -1 {
  94. end = len(str)
  95. }
  96. if len(str) < end {
  97. return str
  98. }
  99. return str[start:end]
  100. },
  101. "Join": strings.Join,
  102. "EllipsisString": tool.EllipsisString,
  103. "DiffTypeToStr": DiffTypeToStr,
  104. "DiffLineTypeToStr": DiffLineTypeToStr,
  105. "Sha1": Sha1,
  106. "ShortSHA1": tool.ShortSHA1,
  107. "MD5": tool.MD5,
  108. "ActionContent2Commits": ActionContent2Commits,
  109. "EscapePound": EscapePound,
  110. "RenderCommitMessage": RenderCommitMessage,
  111. "ThemeColorMetaTag": func() string {
  112. return setting.UI.ThemeColorMetaTag
  113. },
  114. "FilenameIsImage": func(filename string) bool {
  115. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  116. return strings.HasPrefix(mimeType, "image/")
  117. },
  118. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  119. if ec != nil {
  120. def, err := ec.GetDefinitionForFilename(filename)
  121. if err == nil && def.TabWidth > 0 {
  122. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  123. }
  124. }
  125. return "tab-size-8"
  126. },
  127. }}
  128. })
  129. return funcMap
  130. }
  131. func Safe(raw string) template.HTML {
  132. return template.HTML(raw)
  133. }
  134. func Str2HTML(raw string) template.HTML {
  135. return template.HTML(markup.Sanitize(raw))
  136. }
  137. // NewLine2br simply replaces "\n" to "<br>".
  138. func NewLine2br(raw string) string {
  139. return strings.Replace(raw, "\n", "<br>", -1)
  140. }
  141. func List(l *list.List) chan interface{} {
  142. e := l.Front()
  143. c := make(chan interface{})
  144. go func() {
  145. for e != nil {
  146. c <- e.Value
  147. e = e.Next()
  148. }
  149. close(c)
  150. }()
  151. return c
  152. }
  153. func Sha1(str string) string {
  154. return tool.SHA1(str)
  155. }
  156. func ToUTF8WithErr(content []byte) (error, string) {
  157. charsetLabel, err := tool.DetectEncoding(content)
  158. if err != nil {
  159. return err, ""
  160. } else if charsetLabel == "UTF-8" {
  161. return nil, string(content)
  162. }
  163. encoding, _ := charset.Lookup(charsetLabel)
  164. if encoding == nil {
  165. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  166. }
  167. // If there is an error, we concatenate the nicely decoded part and the
  168. // original left over. This way we won't loose data.
  169. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  170. if err != nil {
  171. result = result + string(content[n:])
  172. }
  173. return err, result
  174. }
  175. // FIXME: Unused function
  176. func ToUTF8(content string) string {
  177. _, res := ToUTF8WithErr([]byte(content))
  178. return res
  179. }
  180. // Replaces all prefixes 'old' in 's' with 'new'.
  181. // FIXME: Unused function
  182. func ReplaceLeft(s, old, new string) string {
  183. old_len, new_len, i, n := len(old), len(new), 0, 0
  184. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  185. i += old_len
  186. }
  187. // simple optimization
  188. if n == 0 {
  189. return s
  190. }
  191. // allocating space for the new string
  192. newLen := n*new_len + len(s[i:])
  193. replacement := make([]byte, newLen, newLen)
  194. j := 0
  195. for ; j < n*new_len; j += new_len {
  196. copy(replacement[j:j+new_len], new)
  197. }
  198. copy(replacement[j:], s[i:])
  199. return string(replacement)
  200. }
  201. // RenderCommitMessage renders commit message with special links.
  202. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  203. cleanMsg := template.HTMLEscapeString(msg)
  204. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  205. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  206. numLines := len(msgLines)
  207. if numLines == 0 {
  208. return ""
  209. } else if !full {
  210. return msgLines[0]
  211. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  212. // First line is a header, standalone or followed by empty line
  213. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  214. if numLines >= 2 {
  215. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  216. } else {
  217. fullMessage = header
  218. }
  219. } else {
  220. // Non-standard git message, there is no header line
  221. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  222. }
  223. return fullMessage
  224. }
  225. type Actioner interface {
  226. GetOpType() int
  227. GetActUserName() string
  228. GetRepoUserName() string
  229. GetRepoName() string
  230. GetRepoPath() string
  231. GetRepoLink() string
  232. GetBranch() string
  233. GetContent() string
  234. GetCreate() time.Time
  235. GetIssueInfos() []string
  236. }
  237. // ActionIcon accepts a int that represents action operation type
  238. // and returns a icon class name.
  239. func ActionIcon(opType int) string {
  240. switch opType {
  241. case 1, 8: // Create and transfer repository
  242. return "repo"
  243. case 5: // Commit repository
  244. return "git-commit"
  245. case 6: // Create issue
  246. return "issue-opened"
  247. case 7: // New pull request
  248. return "git-pull-request"
  249. case 9: // Push tag
  250. return "tag"
  251. case 10: // Comment issue
  252. return "comment-discussion"
  253. case 11: // Merge pull request
  254. return "git-merge"
  255. case 12, 14: // Close issue or pull request
  256. return "issue-closed"
  257. case 13, 15: // Reopen issue or pull request
  258. return "issue-reopened"
  259. case 16: // Create branch
  260. return "git-branch"
  261. case 17, 18: // Delete branch or tag
  262. return "alert"
  263. case 19: // Fork a repository
  264. return "repo-forked"
  265. case 20, 21, 22: // Mirror sync
  266. return "repo-clone"
  267. default:
  268. return "invalid type"
  269. }
  270. }
  271. func ActionContent2Commits(act Actioner) *db.PushCommits {
  272. push := db.NewPushCommits()
  273. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  274. log.Error(4, "Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  275. }
  276. return push
  277. }
  278. func EscapePound(str string) string {
  279. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  280. }
  281. func DiffTypeToStr(diffType int) string {
  282. diffTypes := map[int]string{
  283. 1: "add", 2: "modify", 3: "del", 4: "rename",
  284. }
  285. return diffTypes[diffType]
  286. }
  287. func DiffLineTypeToStr(diffType int) string {
  288. switch diffType {
  289. case 2:
  290. return "add"
  291. case 3:
  292. return "del"
  293. case 4:
  294. return "tag"
  295. }
  296. return "same"
  297. }