utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. "unicode/utf16"
  19. "golang-fave/assets"
  20. "golang-fave/consts"
  21. )
  22. func IsFileExists(filename string) bool {
  23. if _, err := os.Stat(filename); !os.IsNotExist(err) {
  24. if err == nil {
  25. return true
  26. }
  27. }
  28. return false
  29. }
  30. func IsDir(filename string) bool {
  31. if st, err := os.Stat(filename); !os.IsNotExist(err) {
  32. if err == nil {
  33. if st.Mode().IsDir() {
  34. return true
  35. }
  36. }
  37. }
  38. return false
  39. }
  40. func IsDirExists(path string) bool {
  41. if IsFileExists(path) && IsDir(path) {
  42. return true
  43. }
  44. return false
  45. }
  46. func IsNumeric(str string) bool {
  47. if _, err := strconv.Atoi(str); err == nil {
  48. return true
  49. }
  50. return false
  51. }
  52. func IsFloat(str string) bool {
  53. if _, err := strconv.ParseFloat(str, 64); err == nil {
  54. return true
  55. }
  56. return false
  57. }
  58. func IsValidMobile(str string) bool {
  59. regexpeChars := regexp.MustCompile(`^\+([0-9]{7,18})$`)
  60. return regexpeChars.MatchString(str)
  61. }
  62. func IsValidEmail(email string) bool {
  63. regexpe := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
  64. return regexpe.MatchString(email)
  65. }
  66. func IsValidAlias(alias string) bool {
  67. // Control panel
  68. regexpeCP := regexp.MustCompile(`^\/cp\/`)
  69. if alias == "/cp" || regexpeCP.MatchString(alias) {
  70. return false
  71. }
  72. // Blog module
  73. regexpeBlog := regexp.MustCompile(`^\/blog\/`)
  74. if alias == "/blog" || regexpeBlog.MatchString(alias) {
  75. return false
  76. }
  77. // Shop module
  78. regexpeShop := regexp.MustCompile(`^\/shop\/`)
  79. if alias == "/shop" || regexpeShop.MatchString(alias) {
  80. return false
  81. }
  82. // API module
  83. regexpeApi := regexp.MustCompile(`^\/api\/`)
  84. if alias == "/api" || regexpeApi.MatchString(alias) {
  85. return false
  86. }
  87. regexpeSlash := regexp.MustCompile(`[\/]{2,}`)
  88. regexpeChars := regexp.MustCompile(`^\/([a-zA-Z0-9\/\-_\.]+)\/?$`)
  89. return (!regexpeSlash.MatchString(alias) && regexpeChars.MatchString(alias)) || alias == "/"
  90. }
  91. func IsValidSingleAlias(alias string) bool {
  92. regexpeChars := regexp.MustCompile(`^([a-zA-Z0-9\-_]{1,})$`)
  93. return regexpeChars.MatchString(alias)
  94. }
  95. func FixPath(path string) string {
  96. newPath := strings.TrimSpace(path)
  97. if len(newPath) <= 0 {
  98. return newPath
  99. }
  100. if newPath[len(newPath)-1] == '/' || newPath[len(newPath)-1] == '\\' {
  101. newPath = newPath[0 : len(newPath)-1]
  102. }
  103. return newPath
  104. }
  105. func ExtractHostPort(host string, https bool) (string, string) {
  106. h := host
  107. p := "80"
  108. if https {
  109. p = "443"
  110. }
  111. i := strings.Index(h, ":")
  112. if i > -1 {
  113. p = h[i+1:]
  114. h = h[0:i]
  115. }
  116. return h, p
  117. }
  118. func GetAssetsUrl(filename string) string {
  119. return "/" + filename + "?v=" + consts.ServerVersion
  120. }
  121. func GetTmplSystemData(cpmod, cpsubmod string) consts.TmplSystem {
  122. return consts.TmplSystem{
  123. CpSubModule: cpsubmod,
  124. InfoVersion: consts.ServerVersion,
  125. PathCssBootstrap: GetAssetsUrl(consts.AssetsBootstrapCss),
  126. PathCssCpCodeMirror: GetAssetsUrl(consts.AssetsCpCodeMirrorCss),
  127. PathCssCpStyles: GetAssetsUrl(consts.AssetsCpStylesCss),
  128. PathCssCpWysiwygPell: GetAssetsUrl(consts.AssetsCpWysiwygPellCss),
  129. PathCssLightGallery: GetAssetsUrl(consts.AssetsLightGalleryCss),
  130. PathCssStyles: GetAssetsUrl(consts.AssetsSysStylesCss),
  131. PathIcoFav: GetAssetsUrl(consts.AssetsSysFaveIco),
  132. PathJsBootstrap: GetAssetsUrl(consts.AssetsBootstrapJs),
  133. PathJsCpCodeMirror: GetAssetsUrl(consts.AssetsCpCodeMirrorJs),
  134. PathJsCpScripts: GetAssetsUrl(consts.AssetsCpScriptsJs),
  135. PathJsCpWysiwygPell: GetAssetsUrl(consts.AssetsCpWysiwygPellJs),
  136. PathJsJquery: GetAssetsUrl(consts.AssetsJqueryJs),
  137. PathJsLightGallery: GetAssetsUrl(consts.AssetsLightGalleryJs),
  138. PathJsPopper: GetAssetsUrl(consts.AssetsPopperJs),
  139. PathSvgLogo: GetAssetsUrl(consts.AssetsSysLogoSvg),
  140. PathThemeScripts: "/assets/theme/scripts.js?v=" + consts.ServerVersion,
  141. PathThemeStyles: "/assets/theme/styles.css?v=" + consts.ServerVersion,
  142. CpModule: cpmod,
  143. }
  144. }
  145. func GetTmplError(err error) consts.TmplError {
  146. return consts.TmplError{
  147. ErrorMessage: err.Error(),
  148. }
  149. }
  150. func GetMd5(str string) string {
  151. hasher := md5.New()
  152. hasher.Write([]byte(str))
  153. return hex.EncodeToString(hasher.Sum(nil))
  154. }
  155. func GetCurrentUnixTimestamp() int64 {
  156. return int64(time.Now().Unix())
  157. }
  158. func SystemRenderTemplate(w http.ResponseWriter, c []byte, d interface{}, cpmod, cpsubmod string) {
  159. tmpl, err := template.New("template").Parse(string(c))
  160. if err != nil {
  161. SystemErrorPageEngine(w, err)
  162. return
  163. }
  164. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  165. w.Header().Set("Content-Type", "text/html")
  166. tmpl.Execute(w, consts.TmplData{
  167. System: GetTmplSystemData(cpmod, cpsubmod),
  168. Data: d,
  169. })
  170. }
  171. func SystemErrorPageEngine(w http.ResponseWriter, err error) {
  172. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorEngine)); e == nil {
  173. w.WriteHeader(http.StatusInternalServerError)
  174. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  175. w.Header().Set("Content-Type", "text/html")
  176. tmpl.Execute(w, consts.TmplData{
  177. System: GetTmplSystemData("error", "engine"),
  178. Data: GetTmplError(err),
  179. })
  180. return
  181. }
  182. w.WriteHeader(http.StatusInternalServerError)
  183. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  184. w.Header().Set("Content-Type", "text/html")
  185. w.Write([]byte("<h1>Critical engine error</h1>"))
  186. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  187. }
  188. func SystemErrorPageTemplate(w http.ResponseWriter, err error) {
  189. if tmpl, e := template.New("template").Parse(string(assets.TmplPageErrorTmpl)); e == nil {
  190. w.WriteHeader(http.StatusInternalServerError)
  191. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  192. w.Header().Set("Content-Type", "text/html")
  193. tmpl.Execute(w, consts.TmplData{
  194. System: GetTmplSystemData("error", "template"),
  195. Data: GetTmplError(err),
  196. })
  197. return
  198. }
  199. w.WriteHeader(http.StatusInternalServerError)
  200. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  201. w.Header().Set("Content-Type", "text/html")
  202. w.Write([]byte("<h1>Critical engine error</h1>"))
  203. w.Write([]byte("<h2>" + err.Error() + "</h2>"))
  204. }
  205. func SystemErrorPage404(w http.ResponseWriter) {
  206. tmpl, err := template.New("template").Parse(string(assets.TmplPageError404))
  207. if err != nil {
  208. SystemErrorPageEngine(w, err)
  209. return
  210. }
  211. w.WriteHeader(http.StatusNotFound)
  212. w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  213. w.Header().Set("Content-Type", "text/html")
  214. tmpl.Execute(w, consts.TmplData{
  215. System: GetTmplSystemData("error", "404"),
  216. Data: nil,
  217. })
  218. }
  219. func UrlToArray(url string) []string {
  220. url_buff := url
  221. // Remove GET parameters
  222. i := strings.Index(url_buff, "?")
  223. if i > -1 {
  224. url_buff = url_buff[:i]
  225. }
  226. // Cut slashes
  227. if len(url_buff) >= 1 && url_buff[:1] == "/" {
  228. url_buff = url_buff[1:]
  229. }
  230. if len(url_buff) >= 1 && url_buff[len(url_buff)-1:] == "/" {
  231. url_buff = url_buff[:len(url_buff)-1]
  232. }
  233. // Explode
  234. if url_buff == "" {
  235. return []string{}
  236. } else {
  237. return strings.Split(url_buff, "/")
  238. }
  239. }
  240. func IntToStr(num int) string {
  241. return fmt.Sprintf("%d", num)
  242. }
  243. func Int64ToStr(num int64) string {
  244. return fmt.Sprintf("%d", num)
  245. }
  246. func StrToInt(str string) int {
  247. num, err := strconv.Atoi(str)
  248. if err == nil {
  249. return num
  250. }
  251. return 0
  252. }
  253. func Float64ToStr(num float64) string {
  254. return fmt.Sprintf("%.2f", num)
  255. }
  256. func Float64ToStrF(num float64, format string) string {
  257. return fmt.Sprintf(format, num)
  258. }
  259. func StrToFloat64(str string) float64 {
  260. num, err := strconv.ParseFloat(str, 64)
  261. if err == nil {
  262. return num
  263. }
  264. return 0
  265. }
  266. func GenerateAlias(str string) string {
  267. if str == "" {
  268. return ""
  269. }
  270. strc := utf16.Encode([]rune(str))
  271. 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"}
  272. 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"}
  273. var alias string = ""
  274. for i := 0; i < len(strc); i++ {
  275. for j := 0; j < len(cyr); j++ {
  276. if string(strc[i]) == cyr[j] {
  277. alias += lat[j]
  278. }
  279. }
  280. }
  281. alias = strings.ToLower(alias)
  282. // Cut repeated chars "-"
  283. if reg, err := regexp.Compile("[\\-]+"); err == nil {
  284. alias = strings.Trim(reg.ReplaceAllString(alias, "-"), "-")
  285. }
  286. alias = "/" + alias + "/"
  287. // Cut repeated chars "/"
  288. if reg, err := regexp.Compile("[/]+"); err == nil {
  289. alias = reg.ReplaceAllString(alias, "/")
  290. }
  291. return alias
  292. }
  293. func GenerateSingleAlias(str string) string {
  294. alias := GenerateAlias(str)
  295. if len(alias) > 1 && alias[0] == '/' {
  296. alias = alias[1:]
  297. }
  298. if len(alias) > 1 && alias[len(alias)-1] == '/' {
  299. alias = alias[:len(alias)-1]
  300. }
  301. return alias
  302. }
  303. func UnixTimestampToMySqlDateTime(sec int64) string {
  304. return time.Unix(sec, 0).Format("2006-01-02 15:04:05")
  305. }
  306. func UnixTimestampToFormat(sec int64, format string) string {
  307. return time.Unix(sec, 0).Format(format)
  308. }
  309. func ExtractGetParams(str string) string {
  310. i := strings.Index(str, "?")
  311. if i == -1 {
  312. return ""
  313. }
  314. return "?" + str[i+1:]
  315. }
  316. func JavaScriptVarValue(str string) string {
  317. return strings.Replace(
  318. strings.Replace(str, `'`, `&rsquo;`, -1),
  319. `"`,
  320. `&rdquo;`,
  321. -1,
  322. )
  323. }
  324. func InArrayInt(slice []int, value int) bool {
  325. for _, item := range slice {
  326. if item == value {
  327. return true
  328. }
  329. }
  330. return false
  331. }
  332. func InArrayString(slice []string, value string) bool {
  333. for _, item := range slice {
  334. if item == value {
  335. return true
  336. }
  337. }
  338. return false
  339. }
  340. func GetPostArrayInt(name string, r *http.Request) []int {
  341. var ids []int
  342. if arr, ok := r.PostForm[name]; ok {
  343. for _, el := range arr {
  344. if IsNumeric(el) {
  345. if !InArrayInt(ids, StrToInt(el)) {
  346. ids = append(ids, StrToInt(el))
  347. }
  348. }
  349. }
  350. }
  351. return ids
  352. }
  353. func GetPostArrayString(name string, r *http.Request) []string {
  354. var ids []string
  355. if arr, ok := r.PostForm[name]; ok {
  356. for _, el := range arr {
  357. if !InArrayString(ids, el) {
  358. ids = append(ids, el)
  359. }
  360. }
  361. }
  362. return ids
  363. }
  364. func ArrayOfIntToArrayOfString(arr []int) []string {
  365. var res []string
  366. for _, el := range arr {
  367. res = append(res, IntToStr(el))
  368. }
  369. return res
  370. }
  371. func ArrayOfStringToArrayOfInt(arr []string) []int {
  372. var res []int
  373. for _, el := range arr {
  374. if IsNumeric(el) {
  375. res = append(res, StrToInt(el))
  376. }
  377. }
  378. return res
  379. }
  380. func TemplateAdditionalFuncs() template.FuncMap {
  381. return template.FuncMap{
  382. "plus": func(a, b int) int {
  383. return a + b
  384. },
  385. "minus": func(a, b int) int {
  386. return a - b
  387. },
  388. "multiply": func(a, b int) int {
  389. return a * b
  390. },
  391. "divide": func(a, b int) int {
  392. return a / b
  393. },
  394. "repeat": func(a string, n int) template.HTML {
  395. out := ""
  396. for i := 1; i <= n; i++ {
  397. out += a
  398. }
  399. return template.HTML(out)
  400. },
  401. }
  402. }
  403. func SqlNullStringToString(arr *[]sql.NullString) *[]string {
  404. values := make([]string, len(*arr))
  405. for key, value := range *arr {
  406. values[key] = value.String
  407. }
  408. return &values
  409. }
  410. func GetImagePlaceholderSrc() string {
  411. return "/" + consts.AssetsSysPlaceholderPng
  412. }
  413. func FormatProductPrice(price float64, format, round int) string {
  414. p := price
  415. if round == 1 {
  416. p = math.Ceil(p)
  417. } else if round == 2 {
  418. p = math.Floor(p)
  419. }
  420. if format == 1 {
  421. return Float64ToStrF(p, "%.1f")
  422. } else if format == 2 {
  423. return Float64ToStrF(p, "%.2f")
  424. } else if format == 3 {
  425. return Float64ToStrF(p, "%.3f")
  426. } else if format == 4 {
  427. return Float64ToStrF(p, "%.4f")
  428. }
  429. return Float64ToStrF(p, "%.0f")
  430. }
  431. func SMTPSend(host, port, user, pass, subject, msg string, receivers []string) error {
  432. header := make(map[string]string)
  433. header["From"] = user
  434. header["To"] = strings.Join(receivers, ", ")
  435. header["Subject"] = subject
  436. header["MIME-Version"] = "1.0"
  437. header["Content-Type"] = fmt.Sprintf("%s; charset=\"utf-8\"", "text/html")
  438. header["Content-Transfer-Encoding"] = "quoted-printable"
  439. header["Content-Disposition"] = "inline"
  440. message := ""
  441. for key, value := range header {
  442. message += fmt.Sprintf("%s: %s\r\n", key, value)
  443. }
  444. var encodedMessage bytes.Buffer
  445. finalMessage := quotedprintable.NewWriter(&encodedMessage)
  446. finalMessage.Write([]byte(msg))
  447. finalMessage.Close()
  448. message += "\r\n" + encodedMessage.String()
  449. return smtp.SendMail(
  450. host+":"+port,
  451. smtp.PlainAuth("", user, pass, host),
  452. user,
  453. receivers,
  454. []byte(message),
  455. )
  456. }