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 11 kB

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