utils.go 12 KB

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