tool.go 11 KB

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