tool.go 11 KB

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