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.

501 lines
12 KiB

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