utils.go 14 KB

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