tool.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. "errors"
  13. "fmt"
  14. "hash"
  15. "html/template"
  16. "math"
  17. "regexp"
  18. "strings"
  19. "time"
  20. "github.com/Unknwon/com"
  21. "github.com/Unknwon/i18n"
  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. func BasicAuthDecode(encoded string) (user string, name string, err error) {
  31. var s []byte
  32. s, err = base64.StdEncoding.DecodeString(encoded)
  33. if err != nil {
  34. return user, name, err
  35. }
  36. a := strings.Split(string(s), ":")
  37. if len(a) == 2 {
  38. user, name = a[0], a[1]
  39. } else {
  40. err = errors.New("decode failed")
  41. }
  42. return user, name, err
  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. } else if setting.Service.EnableCacheAvatar {
  150. return setting.AppSubUrl + "/avatar/" + EncodeMd5(email)
  151. }
  152. return "//1.gravatar.com/avatar/" + EncodeMd5(email)
  153. }
  154. // Seconds-based time units
  155. const (
  156. Minute = 60
  157. Hour = 60 * Minute
  158. Day = 24 * Hour
  159. Week = 7 * Day
  160. Month = 30 * Day
  161. Year = 12 * Month
  162. )
  163. func computeTimeDiff(diff int64) (int64, string) {
  164. diffStr := ""
  165. switch {
  166. case diff <= 0:
  167. diff = 0
  168. diffStr = "now"
  169. case diff < 2:
  170. diff = 0
  171. diffStr = "1 second"
  172. case diff < 1*Minute:
  173. diffStr = fmt.Sprintf("%d seconds", diff)
  174. diff = 0
  175. case diff < 2*Minute:
  176. diff -= 1 * Minute
  177. diffStr = "1 minute"
  178. case diff < 1*Hour:
  179. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  180. diff -= diff / Minute * Minute
  181. case diff < 2*Hour:
  182. diff -= 1 * Hour
  183. diffStr = "1 hour"
  184. case diff < 1*Day:
  185. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  186. diff -= diff / Hour * Hour
  187. case diff < 2*Day:
  188. diff -= 1 * Day
  189. diffStr = "1 day"
  190. case diff < 1*Week:
  191. diffStr = fmt.Sprintf("%d days", diff/Day)
  192. diff -= diff / Day * Day
  193. case diff < 2*Week:
  194. diff -= 1 * Week
  195. diffStr = "1 week"
  196. case diff < 1*Month:
  197. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  198. diff -= diff / Week * Week
  199. case diff < 2*Month:
  200. diff -= 1 * Month
  201. diffStr = "1 month"
  202. case diff < 1*Year:
  203. diffStr = fmt.Sprintf("%d months", diff/Month)
  204. diff -= diff / Month * Month
  205. case diff < 2*Year:
  206. diff -= 1 * Year
  207. diffStr = "1 year"
  208. default:
  209. diffStr = fmt.Sprintf("%d years", diff/Year)
  210. diff = 0
  211. }
  212. return diff, diffStr
  213. }
  214. // TimeSincePro calculates the time interval and generate full user-friendly string.
  215. func TimeSincePro(then time.Time) string {
  216. now := time.Now()
  217. diff := now.Unix() - then.Unix()
  218. if then.After(now) {
  219. return "future"
  220. }
  221. var timeStr, diffStr string
  222. for {
  223. if diff == 0 {
  224. break
  225. }
  226. diff, diffStr = computeTimeDiff(diff)
  227. timeStr += ", " + diffStr
  228. }
  229. return strings.TrimPrefix(timeStr, ", ")
  230. }
  231. func timeSince(then time.Time, lang string) string {
  232. now := time.Now()
  233. lbl := i18n.Tr(lang, "tool.ago")
  234. diff := now.Unix() - then.Unix()
  235. if then.After(now) {
  236. lbl = i18n.Tr(lang, "tool.from_now")
  237. diff = then.Unix() - now.Unix()
  238. }
  239. switch {
  240. case diff <= 0:
  241. return i18n.Tr(lang, "tool.now")
  242. case diff <= 2:
  243. return i18n.Tr(lang, "tool.1s", lbl)
  244. case diff < 1*Minute:
  245. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  246. case diff < 2*Minute:
  247. return i18n.Tr(lang, "tool.1m", lbl)
  248. case diff < 1*Hour:
  249. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  250. case diff < 2*Hour:
  251. return i18n.Tr(lang, "tool.1h", lbl)
  252. case diff < 1*Day:
  253. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  254. case diff < 2*Day:
  255. return i18n.Tr(lang, "tool.1d", lbl)
  256. case diff < 1*Week:
  257. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  258. case diff < 2*Week:
  259. return i18n.Tr(lang, "tool.1w", lbl)
  260. case diff < 1*Month:
  261. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  262. case diff < 2*Month:
  263. return i18n.Tr(lang, "tool.1mon", lbl)
  264. case diff < 1*Year:
  265. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  266. case diff < 2*Year:
  267. return i18n.Tr(lang, "tool.1y", lbl)
  268. default:
  269. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  270. }
  271. }
  272. // TimeSince calculates the time interval and generate user-friendly string.
  273. func TimeSince(t time.Time, lang string) template.HTML {
  274. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  275. }
  276. const (
  277. Byte = 1
  278. KByte = Byte * 1024
  279. MByte = KByte * 1024
  280. GByte = MByte * 1024
  281. TByte = GByte * 1024
  282. PByte = TByte * 1024
  283. EByte = PByte * 1024
  284. )
  285. var bytesSizeTable = map[string]uint64{
  286. "b": Byte,
  287. "kb": KByte,
  288. "mb": MByte,
  289. "gb": GByte,
  290. "tb": TByte,
  291. "pb": PByte,
  292. "eb": EByte,
  293. }
  294. func logn(n, b float64) float64 {
  295. return math.Log(n) / math.Log(b)
  296. }
  297. func humanateBytes(s uint64, base float64, sizes []string) string {
  298. if s < 10 {
  299. return fmt.Sprintf("%dB", s)
  300. }
  301. e := math.Floor(logn(float64(s), base))
  302. suffix := sizes[int(e)]
  303. val := float64(s) / math.Pow(base, math.Floor(e))
  304. f := "%.0f"
  305. if val < 10 {
  306. f = "%.1f"
  307. }
  308. return fmt.Sprintf(f+"%s", val, suffix)
  309. }
  310. // FileSize calculates the file size and generate user-friendly string.
  311. func FileSize(s int64) string {
  312. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  313. return humanateBytes(uint64(s), 1024, sizes)
  314. }
  315. // Subtract deals with subtraction of all types of number.
  316. func Subtract(left interface{}, right interface{}) interface{} {
  317. var rleft, rright int64
  318. var fleft, fright float64
  319. var isInt bool = true
  320. switch left.(type) {
  321. case int:
  322. rleft = int64(left.(int))
  323. case int8:
  324. rleft = int64(left.(int8))
  325. case int16:
  326. rleft = int64(left.(int16))
  327. case int32:
  328. rleft = int64(left.(int32))
  329. case int64:
  330. rleft = left.(int64)
  331. case float32:
  332. fleft = float64(left.(float32))
  333. isInt = false
  334. case float64:
  335. fleft = left.(float64)
  336. isInt = false
  337. }
  338. switch right.(type) {
  339. case int:
  340. rright = int64(right.(int))
  341. case int8:
  342. rright = int64(right.(int8))
  343. case int16:
  344. rright = int64(right.(int16))
  345. case int32:
  346. rright = int64(right.(int32))
  347. case int64:
  348. rright = right.(int64)
  349. case float32:
  350. fright = float64(left.(float32))
  351. isInt = false
  352. case float64:
  353. fleft = left.(float64)
  354. isInt = false
  355. }
  356. if isInt {
  357. return rleft - rright
  358. } else {
  359. return fleft + float64(rleft) - (fright + float64(rright))
  360. }
  361. }
  362. // DateFormat pattern rules.
  363. var datePatterns = []string{
  364. // year
  365. "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  366. "y", "06", //A two digit representation of a year Examples: 99 or 03
  367. // month
  368. "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
  369. "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
  370. "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
  371. "F", "January", // A full textual representation of a month, such as January or March January through December
  372. // day
  373. "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
  374. "j", "2", // Day of the month without leading zeros 1 to 31
  375. // week
  376. "D", "Mon", // A textual representation of a day, three letters Mon through Sun
  377. "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
  378. // time
  379. "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
  380. "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
  381. "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
  382. "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
  383. "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
  384. "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
  385. "i", "04", // Minutes with leading zeros 00 to 59
  386. "s", "05", // Seconds, with leading zeros 00 through 59
  387. // time zone
  388. "T", "MST",
  389. "P", "-07:00",
  390. "O", "-0700",
  391. // RFC 2822
  392. "r", time.RFC1123Z,
  393. }
  394. // Parse Date use PHP time format.
  395. func DateParse(dateString, format string) (time.Time, error) {
  396. replacer := strings.NewReplacer(datePatterns...)
  397. format = replacer.Replace(format)
  398. return time.ParseInLocation(format, dateString, time.Local)
  399. }
  400. // Date takes a PHP like date func to Go's time format.
  401. func DateFormat(t time.Time, format string) string {
  402. replacer := strings.NewReplacer(datePatterns...)
  403. format = replacer.Replace(format)
  404. return t.Format(format)
  405. }
  406. type xssFilter struct {
  407. reg *regexp.Regexp
  408. repl []byte
  409. }
  410. var (
  411. whiteSpace = []byte(" ")
  412. xssFilters = []xssFilter{
  413. {regexp.MustCompile(`\ [ONon]\w*=["]*`), whiteSpace},
  414. {regexp.MustCompile(`<[SCRIPTscript]{6}`), whiteSpace},
  415. {regexp.MustCompile(`=[` + "`" + `'"]*[JAVASCRIPTjavascript \t\0&#x0D;]*:`), whiteSpace},
  416. }
  417. )
  418. // XSS goes through all the XSS filters to make user input content as safe as possible.
  419. func XSS(in []byte) []byte {
  420. for _, filter := range xssFilters {
  421. in = filter.reg.ReplaceAll(in, filter.repl)
  422. }
  423. return in
  424. }
  425. func XSSString(in string) string {
  426. return string(XSS([]byte(in)))
  427. }