template.go 7.6 KB

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