utils.go 12 KB

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