A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

241 lines
6.7 KiB

  1. /*
  2. * Copyright © 2018-2021 Musing Studio LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "errors"
  13. "html/template"
  14. "io"
  15. "os"
  16. "net/http"
  17. "path/filepath"
  18. "strings"
  19. "github.com/dustin/go-humanize"
  20. "github.com/writeas/web-core/l10n"
  21. "github.com/writeas/web-core/log"
  22. "github.com/writefreely/writefreely/config"
  23. )
  24. var (
  25. templates = map[string]*template.Template{}
  26. pages = map[string]*template.Template{}
  27. userPages = map[string]*template.Template{}
  28. funcMap = template.FuncMap{
  29. "largeNumFmt": largeNumFmt,
  30. "pluralize": pluralize,
  31. "isRTL": isRTL,
  32. "isLTR": isLTR,
  33. "localstr": localStr,
  34. "localhtml": localHTML,
  35. "tolower": strings.ToLower,
  36. "title": strings.Title,
  37. "hasPrefix": strings.HasPrefix,
  38. "hasSuffix": strings.HasSuffix,
  39. "dict": dict,
  40. }
  41. )
  42. const (
  43. templatesDir = "templates"
  44. pagesDir = "pages"
  45. )
  46. func showUserPage(w http.ResponseWriter, name string, obj interface{}) {
  47. if obj == nil {
  48. log.Error("showUserPage: data is nil!")
  49. return
  50. }
  51. if err := userPages[filepath.Join("user", name+".tmpl")].ExecuteTemplate(w, name, obj); err != nil {
  52. log.Error("Error parsing %s: %v", name, err)
  53. }
  54. }
  55. func initTemplate(parentDir, name string) {
  56. if debugging {
  57. log.Info(" " + filepath.Join(parentDir, templatesDir, name+".tmpl"))
  58. }
  59. files := []string{
  60. filepath.Join(parentDir, templatesDir, name+".tmpl"),
  61. filepath.Join(parentDir, templatesDir, "include", "footer.tmpl"),
  62. filepath.Join(parentDir, templatesDir, "base.tmpl"),
  63. filepath.Join(parentDir, templatesDir, "user", "include", "silenced.tmpl"),
  64. }
  65. if name == "collection" || name == "collection-tags" || name == "chorus-collection" || name == "read" {
  66. // These pages list out collection posts, so we also parse templatesDir + "include/posts.tmpl"
  67. files = append(files, filepath.Join(parentDir, templatesDir, "include", "posts.tmpl"))
  68. }
  69. if name == "chorus-collection" || name == "chorus-collection-post" {
  70. files = append(files, filepath.Join(parentDir, templatesDir, "user", "include", "header.tmpl"))
  71. }
  72. if name == "collection" || name == "collection-tags" || name == "collection-post" || name == "post" || name == "chorus-collection" || name == "chorus-collection-post" {
  73. files = append(files, filepath.Join(parentDir, templatesDir, "include", "post-render.tmpl"))
  74. }
  75. templates[name] = template.Must(template.New("").Funcs(funcMap).ParseFiles(files...))
  76. }
  77. func initPage(parentDir, path, key string) {
  78. if debugging {
  79. log.Info(" [%s] %s", key, path)
  80. }
  81. files := []string{
  82. path,
  83. filepath.Join(parentDir, templatesDir, "include", "footer.tmpl"),
  84. filepath.Join(parentDir, templatesDir, "base.tmpl"),
  85. filepath.Join(parentDir, templatesDir, "user", "include", "silenced.tmpl"),
  86. }
  87. if key == "login.tmpl" || key == "landing.tmpl" || key == "signup.tmpl" {
  88. files = append(files, filepath.Join(parentDir, templatesDir, "include", "oauth.tmpl"))
  89. }
  90. pages[key] = template.Must(template.New("").Funcs(funcMap).ParseFiles(files...))
  91. }
  92. func initUserPage(parentDir, path, key string) {
  93. if debugging {
  94. log.Info(" [%s] %s", key, path)
  95. }
  96. userPages[key] = template.Must(template.New(key).Funcs(funcMap).ParseFiles(
  97. path,
  98. filepath.Join(parentDir, templatesDir, "user", "include", "header.tmpl"),
  99. filepath.Join(parentDir, templatesDir, "user", "include", "footer.tmpl"),
  100. filepath.Join(parentDir, templatesDir, "user", "include", "silenced.tmpl"),
  101. filepath.Join(parentDir, templatesDir, "user", "include", "nav.tmpl"),
  102. ))
  103. }
  104. // InitTemplates loads all template files from the configured parent dir.
  105. func InitTemplates(cfg *config.Config) error {
  106. log.Info("Loading templates...")
  107. tmplFiles, err := os.ReadDir(filepath.Join(cfg.Server.TemplatesParentDir, templatesDir))
  108. if err != nil {
  109. return err
  110. }
  111. for _, f := range tmplFiles {
  112. if !f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
  113. parts := strings.Split(f.Name(), ".")
  114. key := parts[0]
  115. initTemplate(cfg.Server.TemplatesParentDir, key)
  116. }
  117. }
  118. log.Info("Loading pages...")
  119. // Initialize all static pages that use the base template
  120. err = filepath.Walk(filepath.Join(cfg.Server.PagesParentDir, pagesDir), func(path string, i os.FileInfo, err error) error {
  121. if err != nil {
  122. return err
  123. }
  124. if !i.IsDir() && !strings.HasPrefix(i.Name(), ".") {
  125. key := i.Name()
  126. initPage(cfg.Server.PagesParentDir, path, key)
  127. }
  128. return nil
  129. })
  130. if err != nil {
  131. return err
  132. }
  133. log.Info("Loading user pages...")
  134. // Initialize all user pages that use base templates
  135. err = filepath.Walk(filepath.Join(cfg.Server.TemplatesParentDir, templatesDir, "user"), func(path string, f os.FileInfo, err error) error {
  136. if err != nil {
  137. return err
  138. }
  139. if !f.IsDir() && !strings.HasPrefix(f.Name(), ".") {
  140. corePath := path
  141. if cfg.Server.TemplatesParentDir != "" {
  142. corePath = corePath[len(cfg.Server.TemplatesParentDir)+1:]
  143. }
  144. parts := strings.Split(corePath, string(filepath.Separator))
  145. key := f.Name()
  146. if len(parts) > 2 {
  147. key = filepath.Join(parts[1], f.Name())
  148. }
  149. initUserPage(cfg.Server.TemplatesParentDir, path, key)
  150. }
  151. return nil
  152. })
  153. if err != nil {
  154. return err
  155. }
  156. return nil
  157. }
  158. // renderPage retrieves the given template and renders it to the given io.Writer.
  159. // If something goes wrong, the error is logged and returned.
  160. func renderPage(w io.Writer, tmpl string, data interface{}) error {
  161. err := pages[tmpl].ExecuteTemplate(w, "base", data)
  162. if err != nil {
  163. log.Error("%v", err)
  164. }
  165. return err
  166. }
  167. func largeNumFmt(n int64) string {
  168. return humanize.Comma(n)
  169. }
  170. func pluralize(singular, plural string, n int64) string {
  171. if n == 1 {
  172. return singular
  173. }
  174. return plural
  175. }
  176. func isRTL(d string) bool {
  177. return d == "rtl"
  178. }
  179. func isLTR(d string) bool {
  180. return d == "ltr" || d == "auto"
  181. }
  182. func localStr(term, lang string) string {
  183. s := l10n.Strings(lang)[term]
  184. if s == "" {
  185. s = l10n.Strings("")[term]
  186. }
  187. return s
  188. }
  189. func localHTML(term, lang string) template.HTML {
  190. s := l10n.Strings(lang)[term]
  191. if s == "" {
  192. s = l10n.Strings("")[term]
  193. }
  194. s = strings.Replace(s, "write.as", "<a href=\"https://writefreely.org\">writefreely</a>", 1)
  195. return template.HTML(s)
  196. }
  197. // from: https://stackoverflow.com/a/18276968/1549194
  198. func dict(values ...interface{}) (map[string]interface{}, error) {
  199. if len(values)%2 != 0 {
  200. return nil, errors.New("dict: invalid number of parameters")
  201. }
  202. dict := make(map[string]interface{}, len(values)/2)
  203. for i := 0; i < len(values); i += 2 {
  204. key, ok := values[i].(string)
  205. if !ok {
  206. return nil, errors.New("dict: keys must be strings")
  207. }
  208. dict[key] = values[i+1]
  209. }
  210. return dict, nil
  211. }