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.

506 lines
12 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. "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/log"
  25. "github.com/gogits/gogs/modules/setting"
  26. )
  27. var Sanitizer = bluemonday.UGCPolicy()
  28. func BuildSanitizer() {
  29. // Normal markdown-stuff
  30. Sanitizer.AllowAttrs("class").Matching(regexp.MustCompile(`[\p{L}\p{N}\s\-_',:\[\]!\./\\\(\)&]*`)).OnElements("code")
  31. // Checkboxes
  32. Sanitizer.AllowAttrs("type").Matching(regexp.MustCompile(`^checkbox$`)).OnElements("input")
  33. Sanitizer.AllowAttrs("checked", "disabled").OnElements("input")
  34. // Custom URL-Schemes
  35. Sanitizer.AllowURLSchemes(setting.Markdown.CustomURLSchemes...)
  36. }
  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. // HashEmail hashes email address to MD5 string.
  178. // https://en.gravatar.com/site/implement/hash/
  179. func HashEmail(email string) string {
  180. email = strings.ToLower(strings.TrimSpace(email))
  181. h := md5.New()
  182. h.Write([]byte(email))
  183. return hex.EncodeToString(h.Sum(nil))
  184. }
  185. // AvatarLink returns avatar link by given email.
  186. func AvatarLink(email string) string {
  187. if setting.DisableGravatar || setting.OfflineMode {
  188. return setting.AppSubUrl + "/img/avatar_default.jpg"
  189. }
  190. return setting.GravatarSource + HashEmail(email)
  191. }
  192. // Seconds-based time units
  193. const (
  194. Minute = 60
  195. Hour = 60 * Minute
  196. Day = 24 * Hour
  197. Week = 7 * Day
  198. Month = 30 * Day
  199. Year = 12 * Month
  200. )
  201. func computeTimeDiff(diff int64) (int64, string) {
  202. diffStr := ""
  203. switch {
  204. case diff <= 0:
  205. diff = 0
  206. diffStr = "now"
  207. case diff < 2:
  208. diff = 0
  209. diffStr = "1 second"
  210. case diff < 1*Minute:
  211. diffStr = fmt.Sprintf("%d seconds", diff)
  212. diff = 0
  213. case diff < 2*Minute:
  214. diff -= 1 * Minute
  215. diffStr = "1 minute"
  216. case diff < 1*Hour:
  217. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  218. diff -= diff / Minute * Minute
  219. case diff < 2*Hour:
  220. diff -= 1 * Hour
  221. diffStr = "1 hour"
  222. case diff < 1*Day:
  223. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  224. diff -= diff / Hour * Hour
  225. case diff < 2*Day:
  226. diff -= 1 * Day
  227. diffStr = "1 day"
  228. case diff < 1*Week:
  229. diffStr = fmt.Sprintf("%d days", diff/Day)
  230. diff -= diff / Day * Day
  231. case diff < 2*Week:
  232. diff -= 1 * Week
  233. diffStr = "1 week"
  234. case diff < 1*Month:
  235. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  236. diff -= diff / Week * Week
  237. case diff < 2*Month:
  238. diff -= 1 * Month
  239. diffStr = "1 month"
  240. case diff < 1*Year:
  241. diffStr = fmt.Sprintf("%d months", diff/Month)
  242. diff -= diff / Month * Month
  243. case diff < 2*Year:
  244. diff -= 1 * Year
  245. diffStr = "1 year"
  246. default:
  247. diffStr = fmt.Sprintf("%d years", diff/Year)
  248. diff = 0
  249. }
  250. return diff, diffStr
  251. }
  252. // TimeSincePro calculates the time interval and generate full user-friendly string.
  253. func TimeSincePro(then time.Time) string {
  254. now := time.Now()
  255. diff := now.Unix() - then.Unix()
  256. if then.After(now) {
  257. return "future"
  258. }
  259. var timeStr, diffStr string
  260. for {
  261. if diff == 0 {
  262. break
  263. }
  264. diff, diffStr = computeTimeDiff(diff)
  265. timeStr += ", " + diffStr
  266. }
  267. return strings.TrimPrefix(timeStr, ", ")
  268. }
  269. func timeSince(then time.Time, lang string) string {
  270. now := time.Now()
  271. lbl := i18n.Tr(lang, "tool.ago")
  272. diff := now.Unix() - then.Unix()
  273. if then.After(now) {
  274. lbl = i18n.Tr(lang, "tool.from_now")
  275. diff = then.Unix() - now.Unix()
  276. }
  277. switch {
  278. case diff <= 0:
  279. return i18n.Tr(lang, "tool.now")
  280. case diff <= 2:
  281. return i18n.Tr(lang, "tool.1s", lbl)
  282. case diff < 1*Minute:
  283. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  284. case diff < 2*Minute:
  285. return i18n.Tr(lang, "tool.1m", lbl)
  286. case diff < 1*Hour:
  287. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  288. case diff < 2*Hour:
  289. return i18n.Tr(lang, "tool.1h", lbl)
  290. case diff < 1*Day:
  291. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  292. case diff < 2*Day:
  293. return i18n.Tr(lang, "tool.1d", lbl)
  294. case diff < 1*Week:
  295. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  296. case diff < 2*Week:
  297. return i18n.Tr(lang, "tool.1w", lbl)
  298. case diff < 1*Month:
  299. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  300. case diff < 2*Month:
  301. return i18n.Tr(lang, "tool.1mon", lbl)
  302. case diff < 1*Year:
  303. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  304. case diff < 2*Year:
  305. return i18n.Tr(lang, "tool.1y", lbl)
  306. default:
  307. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  308. }
  309. }
  310. func RawTimeSince(t time.Time, lang string) string {
  311. return timeSince(t, lang)
  312. }
  313. // TimeSince calculates the time interval and generate user-friendly string.
  314. func TimeSince(t time.Time, lang string) template.HTML {
  315. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  316. }
  317. const (
  318. Byte = 1
  319. KByte = Byte * 1024
  320. MByte = KByte * 1024
  321. GByte = MByte * 1024
  322. TByte = GByte * 1024
  323. PByte = TByte * 1024
  324. EByte = PByte * 1024
  325. )
  326. var bytesSizeTable = map[string]uint64{
  327. "b": Byte,
  328. "kb": KByte,
  329. "mb": MByte,
  330. "gb": GByte,
  331. "tb": TByte,
  332. "pb": PByte,
  333. "eb": EByte,
  334. }
  335. func logn(n, b float64) float64 {
  336. return math.Log(n) / math.Log(b)
  337. }
  338. func humanateBytes(s uint64, base float64, sizes []string) string {
  339. if s < 10 {
  340. return fmt.Sprintf("%dB", s)
  341. }
  342. e := math.Floor(logn(float64(s), base))
  343. suffix := sizes[int(e)]
  344. val := float64(s) / math.Pow(base, math.Floor(e))
  345. f := "%.0f"
  346. if val < 10 {
  347. f = "%.1f"
  348. }
  349. return fmt.Sprintf(f+"%s", val, suffix)
  350. }
  351. // FileSize calculates the file size and generate user-friendly string.
  352. func FileSize(s int64) string {
  353. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  354. return humanateBytes(uint64(s), 1024, sizes)
  355. }
  356. // Subtract deals with subtraction of all types of number.
  357. func Subtract(left interface{}, right interface{}) interface{} {
  358. var rleft, rright int64
  359. var fleft, fright float64
  360. var isInt bool = true
  361. switch left.(type) {
  362. case int:
  363. rleft = int64(left.(int))
  364. case int8:
  365. rleft = int64(left.(int8))
  366. case int16:
  367. rleft = int64(left.(int16))
  368. case int32:
  369. rleft = int64(left.(int32))
  370. case int64:
  371. rleft = left.(int64)
  372. case float32:
  373. fleft = float64(left.(float32))
  374. isInt = false
  375. case float64:
  376. fleft = left.(float64)
  377. isInt = false
  378. }
  379. switch right.(type) {
  380. case int:
  381. rright = int64(right.(int))
  382. case int8:
  383. rright = int64(right.(int8))
  384. case int16:
  385. rright = int64(right.(int16))
  386. case int32:
  387. rright = int64(right.(int32))
  388. case int64:
  389. rright = right.(int64)
  390. case float32:
  391. fright = float64(left.(float32))
  392. isInt = false
  393. case float64:
  394. fleft = left.(float64)
  395. isInt = false
  396. }
  397. if isInt {
  398. return rleft - rright
  399. } else {
  400. return fleft + float64(rleft) - (fright + float64(rright))
  401. }
  402. }
  403. // EllipsisString returns a truncated short string,
  404. // it appends '...' in the end of the length of string is too large.
  405. func EllipsisString(str string, length int) string {
  406. if len(str) < length {
  407. return str
  408. }
  409. return str[:length-3] + "..."
  410. }
  411. // StringsToInt64s converts a slice of string to a slice of int64.
  412. func StringsToInt64s(strs []string) []int64 {
  413. ints := make([]int64, len(strs))
  414. for i := range strs {
  415. ints[i] = com.StrTo(strs[i]).MustInt64()
  416. }
  417. return ints
  418. }
  419. // Int64sToStrings converts a slice of int64 to a slice of string.
  420. func Int64sToStrings(ints []int64) []string {
  421. strs := make([]string, len(ints))
  422. for i := range ints {
  423. strs[i] = com.ToStr(ints[i])
  424. }
  425. return strs
  426. }
  427. // Int64sToMap converts a slice of int64 to a int64 map.
  428. func Int64sToMap(ints []int64) map[int64]bool {
  429. m := make(map[int64]bool)
  430. for _, i := range ints {
  431. m[i] = true
  432. }
  433. return m
  434. }