tool.go 10 KB

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