tool.go 11 KB

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