tool.go 12 KB

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