tool.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 base
  5. import (
  6. "crypto/hmac"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "fmt"
  13. "hash"
  14. "html/template"
  15. "math"
  16. "regexp"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/Unknwon/com"
  21. "github.com/Unknwon/i18n"
  22. "github.com/microcosm-cc/bluemonday"
  23. "github.com/gogits/chardet"
  24. "github.com/gogits/gogs/modules/avatar"
  25. "github.com/gogits/gogs/modules/log"
  26. "github.com/gogits/gogs/modules/setting"
  27. )
  28. var Sanitizer = bluemonday.UGCPolicy()
  29. func BuildSanitizer() {
  30. // Normal markdown-stuff
  31. Sanitizer.AllowAttrs("class").Matching(regexp.MustCompile(`[\p{L}\p{N}\s\-_',:\[\]!\./\\\(\)&]*`)).OnElements("code")
  32. // Checkboxes
  33. Sanitizer.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  34. Sanitizer.AllowAttrs("checked", "disabled").OnElements("input")
  35. // Custom URL-Schemes
  36. Sanitizer.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  37. }
  38. // EncodeMD5 encodes string to md5 hex value.
  39. func EncodeMD5(str string) string {
  40. m := md5.New()
  41. m.Write([]byte(str))
  42. return hex.EncodeToString(m.Sum(nil))
  43. }
  44. // Encode string to sha1 hex value.
  45. func EncodeSha1(str string) string {
  46. h := sha1.New()
  47. h.Write([]byte(str))
  48. return hex.EncodeToString(h.Sum(nil))
  49. }
  50. func ShortSha(sha1 string) string {
  51. if len(sha1) == 40 {
  52. return sha1[:10]
  53. }
  54. return sha1
  55. }
  56. func DetectEncoding(content []byte) (string, error) {
  57. if utf8.Valid(content) {
  58. log.Debug("Detected encoding: utf-8 (fast)")
  59. return "UTF-8", nil
  60. }
  61. result, err := chardet.NewTextDetector().DetectBest(content)
  62. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  63. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  64. return setting.Repository.AnsiCharset, err
  65. }
  66. log.Debug("Detected encoding: %s", result.Charset)
  67. return result.Charset, err
  68. }
  69. func BasicAuthDecode(encoded string) (string, string, error) {
  70. s, err := base64.StdEncoding.DecodeString(encoded)
  71. if err != nil {
  72. return "", "", err
  73. }
  74. auth := strings.SplitN(string(s), ":", 2)
  75. return auth[0], auth[1], nil
  76. }
  77. func BasicAuthEncode(username, password string) string {
  78. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  79. }
  80. // GetRandomString generate random string by specify chars.
  81. func GetRandomString(n int, alphabets ...byte) string {
  82. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  83. var bytes = make([]byte, n)
  84. rand.Read(bytes)
  85. for i, b := range bytes {
  86. if len(alphabets) == 0 {
  87. bytes[i] = alphanum[b%byte(len(alphanum))]
  88. } else {
  89. bytes[i] = alphabets[b%byte(len(alphabets))]
  90. }
  91. }
  92. return string(bytes)
  93. }
  94. // http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
  95. func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  96. prf := hmac.New(h, password)
  97. hashLen := prf.Size()
  98. numBlocks := (keyLen + hashLen - 1) / hashLen
  99. var buf [4]byte
  100. dk := make([]byte, 0, numBlocks*hashLen)
  101. U := make([]byte, hashLen)
  102. for block := 1; block <= numBlocks; block++ {
  103. // N.B.: || means concatenation, ^ means XOR
  104. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  105. // U_1 = PRF(password, salt || uint(i))
  106. prf.Reset()
  107. prf.Write(salt)
  108. buf[0] = byte(block >> 24)
  109. buf[1] = byte(block >> 16)
  110. buf[2] = byte(block >> 8)
  111. buf[3] = byte(block)
  112. prf.Write(buf[:4])
  113. dk = prf.Sum(dk)
  114. T := dk[len(dk)-hashLen:]
  115. copy(U, T)
  116. // U_n = PRF(password, U_(n-1))
  117. for n := 2; n <= iter; n++ {
  118. prf.Reset()
  119. prf.Write(U)
  120. U = U[:0]
  121. U = prf.Sum(U)
  122. for x := range U {
  123. T[x] ^= U[x]
  124. }
  125. }
  126. }
  127. return dk[:keyLen]
  128. }
  129. // verify time limit code
  130. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  131. if len(code) <= 18 {
  132. return false
  133. }
  134. // split code
  135. start := code[:12]
  136. lives := code[12:18]
  137. if d, err := com.StrTo(lives).Int(); err == nil {
  138. minutes = d
  139. }
  140. // right active code
  141. retCode := CreateTimeLimitCode(data, minutes, start)
  142. if retCode == code && minutes > 0 {
  143. // check time is expired or not
  144. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  145. now := time.Now()
  146. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  147. return true
  148. }
  149. }
  150. return false
  151. }
  152. const TimeLimitCodeLength = 12 + 6 + 40
  153. // create a time limit code
  154. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  155. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  156. format := "200601021504"
  157. var start, end time.Time
  158. var startStr, endStr string
  159. if startInf == nil {
  160. // Use now time create code
  161. start = time.Now()
  162. startStr = start.Format(format)
  163. } else {
  164. // use start string create code
  165. startStr = startInf.(string)
  166. start, _ = time.ParseInLocation(format, startStr, time.Local)
  167. startStr = start.Format(format)
  168. }
  169. end = start.Add(time.Minute * time.Duration(minutes))
  170. endStr = end.Format(format)
  171. // create sha1 encode string
  172. sh := sha1.New()
  173. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  174. encoded := hex.EncodeToString(sh.Sum(nil))
  175. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  176. return code
  177. }
  178. // AvatarLink returns avatar link by given e-mail.
  179. func AvatarLink(email string) string {
  180. if setting.DisableGravatar || setting.OfflineMode {
  181. return setting.AppSubUrl + "/img/avatar_default.jpg"
  182. }
  183. gravatarHash := avatar.HashEmail(email)
  184. if setting.Service.EnableCacheAvatar {
  185. return setting.AppSubUrl + "/avatar/" + gravatarHash
  186. }
  187. return setting.GravatarSource + gravatarHash
  188. }
  189. // Seconds-based time units
  190. const (
  191. Minute = 60
  192. Hour = 60 * Minute
  193. Day = 24 * Hour
  194. Week = 7 * Day
  195. Month = 30 * Day
  196. Year = 12 * Month
  197. )
  198. func computeTimeDiff(diff int64) (int64, string) {
  199. diffStr := ""
  200. switch {
  201. case diff <= 0:
  202. diff = 0
  203. diffStr = "now"
  204. case diff < 2:
  205. diff = 0
  206. diffStr = "1 second"
  207. case diff < 1*Minute:
  208. diffStr = fmt.Sprintf("%d seconds", diff)
  209. diff = 0
  210. case diff < 2*Minute:
  211. diff -= 1 * Minute
  212. diffStr = "1 minute"
  213. case diff < 1*Hour:
  214. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  215. diff -= diff / Minute * Minute
  216. case diff < 2*Hour:
  217. diff -= 1 * Hour
  218. diffStr = "1 hour"
  219. case diff < 1*Day:
  220. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  221. diff -= diff / Hour * Hour
  222. case diff < 2*Day:
  223. diff -= 1 * Day
  224. diffStr = "1 day"
  225. case diff < 1*Week:
  226. diffStr = fmt.Sprintf("%d days", diff/Day)
  227. diff -= diff / Day * Day
  228. case diff < 2*Week:
  229. diff -= 1 * Week
  230. diffStr = "1 week"
  231. case diff < 1*Month:
  232. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  233. diff -= diff / Week * Week
  234. case diff < 2*Month:
  235. diff -= 1 * Month
  236. diffStr = "1 month"
  237. case diff < 1*Year:
  238. diffStr = fmt.Sprintf("%d months", diff/Month)
  239. diff -= diff / Month * Month
  240. case diff < 2*Year:
  241. diff -= 1 * Year
  242. diffStr = "1 year"
  243. default:
  244. diffStr = fmt.Sprintf("%d years", diff/Year)
  245. diff = 0
  246. }
  247. return diff, diffStr
  248. }
  249. // TimeSincePro calculates the time interval and generate full user-friendly string.
  250. func TimeSincePro(then time.Time) string {
  251. now := time.Now()
  252. diff := now.Unix() - then.Unix()
  253. if then.After(now) {
  254. return "future"
  255. }
  256. var timeStr, diffStr string
  257. for {
  258. if diff == 0 {
  259. break
  260. }
  261. diff, diffStr = computeTimeDiff(diff)
  262. timeStr += ", " + diffStr
  263. }
  264. return strings.TrimPrefix(timeStr, ", ")
  265. }
  266. func timeSince(then time.Time, lang string) string {
  267. now := time.Now()
  268. lbl := i18n.Tr(lang, "tool.ago")
  269. diff := now.Unix() - then.Unix()
  270. if then.After(now) {
  271. lbl = i18n.Tr(lang, "tool.from_now")
  272. diff = then.Unix() - now.Unix()
  273. }
  274. switch {
  275. case diff <= 0:
  276. return i18n.Tr(lang, "tool.now")
  277. case diff <= 2:
  278. return i18n.Tr(lang, "tool.1s", lbl)
  279. case diff < 1*Minute:
  280. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  281. case diff < 2*Minute:
  282. return i18n.Tr(lang, "tool.1m", lbl)
  283. case diff < 1*Hour:
  284. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  285. case diff < 2*Hour:
  286. return i18n.Tr(lang, "tool.1h", lbl)
  287. case diff < 1*Day:
  288. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  289. case diff < 2*Day:
  290. return i18n.Tr(lang, "tool.1d", lbl)
  291. case diff < 1*Week:
  292. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  293. case diff < 2*Week:
  294. return i18n.Tr(lang, "tool.1w", lbl)
  295. case diff < 1*Month:
  296. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  297. case diff < 2*Month:
  298. return i18n.Tr(lang, "tool.1mon", lbl)
  299. case diff < 1*Year:
  300. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  301. case diff < 2*Year:
  302. return i18n.Tr(lang, "tool.1y", lbl)
  303. default:
  304. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  305. }
  306. }
  307. func RawTimeSince(t time.Time, lang string) string {
  308. return timeSince(t, lang)
  309. }
  310. // TimeSince calculates the time interval and generate user-friendly string.
  311. func TimeSince(t time.Time, lang string) template.HTML {
  312. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  313. }
  314. const (
  315. Byte = 1
  316. KByte = Byte * 1024
  317. MByte = KByte * 1024
  318. GByte = MByte * 1024
  319. TByte = GByte * 1024
  320. PByte = TByte * 1024
  321. EByte = PByte * 1024
  322. )
  323. var bytesSizeTable = map[string]uint64{
  324. "b": Byte,
  325. "kb": KByte,
  326. "mb": MByte,
  327. "gb": GByte,
  328. "tb": TByte,
  329. "pb": PByte,
  330. "eb": EByte,
  331. }
  332. func logn(n, b float64) float64 {
  333. return math.Log(n) / math.Log(b)
  334. }
  335. func humanateBytes(s uint64, base float64, sizes []string) string {
  336. if s < 10 {
  337. return fmt.Sprintf("%dB", s)
  338. }
  339. e := math.Floor(logn(float64(s), base))
  340. suffix := sizes[int(e)]
  341. val := float64(s) / math.Pow(base, math.Floor(e))
  342. f := "%.0f"
  343. if val < 10 {
  344. f = "%.1f"
  345. }
  346. return fmt.Sprintf(f+"%s", val, suffix)
  347. }
  348. // FileSize calculates the file size and generate user-friendly string.
  349. func FileSize(s int64) string {
  350. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  351. return humanateBytes(uint64(s), 1024, sizes)
  352. }
  353. // Subtract deals with subtraction of all types of number.
  354. func Subtract(left interface{}, right interface{}) interface{} {
  355. var rleft, rright int64
  356. var fleft, fright float64
  357. var isInt bool = true
  358. switch left.(type) {
  359. case int:
  360. rleft = int64(left.(int))
  361. case int8:
  362. rleft = int64(left.(int8))
  363. case int16:
  364. rleft = int64(left.(int16))
  365. case int32:
  366. rleft = int64(left.(int32))
  367. case int64:
  368. rleft = left.(int64)
  369. case float32:
  370. fleft = float64(left.(float32))
  371. isInt = false
  372. case float64:
  373. fleft = left.(float64)
  374. isInt = false
  375. }
  376. switch right.(type) {
  377. case int:
  378. rright = int64(right.(int))
  379. case int8:
  380. rright = int64(right.(int8))
  381. case int16:
  382. rright = int64(right.(int16))
  383. case int32:
  384. rright = int64(right.(int32))
  385. case int64:
  386. rright = right.(int64)
  387. case float32:
  388. fright = float64(left.(float32))
  389. isInt = false
  390. case float64:
  391. fleft = left.(float64)
  392. isInt = false
  393. }
  394. if isInt {
  395. return rleft - rright
  396. } else {
  397. return fleft + float64(rleft) - (fright + float64(rright))
  398. }
  399. }
  400. // EllipsisString returns a truncated short string,
  401. // it appends '...' in the end of the length of string is too large.
  402. func EllipsisString(str string, length int) string {
  403. if len(str) < length {
  404. return str
  405. }
  406. return str[:length-3] + "..."
  407. }
  408. // StringsToInt64s converts a slice of string to a slice of int64.
  409. func StringsToInt64s(strs []string) []int64 {
  410. ints := make([]int64, len(strs))
  411. for i := range strs {
  412. ints[i] = com.StrTo(strs[i]).MustInt64()
  413. }
  414. return ints
  415. }
  416. // Int64sToStrings converts a slice of int64 to a slice of string.
  417. func Int64sToStrings(ints []int64) []string {
  418. strs := make([]string, len(ints))
  419. for i := range ints {
  420. strs[i] = com.ToStr(ints[i])
  421. }
  422. return strs
  423. }
  424. // Int64sToMap converts a slice of int64 to a int64 map.
  425. func Int64sToMap(ints []int64) map[int64]bool {
  426. m := make(map[int64]bool)
  427. for _, i := range ints {
  428. m[i] = true
  429. }
  430. return m
  431. }