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

473 lines
11 KiB

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