utils.go 14 KB

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