You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tool.go 12 kB

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