utils.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "database/sql"
  6. "encoding/hex"
  7. "fmt"
  8. "html/template"
  9. "math"
  10. "mime/quotedprintable"
  11. "net/http"
  12. "net/smtp"
  13. "os"
  14. "regexp"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "golang-fave/engine/assets"
  19. "golang-fave/engine/consts"
  20. )
  21. func Trim(str string) string {
  22. return strings.TrimSpace(str)
  23. }
  24. func IsFileExists(filename string) bool {
  25. if _, err := os.Stat(filename); !os.IsNotExist(err) {
  26. if err == nil {
  27. return true
  28. }
  29. }
  30. return false
  31. }
  32. func IsRegularFileExists(filename string) bool {
  33. if st, err := os.Stat(filename); !os.IsNotExist(err) {
  34. if err == nil {
  35. if !st.Mode().IsDir() {
  36. return true
  37. }
  38. }
  39. }
  40. return false
  41. }
  42. func IsDir(filename string) bool {
  43. if st, err := os.Stat(filename); !os.IsNotExist(err) {
  44. if err == nil {
  45. if st.Mode().IsDir() {
  46. return true
  47. }
  48. }
  49. }
  50. return false
  51. }
  52. func IsDirExists(path string) bool {
  53. if IsFileExists(path) && IsDir(path) {
  54. return true
  55. }
  56. return false
  57. }
  58. func IsNumeric(str string) bool {
  59. if _, err := strconv.Atoi(str); err == nil {
  60. return true
  61. }
  62. return false
  63. }
  64. func IsFloat(str string) bool {
  65. if _, err := strconv.ParseFloat(str, 64); err == nil {
  66. return true
  67. }
  68. return false
  69. }
  70. func IsValidMobile(str string) bool {
  71. regexpeChars := regexp.MustCompile(`^\+([0-9]{7,18})$`)
  72. return regexpeChars.MatchString(str)
  73. }
  74. func IsValidEmail(email string) bool {
  75. regexpe := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
  76. return regexpe.MatchString(email)
  77. }
  78. func IsValidAlias(alias string) bool {
  79. // Control panel
  80. regexpeCP := regexp.MustCompile(`^\/cp\/`)
  81. if alias == "/cp" || regexpeCP.MatchString(alias) {
  82. return false
  83. }
  84. // Blog module
  85. regexpeBlog := regexp.MustCompile(`^\/blog\/`)
  86. if alias == "/blog" || regexpeBlog.MatchString(alias) {
  87. return false
  88. }
  89. // Shop module
  90. regexpeShop := regexp.MustCompile(`^\/shop\/`)
  91. if alias == "/shop" || regexpeShop.MatchString(alias) {
  92. return false
  93. }
  94. // API module
  95. regexpeApi := regexp.MustCompile(`^\/api\/`)
  96. if alias == "/api" || regexpeApi.MatchString(alias) {
  97. return false
  98. }
  99. regexpeSlash := regexp.MustCompile(`[\/]{2,}`)
  100. regexpeChars := regexp.MustCompile(`^\/([a-zA-Z0-9\/\-_\.]+)\/?$`)
  101. return (!regexpeSlash.MatchString(alias) && regexpeChars.MatchString(alias)) || alias == "/"
  102. }
  103. func IsValidSingleAlias(alias string) bool {
  104. regexpeChars := regexp.MustCompile(`^([a-zA-Z0-9\-_]{1,})$`)
  105. return regexpeChars.MatchString(alias)
  106. }
  107. func FixPath(path string) string {
  108. newPath := strings.TrimSpace(path)
  109. if len(newPath) <= 0 {
  110. return newPath
  111. }
  112. if newPath[len(newPath)-1] == '/' || newPath[len(newPath)-1] == '\\' {
  113. newPath = newPath[0 : len(newPath)-1]
  114. }
  115. return newPath
  116. }
  117. func ExtractHostPort(host string, https bool) (string, string) {
  118. h := host
  119. p := "80"
  120. if https {
  121. p = "443"
  122. }
  123. i := strings.Index(h, ":")
  124. if i > -1 {
  125. p = h[i+1:]
  126. h = h[0:i]
  127. }
  128. return h, p
  129. }
  130. func GetFileSize(filename string) int64 {
  131. if st, err := os.Stat(filename); !os.IsNotExist(err) {
  132. if err == nil {
  133. if !st.Mode().IsDir() {
  134. return st.Size()
  135. }
  136. }
  137. }
  138. return 0
  139. }
  140. func GetAssetsUrl(filename string) string {
  141. return "/" + filename + "?v=" + consts.ServerVersion
  142. }
  143. func GetTmplSystemData(cpmod, cpsubmod string) consts.TmplSystem {
  144. return consts.TmplSystem{
  145. CpSubModule: cpsubmod,
  146. InfoVersion: consts.ServerVersion,
  147. PathCssBootstrap: GetAssetsUrl(consts.AssetsBootstrapCss),
  148. PathCssCpCodeMirror: GetAssetsUrl(consts.AssetsCpCodeMirrorCss),
  149. PathCssCpStyles: GetAssetsUrl(consts.AssetsCpStylesCss),
  150. PathCssCpWysiwygPell: GetAssetsUrl(consts.AssetsCpWysiwygPellCss),
  151. PathCssLightGallery: GetAssetsUrl(consts.AssetsLightGalleryCss),
  152. PathCssStyles: GetAssetsUrl(consts.AssetsSysStylesCss),
  153. PathIcoFav: GetAssetsUrl(consts.AssetsSysFaveIco),
  154. PathJsBootstrap: GetAssetsUrl(consts.AssetsBootstrapJs),
  155. PathJsCpCodeMirror: GetAssetsUrl(consts.AssetsCpCodeMirrorJs),
  156. PathJsCpScripts: GetAssetsUrl(consts.AssetsCpScriptsJs),
  157. PathJsCpWysiwygPell: GetAssetsUrl(consts.AssetsCpWysiwygPellJs),
  158. PathJsJquery: GetAssetsUrl(consts.AssetsJqueryJs),
  159. PathJsLightGallery: GetAssetsUrl(consts.AssetsLightGalleryJs),
  160. PathJsPopper: GetAssetsUrl(consts.AssetsPopperJs),
  161. PathSvgLogo: GetAssetsUrl(consts.AssetsSysLogoSvg),
  162. PathThemeScripts: "/assets/theme/scripts.js?v=" + consts.ServerVersion,
  163. PathThemeStyles: "/assets/theme/styles.css?v=" + consts.ServerVersion,
  164. CpModule: cpmod,
  165. }
  166. }
  167. func GetTmplError(err error) consts.TmplError {
  168. return consts.TmplError{
  169. ErrorMessage: err.Error(),
  170. }
  171. }
  172. func GetMd5(str string) string {
  173. hasher := md5.New()
  174. hasher.Write([]byte(str))
  175. return hex.EncodeToString(hasher.Sum(nil))
  176. }
  177. func GetCurrentUnixTimestamp() int64 {
  178. return int64(time.Now().Unix())
  179. }
  180. func SystemRenderTemplate(w http.ResponseWriter, c []byte, d interface{}, cpmod, cpsubmod string) {
  181. tmpl, err := template.New("template").Parse(string(c))
  182. if err != nil {
  183. SystemErrorPageEngine(w, err)
  184. return
  185. }
  186. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  187. w.Header().Set("Content-Type", "text/html")
  188. tmpl.Execute(w, consts.TmplData{
  189. System: GetTmplSystemData(cpmod, cpsubmod),
  190. Data: d,
  191. })
  192. }
  193. func SystemErrorPageEngine(w http.ResponseWriter, err error) {
  194. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorEngine)); e == nil {
  195. w.WriteHeader(http.StatusInternalServerError)
  196. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  197. w.Header().Set("Content-Type", "text/html")
  198. tmpl.Execute(w, consts.TmplData{
  199. System: GetTmplSystemData("error", "engine"),
  200. Data: GetTmplError(err),
  201. })
  202. return
  203. }
  204. w.WriteHeader(http.StatusInternalServerError)
  205. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  206. w.Header().Set("Content-Type", "text/html")
  207. w.Write([]byte("<h1>Critical engine error</h1>"))
  208. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  209. }
  210. func SystemErrorPageTemplate(w http.ResponseWriter, err error) {
  211. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorTmpl)); e == nil {
  212. w.WriteHeader(http.StatusInternalServerError)
  213. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  214. w.Header().Set("Content-Type", "text/html")
  215. tmpl.Execute(w, consts.TmplData{
  216. System: GetTmplSystemData("error", "template"),
  217. Data: GetTmplError(err),
  218. })
  219. return
  220. }
  221. w.WriteHeader(http.StatusInternalServerError)
  222. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  223. w.Header().Set("Content-Type", "text/html")
  224. w.Write([]byte("<h1>Critical engine error</h1>"))
  225. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  226. }
  227. func SystemErrorPage404(w http.ResponseWriter) {
  228. tmpl, err := template.New("template").Parse(string(assets.TmplPageError404))
  229. if err != nil {
  230. SystemErrorPageEngine(w, err)
  231. return
  232. }
  233. w.WriteHeader(http.StatusNotFound)
  234. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  235. w.Header().Set("Content-Type", "text/html")
  236. tmpl.Execute(w, consts.TmplData{
  237. System: GetTmplSystemData("error", "404"),
  238. Data: nil,
  239. })
  240. }
  241. func UrlToArray(url string) []string {
  242. url_buff := url
  243. // Remove GET parameters
  244. i := strings.Index(url_buff, "?")
  245. if i > -1 {
  246. url_buff = url_buff[:i]
  247. }
  248. // Cut slashes
  249. if len(url_buff) >= 1 && url_buff[:1] == "/" {
  250. url_buff = url_buff[1:]
  251. }
  252. if len(url_buff) >= 1 && url_buff[len(url_buff)-1:] == "/" {
  253. url_buff = url_buff[:len(url_buff)-1]
  254. }
  255. // Explode
  256. if url_buff == "" {
  257. return []string{}
  258. } else {
  259. return strings.Split(url_buff, "/")
  260. }
  261. }
  262. func IntToStr(num int) string {
  263. return fmt.Sprintf("%d", num)
  264. }
  265. func Int64ToStr(num int64) string {
  266. return fmt.Sprintf("%d", num)
  267. }
  268. func StrToInt(str string) int {
  269. num, err := strconv.Atoi(str)
  270. if err == nil {
  271. return num
  272. }
  273. return 0
  274. }
  275. func Float64ToStr(num float64) string {
  276. return fmt.Sprintf("%.2f", num)
  277. }
  278. func Float64ToStrF(num float64, format string) string {
  279. return fmt.Sprintf(format, num)
  280. }
  281. func StrToFloat64(str string) float64 {
  282. num, err := strconv.ParseFloat(str, 64)
  283. if err == nil {
  284. return num
  285. }
  286. return 0
  287. }
  288. func GenerateAlias(str string) string {
  289. if str == "" {
  290. return ""
  291. }
  292. strc := []rune(str)
  293. lat := []string{"EH", "I", "i", "#", "eh", "A", "B", "V", "G", "D", "E", "JO", "ZH", "Z", "I", "JJ", "K", "L", "M", "N", "O", "P", "R", "S", "T", "U", "F", "KH", "C", "CH", "SH", "SHH", "'", "Y", "", "EH", "YU", "YA", "a", "b", "v", "g", "d", "e", "jo", "zh", "z", "i", "jj", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "kh", "c", "ch", "sh", "shh", "", "y", "", "eh", "yu", "ya", "", "", "-", "-", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "z", "x", "c", "v", "b", "n", "m", ",", ".", "/", "-", "-", ":", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"}
  294. cyr := []string{"Є", "І", "і", "№", "є", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы", "Ь", "Э", "Ю", "Я", "а", "б", "в", "г", "д", "е", "ё", "ж", "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы", "ь", "э", "ю", "я", "«", "»", "—", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "", "", "a", "s", "d", "f", "g", "h", "j", "k", "l", "", "", "z", "x", "c", "v", "b", "n", "m", "", "", "", "(", ")", "", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"}
  295. var alias string = ""
  296. for i := 0; i < len(strc); i++ {
  297. for j := 0; j < len(cyr); j++ {
  298. if string(strc[i]) == cyr[j] {
  299. alias += lat[j]
  300. }
  301. }
  302. }
  303. alias = strings.ToLower(alias)
  304. // Cut repeated chars "-"
  305. if reg, err := regexp.Compile(`[\-]+`); err == nil {
  306. alias = strings.Trim(reg.ReplaceAllString(alias, "-"), "-")
  307. }
  308. alias = "/" + alias + "/"
  309. // Cut repeated chars "/"
  310. if reg, err := regexp.Compile("[/]+"); err == nil {
  311. alias = reg.ReplaceAllString(alias, "/")
  312. }
  313. return alias
  314. }
  315. func GenerateSingleAlias(str string) string {
  316. alias := GenerateAlias(str)
  317. if len(alias) > 1 && alias[0] == '/' {
  318. alias = alias[1:]
  319. }
  320. if len(alias) > 1 && alias[len(alias)-1] == '/' {
  321. alias = alias[:len(alias)-1]
  322. }
  323. return alias
  324. }
  325. func UnixTimestampToMySqlDateTime(sec int64) string {
  326. return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
  327. }
  328. func UnixTimestampToFormat(sec int64, format string) string {
  329. return time.Unix(sec, 0).Format(format)
  330. }
  331. func ExtractGetParams(str string) string {
  332. i := strings.Index(str, "?")
  333. if i == -1 {
  334. return ""
  335. }
  336. return "?" + str[i+1:]
  337. }
  338. func JavaScriptVarValue(str string) string {
  339. return strings.Replace(
  340. strings.Replace(str, `'`, `&rsquo;`, -1),
  341. `"`,
  342. `&rdquo;`,
  343. -1,
  344. )
  345. }
  346. func InArrayInt(slice []int, value int) bool {
  347. for _, item := range slice {
  348. if item == value {
  349. return true
  350. }
  351. }
  352. return false
  353. }
  354. func InArrayString(slice []string, value string) bool {
  355. for _, item := range slice {
  356. if item == value {
  357. return true
  358. }
  359. }
  360. return false
  361. }
  362. func GetPostArrayInt(name string, r *http.Request) []int {
  363. var ids []int
  364. if arr, ok := r.PostForm[name]; ok {
  365. for _, el := range arr {
  366. if IsNumeric(el) {
  367. if !InArrayInt(ids, StrToInt(el)) {
  368. ids = append(ids, StrToInt(el))
  369. }
  370. }
  371. }
  372. }
  373. return ids
  374. }
  375. func GetPostArrayString(name string, r *http.Request) []string {
  376. var ids []string
  377. if arr, ok := r.PostForm[name]; ok {
  378. for _, el := range arr {
  379. if !InArrayString(ids, el) {
  380. ids = append(ids, el)
  381. }
  382. }
  383. }
  384. return ids
  385. }
  386. func ArrayOfIntToArrayOfString(arr []int) []string {
  387. var res []string
  388. for _, el := range arr {
  389. res = append(res, IntToStr(el))
  390. }
  391. return res
  392. }
  393. func ArrayOfStringToArrayOfInt(arr []string) []int {
  394. var res []int
  395. for _, el := range arr {
  396. if IsNumeric(el) {
  397. res = append(res, StrToInt(el))
  398. }
  399. }
  400. return res
  401. }
  402. func TemplateAdditionalFuncs() template.FuncMap {
  403. return template.FuncMap{
  404. "plus": func(a, b int) int {
  405. return a + b
  406. },
  407. "minus": func(a, b int) int {
  408. return a - b
  409. },
  410. "multiply": func(a, b int) int {
  411. return a * b
  412. },
  413. "divide": func(a, b int) int {
  414. return a / b
  415. },
  416. "repeat": func(a string, n int) template.HTML {
  417. out := ""
  418. for i := 1; i <= n; i++ {
  419. out += a
  420. }
  421. return template.HTML(out)
  422. },
  423. }
  424. }
  425. func SqlNullStringToString(arr *[]sql.NullString) *[]string {
  426. values := make([]string, len(*arr))
  427. for key, value := range *arr {
  428. values[key] = value.String
  429. }
  430. return &values
  431. }
  432. func GetImagePlaceholderSrc() string {
  433. return "/" + consts.AssetsSysPlaceholderPng
  434. }
  435. func FormatProductPrice(price float64, format, round int) string {
  436. p := price
  437. if round == 1 {
  438. p = math.Ceil(p)
  439. } else if round == 2 {
  440. p = math.Floor(p)
  441. }
  442. if format == 1 {
  443. return Float64ToStrF(p, "%.1f")
  444. } else if format == 2 {
  445. return Float64ToStrF(p, "%.2f")
  446. } else if format == 3 {
  447. return Float64ToStrF(p, "%.3f")
  448. } else if format == 4 {
  449. return Float64ToStrF(p, "%.4f")
  450. }
  451. return Float64ToStrF(p, "%.0f")
  452. }
  453. func SMTPSend(host, port, user, pass, subject, msg string, receivers []string) error {
  454. header := make(map[string]string)
  455. header["From"] = user
  456. header["To"] = strings.Join(receivers, ", ")
  457. header["Subject"] = subject
  458. header["MIME-Version"] = "1.0"
  459. header["Content-Type"] = fmt.Sprintf("%s; charset=\"utf-8\"", "text/html")
  460. header["Content-Transfer-Encoding"] = "quoted-printable"
  461. header["Content-Disposition"] = "inline"
  462. message := ""
  463. for key, value := range header {
  464. message += fmt.Sprintf("%s: %s\r\n", key, value)
  465. }
  466. var encodedMessage bytes.Buffer
  467. finalMessage := quotedprintable.NewWriter(&encodedMessage)
  468. finalMessage.Write([]byte(msg))
  469. finalMessage.Close()
  470. message += "\r\n" + encodedMessage.String()
  471. return smtp.SendMail(
  472. host+":"+port,
  473. smtp.PlainAuth("", user, pass, host),
  474. user,
  475. receivers,
  476. []byte(message),
  477. )
  478. }
  479. func SafeFilePath(path string) string {
  480. result := path
  481. if reg, err := regexp.Compile(`([/]+\.\.)|(\.\.[/]+)`); err == nil {
  482. result = reg.ReplaceAllString(result, "/")
  483. }
  484. if reg, err := regexp.Compile(`([/]+[\.]+[/]+)`); err == nil {
  485. result = reg.ReplaceAllString(result, "/")
  486. }
  487. if reg, err := regexp.Compile("([/]+)"); err == nil {
  488. result = reg.ReplaceAllString(result, "/")
  489. }
  490. return result
  491. }
  492. func IsValidTemplateFileName(str string) bool {
  493. regexpeChars := regexp.MustCompile(`^[0-9A-Za-z-]+$`)
  494. return regexpeChars.MatchString(str)
  495. }