tool.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. "github.com/Unknwon/com"
  20. "github.com/Unknwon/i18n"
  21. "github.com/microcosm-cc/bluemonday"
  22. "github.com/gogits/gogs/modules/avatar"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. var Sanitizer = bluemonday.UGCPolicy().AllowAttrs("class").Matching(regexp.MustCompile(`[\p{L}\p{N}\s\-_',:\[\]!\./\\\(\)&]*`)).OnElements("code")
  26. // Encode string to md5 hex value.
  27. func EncodeMd5(str string) string {
  28. m := md5.New()
  29. m.Write([]byte(str))
  30. return hex.EncodeToString(m.Sum(nil))
  31. }
  32. // Encode string to sha1 hex value.
  33. func EncodeSha1(str string) string {
  34. h := sha1.New()
  35. h.Write([]byte(str))
  36. return hex.EncodeToString(h.Sum(nil))
  37. }
  38. func BasicAuthDecode(encoded string) (string, string, error) {
  39. s, err := base64.StdEncoding.DecodeString(encoded)
  40. if err != nil {
  41. return "", "", err
  42. }
  43. auth := strings.SplitN(string(s), ":", 2)
  44. return auth[0], auth[1], nil
  45. }
  46. func BasicAuthEncode(username, password string) string {
  47. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  48. }
  49. // GetRandomString generate random string by specify chars.
  50. func GetRandomString(n int, alphabets ...byte) string {
  51. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  52. var bytes = make([]byte, n)
  53. rand.Read(bytes)
  54. for i, b := range bytes {
  55. if len(alphabets) == 0 {
  56. bytes[i] = alphanum[b%byte(len(alphanum))]
  57. } else {
  58. bytes[i] = alphabets[b%byte(len(alphabets))]
  59. }
  60. }
  61. return string(bytes)
  62. }
  63. // http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
  64. func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  65. prf := hmac.New(h, password)
  66. hashLen := prf.Size()
  67. numBlocks := (keyLen + hashLen - 1) / hashLen
  68. var buf [4]byte
  69. dk := make([]byte, 0, numBlocks*hashLen)
  70. U := make([]byte, hashLen)
  71. for block := 1; block <= numBlocks; block++ {
  72. // N.B.: || means concatenation, ^ means XOR
  73. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  74. // U_1 = PRF(password, salt || uint(i))
  75. prf.Reset()
  76. prf.Write(salt)
  77. buf[0] = byte(block >> 24)
  78. buf[1] = byte(block >> 16)
  79. buf[2] = byte(block >> 8)
  80. buf[3] = byte(block)
  81. prf.Write(buf[:4])
  82. dk = prf.Sum(dk)
  83. T := dk[len(dk)-hashLen:]
  84. copy(U, T)
  85. // U_n = PRF(password, U_(n-1))
  86. for n := 2; n <= iter; n++ {
  87. prf.Reset()
  88. prf.Write(U)
  89. U = U[:0]
  90. U = prf.Sum(U)
  91. for x := range U {
  92. T[x] ^= U[x]
  93. }
  94. }
  95. }
  96. return dk[:keyLen]
  97. }
  98. // verify time limit code
  99. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  100. if len(code) <= 18 {
  101. return false
  102. }
  103. // split code
  104. start := code[:12]
  105. lives := code[12:18]
  106. if d, err := com.StrTo(lives).Int(); err == nil {
  107. minutes = d
  108. }
  109. // right active code
  110. retCode := CreateTimeLimitCode(data, minutes, start)
  111. if retCode == code && minutes > 0 {
  112. // check time is expired or not
  113. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  114. now := time.Now()
  115. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  116. return true
  117. }
  118. }
  119. return false
  120. }
  121. const TimeLimitCodeLength = 12 + 6 + 40
  122. // create a time limit code
  123. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  124. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  125. format := "200601021504"
  126. var start, end time.Time
  127. var startStr, endStr string
  128. if startInf == nil {
  129. // Use now time create code
  130. start = time.Now()
  131. startStr = start.Format(format)
  132. } else {
  133. // use start string create code
  134. startStr = startInf.(string)
  135. start, _ = time.ParseInLocation(format, startStr, time.Local)
  136. startStr = start.Format(format)
  137. }
  138. end = start.Add(time.Minute * time.Duration(minutes))
  139. endStr = end.Format(format)
  140. // create sha1 encode string
  141. sh := sha1.New()
  142. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  143. encoded := hex.EncodeToString(sh.Sum(nil))
  144. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  145. return code
  146. }
  147. // AvatarLink returns avatar link by given e-mail.
  148. func AvatarLink(email string) string {
  149. if setting.DisableGravatar || setting.OfflineMode {
  150. return setting.AppSubUrl + "/img/avatar_default.jpg"
  151. }
  152. gravatarHash := avatar.HashEmail(email)
  153. if setting.Service.EnableCacheAvatar {
  154. return setting.AppSubUrl + "/avatar/" + gravatarHash
  155. }
  156. return setting.GravatarSource + gravatarHash
  157. }
  158. // Seconds-based time units
  159. const (
  160. Minute = 60
  161. Hour = 60 * Minute
  162. Day = 24 * Hour
  163. Week = 7 * Day
  164. Month = 30 * Day
  165. Year = 12 * Month
  166. )
  167. func computeTimeDiff(diff int64) (int64, string) {
  168. diffStr := ""
  169. switch {
  170. case diff <= 0:
  171. diff = 0
  172. diffStr = "now"
  173. case diff < 2:
  174. diff = 0
  175. diffStr = "1 second"
  176. case diff < 1*Minute:
  177. diffStr = fmt.Sprintf("%d seconds", diff)
  178. diff = 0
  179. case diff < 2*Minute:
  180. diff -= 1 * Minute
  181. diffStr = "1 minute"
  182. case diff < 1*Hour:
  183. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  184. diff -= diff / Minute * Minute
  185. case diff < 2*Hour:
  186. diff -= 1 * Hour
  187. diffStr = "1 hour"
  188. case diff < 1*Day:
  189. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  190. diff -= diff / Hour * Hour
  191. case diff < 2*Day:
  192. diff -= 1 * Day
  193. diffStr = "1 day"
  194. case diff < 1*Week:
  195. diffStr = fmt.Sprintf("%d days", diff/Day)
  196. diff -= diff / Day * Day
  197. case diff < 2*Week:
  198. diff -= 1 * Week
  199. diffStr = "1 week"
  200. case diff < 1*Month:
  201. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  202. diff -= diff / Week * Week
  203. case diff < 2*Month:
  204. diff -= 1 * Month
  205. diffStr = "1 month"
  206. case diff < 1*Year:
  207. diffStr = fmt.Sprintf("%d months", diff/Month)
  208. diff -= diff / Month * Month
  209. case diff < 2*Year:
  210. diff -= 1 * Year
  211. diffStr = "1 year"
  212. default:
  213. diffStr = fmt.Sprintf("%d years", diff/Year)
  214. diff = 0
  215. }
  216. return diff, diffStr
  217. }
  218. // TimeSincePro calculates the time interval and generate full user-friendly string.
  219. func TimeSincePro(then time.Time) string {
  220. now := time.Now()
  221. diff := now.Unix() - then.Unix()
  222. if then.After(now) {
  223. return "future"
  224. }
  225. var timeStr, diffStr string
  226. for {
  227. if diff == 0 {
  228. break
  229. }
  230. diff, diffStr = computeTimeDiff(diff)
  231. timeStr += ", " + diffStr
  232. }
  233. return strings.TrimPrefix(timeStr, ", ")
  234. }
  235. func timeSince(then time.Time, lang string) string {
  236. now := time.Now()
  237. lbl := i18n.Tr(lang, "tool.ago")
  238. diff := now.Unix() - then.Unix()
  239. if then.After(now) {
  240. lbl = i18n.Tr(lang, "tool.from_now")
  241. diff = then.Unix() - now.Unix()
  242. }
  243. switch {
  244. case diff <= 0:
  245. return i18n.Tr(lang, "tool.now")
  246. case diff <= 2:
  247. return i18n.Tr(lang, "tool.1s", lbl)
  248. case diff < 1*Minute:
  249. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  250. case diff < 2*Minute:
  251. return i18n.Tr(lang, "tool.1m", lbl)
  252. case diff < 1*Hour:
  253. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  254. case diff < 2*Hour:
  255. return i18n.Tr(lang, "tool.1h", lbl)
  256. case diff < 1*Day:
  257. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  258. case diff < 2*Day:
  259. return i18n.Tr(lang, "tool.1d", lbl)
  260. case diff < 1*Week:
  261. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  262. case diff < 2*Week:
  263. return i18n.Tr(lang, "tool.1w", lbl)
  264. case diff < 1*Month:
  265. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  266. case diff < 2*Month:
  267. return i18n.Tr(lang, "tool.1mon", lbl)
  268. case diff < 1*Year:
  269. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  270. case diff < 2*Year:
  271. return i18n.Tr(lang, "tool.1y", lbl)
  272. default:
  273. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  274. }
  275. }
  276. func RawTimeSince(t time.Time, lang string) string {
  277. return timeSince(t, lang)
  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. // StringsToInt64s converts a slice of string to a slice of int64.
  370. func StringsToInt64s(strs []string) []int64 {
  371. ints := make([]int64, len(strs))
  372. for i := range strs {
  373. ints[i] = com.StrTo(strs[i]).MustInt64()
  374. }
  375. return ints
  376. }
  377. // Int64sToStrings converts a slice of int64 to a slice of string.
  378. func Int64sToStrings(ints []int64) []string {
  379. strs := make([]string, len(ints))
  380. for i := range ints {
  381. strs[i] = com.ToStr(ints[i])
  382. }
  383. return strs
  384. }
  385. // Int64sToMap converts a slice of int64 to a int64 map.
  386. func Int64sToMap(ints []int64) map[int64]bool {
  387. m := make(map[int64]bool)
  388. for _, i := range ints {
  389. m[i] = true
  390. }
  391. return m
  392. }