Files
summercms/modules/cabana/mail_admin.go
Jakub Zych 3a725469c6 fix(postcard,cabana): unsafe site names never stop a send and are refused at save
- postcard.UnsafeText: a text a layout prints is unsafe when, escaped,
  it fails the rendered-HTML checks or holds a script or data URL at a
  scheme boundary ("Big Data: Summit" is safe)
- siteNameFrom/layoutSiteName: an unsafe Branding name falls back to the
  mail.from display name, an unsafe one of those gives no name; one
  rate-limited warning per source (site_name:branding, site_name:mail.from),
  never the value; file version, override, fallback and editor alike
- the Branding preview of an unsafe draft name renders without it
- MailBrandSetting.BeforeValidate: 422 on site_name with
  backend::lang.mail.brand.site_name_unsafe (en/pl)
- settings Put localizes a BeforeValidate refusal's phrase keys, as a
  controller save does
- TestMailSafetySmoke/unsafe_site_name, TestMailBrandSiteName/unsafe_name_refused
2026-11-14 15:20:29 +01:00

2037 lines
69 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cabana
import (
"context"
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/postcard"
"git.golem15.com/golem15/summercms/modules/towel"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// mailLang prefixes the phrase keys of the mail screens.
const mailLang = "backend::lang.mail."
// mailScreens is the state the mail screens share: the postcard editor the
// application's Mailer exposes, and whether this process has synced the
// mail index rows (postcard.SyncIndex) yet.
type mailScreens struct {
screens *backendScreens
editor *postcard.Editor
syncMu sync.Mutex
synced atomic.Bool
// syncedLocales is the mail locale set of the last successful sync
// (mailLocaleKey); a different set syncs again. Guarded by syncMu.
syncedLocales string
}
// mailPermissions are the two mail codes, with no role grants (D-03).
func mailPermissions() []pact.Permission {
return []pact.Permission{
{Code: PermissionManageMailTemplates, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_mail_templates"},
{Code: PermissionManageMailLayouts, Tab: "backend::lang.permissions.tab_system", Label: "backend::lang.permissions.manage_mail_layouts"},
}
}
func (m *mailScreens) controllers() []pact.AdminController {
return []pact.AdminController{
mailTemplatesAdmin{mail: m},
mailLayoutsAdmin{mail: m},
mailPartialsAdmin{mail: m},
mailImagesAdmin{mail: m},
}
}
// settings are the Settings → Mail entries.
func (m *mailScreens) settings() []pact.SettingsItem {
return []pact.SettingsItem{
{
Code: "mail_templates",
Label: mailLang + "template.menu_label",
Description: mailLang + "template.menu_description",
Category: mailCategory,
Icon: "mail",
Order: 200,
Permissions: []string{PermissionManageMailTemplates},
Controller: MailTemplatesControllerID,
},
{
Code: "mail_layouts",
Label: mailLang + "layout.menu_label",
Description: mailLang + "layout.menu_description",
Category: mailCategory,
Icon: "layout-grid",
Order: 210,
Permissions: []string{PermissionManageMailLayouts},
Controller: MailLayoutsControllerID,
},
{
Code: "mail_partials",
Label: mailLang + "partial.menu_label",
Description: mailLang + "partial.menu_description",
Category: mailCategory,
Icon: "puzzle",
Order: 220,
Permissions: []string{PermissionManageMailLayouts},
Controller: MailPartialsControllerID,
},
{
Code: "mail_brand",
Label: mailLang + "brand.menu_label",
Description: mailLang + "brand.menu_description",
Category: mailCategory,
Icon: "palette",
Order: 230,
Permissions: []string{PermissionManageMailLayouts},
Form: "models/mailbrandsetting/fields.yaml",
NewModel: func() any { return &MailBrandSetting{} },
},
{
Code: "mail_images",
Label: mailLang + "images.menu_label",
Description: mailLang + "images.menu_description",
Category: mailCategory,
Icon: "image",
Order: 240,
Permissions: []string{PermissionManageMailLayouts},
Controller: MailImagesControllerID,
},
}
}
// mailCategory is the Settings category of the mail screens.
const mailCategory = "backend::lang.settings.category_mail"
// application is the activating app, or nil.
func (m *mailScreens) application() *backpack.App {
if m == nil {
return nil
}
return m.screens.application()
}
// catalog is the Mailer's file catalog.
func (m *mailScreens) catalog() *postcard.Catalog {
return m.editor.Catalog()
}
// db is the application pool, or nil without one.
func (m *mailScreens) db() *gorm.DB {
app := m.application()
if app == nil {
return nil
}
gdb, ok := app.Lookup[*gorm.DB]()
if !ok {
return nil
}
return gdb
}
// requestDB is the write transaction on ctx, else the application pool.
func (m *mailScreens) requestDB(ctx context.Context) *gorm.DB {
if tx, ok := TxFromContext(ctx); ok {
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx)
}
if gdb := m.db(); gdb != nil {
return gdb.Session(&gorm.Session{NewDB: true}).WithContext(ctx)
}
return nil
}
// translator is the application's translator, or nil.
func (m *mailScreens) translator() *phrasebook.Translator {
app := m.application()
if app == nil {
return nil
}
tr, _ := app.Lookup[*phrasebook.Translator]()
return tr
}
// mailLocales are the application's mail locales and its default locale:
// the locales the translator's catalog holds plus, when a TranslationWriter
// is published and answers, its enabled locales. The default is the
// writer's default locale, else the translator's locale. locales is sorted
// and includes the default. db is the handle the writer reads with; nil
// leaves the writer out.
func (m *mailScreens) mailLocales(ctx context.Context, db *gorm.DB) (def string, locales []string) {
tr := m.translator()
def = tr.Locale()
seen := map[string]bool{}
add := func(codes ...string) {
for _, code := range codes {
if code = strings.TrimSpace(code); code != "" && !seen[code] {
seen[code] = true
locales = append(locales, code)
}
}
}
add(tr.Locales("")...)
if app := m.application(); app != nil && db != nil {
if w, ok := app.Lookup[TranslationWriter](); ok && w != nil {
if codes, err := w.EnabledLocales(ctx, db); err == nil {
add(codes...)
} else {
moduleLog.WarnContext(ctx, "cabana: mail locales: enabled locales", "error", err)
}
if code, err := w.DefaultLocale(ctx, db); err == nil && strings.TrimSpace(code) != "" {
def = strings.TrimSpace(code)
}
}
}
add(def)
sort.Strings(locales)
return def, locales
}
// mailLocaleKey identifies a mail locale set, to tell whether the index was
// synced with the current one.
func mailLocaleKey(def string, locales []string) string {
return def + "|" + strings.Join(locales, ",")
}
// sync writes the index rows of every file template, layout and partial
// (postcard.SyncIndex), then the rows of the locales a template ships no
// file for (postcard.EnsureLocaleRows), and remembers the locale set it
// succeeded with.
func (m *mailScreens) sync(ctx context.Context, gdb *gorm.DB) error {
m.syncMu.Lock()
defer m.syncMu.Unlock()
def, locales := m.mailLocales(ctx, gdb)
if err := postcard.SyncIndex(ctx, gdb, m.catalog(), locales); err != nil {
return err
}
if err := postcard.EnsureLocaleRows(ctx, gdb, m.catalog(), def, locales); err != nil {
return err
}
m.syncedLocales = mailLocaleKey(def, locales)
m.synced.Store(true)
return nil
}
// syncOnDatabase is the serve-start sync (D-23), run through
// lagoon.OnDatabase. A failure (the tables not migrated yet, for example)
// is logged and never fails the boot: the first mail list request retries.
func (m *mailScreens) syncOnDatabase(gdb *gorm.DB) {
ctx := context.Background()
if err := m.sync(ctx, gdb.Session(&gorm.Session{NewDB: true}).WithContext(ctx)); err != nil {
moduleLog.Warn("cabana: mail index sync failed; the first mail list request retries", "error", err)
}
}
// ensureSynced retries the index sync until it has succeeded once in this
// process, and syncs again when the mail locales changed since (a locale
// enabled through a translate plugin, for example). It is called before a
// mail list is read.
func (m *mailScreens) ensureSynced(ctx context.Context) {
gdb := m.db()
if gdb == nil {
return
}
db := gdb.Session(&gorm.Session{NewDB: true}).WithContext(ctx)
if m.synced.Load() {
def, locales := m.mailLocales(ctx, db)
m.syncMu.Lock()
current := m.syncedLocales == mailLocaleKey(def, locales)
m.syncMu.Unlock()
if current {
return
}
}
if err := m.sync(ctx, db); err != nil {
moduleLog.WarnContext(ctx, "cabana: mail index sync failed", "error", err)
}
}
// message translates a backend phrase key in the request locale with
// params; the key itself is returned without a translator.
func (m *mailScreens) message(ctx context.Context, key string, params map[string]string) string {
tr := m.translator()
if tr == nil || !tr.Has(key) {
return key
}
return tr.Get(towel.WithLocale(ctx, schemaLocale(ctx, tr)), key, params)
}
// choice translates a plural backend phrase key in the request locale.
func (m *mailScreens) choice(ctx context.Context, key string, count int64, params map[string]string) string {
tr := m.translator()
if tr == nil || !tr.Has(key) {
return key
}
return tr.Choice(towel.WithLocale(ctx, schemaLocale(ctx, tr)), key, count, params)
}
// draftFailure turns postcard's verdict on a draft into the 422 field line
// of the edited field: the translated rule text, with the parser's or the
// checker's own text as :message and the partial as :name.
func (m *mailScreens) draftFailure(ctx context.Context, de *postcard.DraftError) error {
field := de.Field
if field == "" {
field = "body"
}
text := m.draftMessage(ctx, de)
return &ValidationError{Details: map[string]any{field: []string{text}}}
}
// draftMessage is the translated text of a draft failure.
func (m *mailScreens) draftMessage(ctx context.Context, de *postcard.DraftError) string {
return m.message(ctx, mailLang+"invalid_"+de.Rule, map[string]string{"message": de.Message, "name": de.Name})
}
// templateCodes are the full names of the templates in this process's
// catalog: a row whose code is not among them is hidden (D-23).
func (m *mailScreens) templateCodes() []string {
files := m.catalog().Templates()
out := make([]string, 0, len(files))
for _, f := range files {
out = append(out, f.Name)
}
return out
}
// layoutCodes are the full names of the layouts in this process's catalog.
func (m *mailScreens) layoutCodes() []string {
files := m.catalog().Layouts()
out := make([]string, 0, len(files))
for _, f := range files {
out = append(out, f.Name)
}
return out
}
// scopeLayouts limits a layouts query to the layouts this process can send:
// every database-only layout, and the file layouts of its catalog.
func (m *mailScreens) scopeLayouts(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
return db.Where("("+postcard.LayoutsTable+".source IS NULL OR "+postcard.LayoutsTable+".code IN ?)", nonEmpty(m.layoutCodes()))
}
// nonEmpty keeps an IN list from being empty, which matches nothing.
func nonEmpty(codes []string) []string {
if len(codes) == 0 {
return []string{""}
}
return codes
}
// MailTemplate is a row of postcard's templates table: one per file
// template and one per locale a template ships no file for (a fallback-locale
// row), its override columns set while that version is customized. BaseCode
// groups the locale versions of one template.
type MailTemplate struct {
ID uint `gorm:"column:id;primaryKey"`
Code string `gorm:"column:code"`
BaseCode *string `gorm:"column:base_code"`
Source string `gorm:"column:source"`
Locale *string `gorm:"column:locale"`
Description string `gorm:"column:description"`
Subject string `gorm:"column:subject"`
Body string `gorm:"column:body"`
LayoutID *uint `gorm:"column:layout_id"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
CustomizedAt *time.Time `gorm:"column:customized_at"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
Layout MailLayout `gorm:"foreignKey:LayoutID"`
// CustomizedLocales is the list's Customized locales column: the labels
// of the template's customized versions (Default, then locale codes),
// filled by the list; it is not stored.
CustomizedLocales string `gorm:"-:all;column:customized_locales"`
}
func (MailTemplate) TableName() string { return postcard.TemplatesTable }
// FilterScopes lists the scopes of the templates list filters: the status.
func (MailTemplate) FilterScopes() []string { return []string{mailFilterStatus} }
// FilterScope narrows the templates list to one status of the whole
// template: customized when any of its locale versions is, not customized
// when none is, outdated when a customized version's file changed since.
func (MailTemplate) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
if db == nil {
return db
}
if name != mailFilterStatus {
return db.Where("1 = 0")
}
table := postcard.TemplatesTable
group := "COALESCE(" + table + ".base_code, " + table + ".code)"
groups := func(cond string) string {
return "SELECT g.base_code FROM " + table + " g WHERE g.base_code IS NOT NULL AND " + cond
}
switch strings.TrimSpace(fmt.Sprint(value)) {
case mailStatusCustomized:
return db.Where(group + " IN (" + groups("g.is_custom") + ")")
case mailStatusNotCustomized:
return db.Where(group + " NOT IN (" + groups("g.is_custom") + ")")
case mailStatusOutdated:
return db.Where(group + " IN (" + groups("g.is_custom AND g.base_hash IS DISTINCT FROM g.file_hash") + ")")
}
return db
}
// Fillable lists the override columns a form writes: subject and body. The
// layout is written through the layout relation field.
func (MailTemplate) Fillable() []string { return []string{"subject", "body"} }
// Rules require a subject.
func (MailTemplate) Rules() map[string]string {
return map[string]string{"subject": "required"}
}
// MailLayout is a row of postcard's layouts table: a file layout's index
// row, or a database-only (custom) layout, whose source is NULL.
type MailLayout struct {
ID uint `gorm:"column:id;primaryKey"`
Code string `gorm:"column:code"`
Source *string `gorm:"column:source"`
Name string `gorm:"column:name"`
ContentHTML string `gorm:"column:content_html"`
ContentText string `gorm:"column:content_text"`
ContentCSS string `gorm:"column:content_css"`
// DisableAutoInlineCSS keeps the layout's CSS in its style block only
// (postcard copies it onto the elements otherwise). A new custom layout
// starts with it off.
DisableAutoInlineCSS bool `gorm:"column:disable_auto_inline_css"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
// CustomizedAt is when the layout was last saved from the admin.
CustomizedAt *time.Time `gorm:"column:customized_at"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (MailLayout) TableName() string { return postcard.LayoutsTable }
// mailTemplatesAdmin is the Mail templates screen
// (summercms.cabana.mailtemplates) over postcard's templates table. Every
// route needs system.manage_mail_templates. Templates come from plugin
// files: rows are never created or deleted here, only customized.
type mailTemplatesAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailTemplatesAdmin{}
_ pact.AdminPermissioned = mailTemplatesAdmin{}
_ pact.AdminRecordSource = mailTemplatesAdmin{}
_ pact.FormRecordTitle = mailTemplatesAdmin{}
_ FieldRelationProvider = mailTemplatesAdmin{}
_ pact.RelationExtendOptionsQuery = mailTemplatesAdmin{}
_ pact.ListExtendQuery = mailTemplatesAdmin{}
_ pact.ListExtendRecords = mailTemplatesAdmin{}
_ pact.FormExtendQuery = mailTemplatesAdmin{}
_ pact.FormBeforeCreate = mailTemplatesAdmin{}
_ pact.FormBeforeUpdate = mailTemplatesAdmin{}
_ pact.FormAfterUpdate = mailTemplatesAdmin{}
_ pact.FormBeforeDelete = mailTemplatesAdmin{}
_ pact.ListRowStates = mailTemplatesAdmin{}
_ pact.FilterOptions = mailTemplatesAdmin{}
_ pact.HasAdminRecordActions = mailTemplatesAdmin{}
_ pact.AdminPartialData = mailTemplatesAdmin{}
_ recordDeletable = mailTemplatesAdmin{}
_ recordLocaleVariants = mailTemplatesAdmin{}
_ recordShowAdjuster = mailTemplatesAdmin{}
_ formFooterActions = mailTemplatesAdmin{}
)
func (mailTemplatesAdmin) ID() string { return MailTemplatesControllerID }
func (mailTemplatesAdmin) ModelName() string { return `System\Models\MailTemplate` }
func (mailTemplatesAdmin) ConfigDir() string { return "controllers/mailtemplates" }
func (mailTemplatesAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailTemplates}
}
func (mailTemplatesAdmin) NewRecord() any { return &MailTemplate{} }
// asMailTemplate asserts a hook's model.
func asMailTemplate(model any) (*MailTemplate, error) {
t, ok := model.(*MailTemplate)
if !ok || t == nil {
return nil, errors.New("cabana: mail templates: record is not a mail template")
}
return t, nil
}
// FormRecordTitle names a template by its base code: every locale version
// of a template carries the same title, the switcher tells them apart.
func (mailTemplatesAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) {
t, err := asMailTemplate(record)
if err != nil {
return "", err
}
if t.BaseCode != nil && *t.BaseCode != "" {
return *t.BaseCode, nil
}
return t.Code, nil
}
// mailLayoutField is the template form's layout picker.
const mailLayoutField = "layout"
// AdminFieldRelations binds the layout picker to layout_id.
func (mailTemplatesAdmin) AdminFieldRelations() []FieldRelationContract {
return []FieldRelationContract{{
Field: mailLayoutField,
Kind: "belongsTo",
NewRelated: func() any { return &MailLayout{} },
ForeignKey: "layout_id",
LabelColumn: "name",
}}
}
// RelationExtendOptionsQuery offers the layouts this process can send: every
// custom layout and the file layouts of its catalog. A save checks the
// submitted id against the same query.
func (c mailTemplatesAdmin) RelationExtendOptionsQuery(_ context.Context, field string, db *gorm.DB) *gorm.DB {
if field != mailLayoutField {
return db
}
return c.mail.scopeLayouts(db)
}
// scopeTemplates hides the rows of templates this process's catalog does
// not hold (a plugin that was removed, for example).
func (c mailTemplatesAdmin) scopeTemplates(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
return db.Where(postcard.TemplatesTable+".code IN ?", nonEmpty(c.mail.templateCodes()))
}
// ListExtendQuery retries the index sync until it succeeded in this process
// and lists one row per template of the catalog (templateRepresentatives).
func (c mailTemplatesAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
c.mail.ensureSynced(ctx)
if db == nil {
return db
}
_, locales := c.mail.mailLocales(ctx, c.mail.db())
return db.Where(postcard.TemplatesTable+".code IN ?", nonEmpty(c.mail.templateRepresentatives(locales)))
}
// templateRepresentatives are the codes of the rows the templates list
// shows, one per template: the base template's own row when the base ships
// a file, otherwise the lowest code of its locale variants.
func (m *mailScreens) templateRepresentatives(locales []string) []string {
byBase := map[string]string{}
for _, f := range m.catalog().Templates() {
base := postcard.TemplateBase(f.Name, locales)
if current, ok := byBase[base]; !ok || f.Name == base || (current != base && f.Name < current) {
byBase[base] = f.Name
}
}
out := make([]string, 0, len(byBase))
for _, code := range byBase {
out = append(out, code)
}
sort.Strings(out)
return out
}
// templateGroup is the base code a template row's locale versions share.
func templateGroup(t *MailTemplate, locales []string) string {
if t.BaseCode != nil && *t.BaseCode != "" {
return *t.BaseCode
}
return postcard.TemplateBase(t.Code, locales)
}
// FormExtendQuery scopes every record lookup to the catalog's templates and
// their fallback-locale rows (base_code a catalog template).
func (c mailTemplatesAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
return c.mail.scopeTemplateVersions(db)
}
// scopeTemplateVersions limits a templates query to the rows a record lookup
// may open: a catalog template's own row, or a row whose base_code is a
// catalog template (a locale that ships no file).
func (m *mailScreens) scopeTemplateVersions(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
codes := nonEmpty(m.templateCodes())
return db.Where("("+postcard.TemplatesTable+".code IN ? OR "+postcard.TemplatesTable+".base_code IN ?)", codes, codes)
}
// mailCustomizedLocalesShown is how many customized locales the list names
// before it adds " +N".
const mailCustomizedLocalesShown = 3
// ListExtendRecords fills the Customized locales column from one query over
// the page's templates: the labels of their customized versions, Default
// first, then the locale codes.
func (c mailTemplatesAdmin) ListExtendRecords(ctx context.Context, db *gorm.DB, records []any) error {
_, locales := c.mail.mailLocales(ctx, c.mail.db())
groups := make([]string, 0, len(records))
for _, record := range records {
t, err := asMailTemplate(record)
if err != nil {
return err
}
groups = append(groups, templateGroup(t, locales))
}
if len(groups) == 0 || db == nil {
return nil
}
var rows []struct {
BaseCode string
Code string
Locale *string
}
q := db.Session(&gorm.Session{NewDB: true}).Table(postcard.TemplatesTable).
Select("base_code, code, locale").
Where(postcard.TemplatesTable+".base_code IN ? AND "+postcard.TemplatesTable+".is_custom", groups)
if err := c.mail.scopeTemplateVersions(q).Scan(&rows).Error; err != nil {
return err
}
byGroup := map[string][]string{}
defaults := map[string]bool{}
for _, r := range rows {
if r.Code == r.BaseCode {
defaults[r.BaseCode] = true
continue
}
label := r.Code
if r.Locale != nil && *r.Locale != "" {
label = *r.Locale
}
byGroup[r.BaseCode] = append(byGroup[r.BaseCode], label)
}
defaultLabel := c.mail.message(ctx, mailLang+"template.locale_default", nil)
for i, record := range records {
t, _ := asMailTemplate(record)
labels := byGroup[groups[i]]
sort.Strings(labels)
if defaults[groups[i]] {
labels = append([]string{defaultLabel}, labels...)
}
text := strings.Join(labels, ", ")
if extra := len(labels) - mailCustomizedLocalesShown; extra > 0 {
text = strings.Join(labels[:mailCustomizedLocalesShown], ", ") + " +" + strconv.Itoa(extra)
}
t.CustomizedLocales = text
}
return nil
}
// FormBeforeCreate refuses: templates come from plugin files.
func (mailTemplatesAdmin) FormBeforeCreate(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "template.no_create"}
}
// FormBeforeDelete refuses: a template's row belongs to its file; Reset to
// file version removes an override.
func (mailTemplatesAdmin) FormBeforeDelete(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "file_delete"}
}
func (mailTemplatesAdmin) recordDeletable(any) bool { return false }
func (mailTemplatesAdmin) formFooterActions() {}
// ListRowStates marks a template customized when any of its locale
// versions is, and outdated as well when a customized version's file
// changed since (D-07), from one grouped query over the page.
func (c mailTemplatesAdmin) ListRowStates(ctx context.Context, db *gorm.DB, records []any) ([][]pact.RowState, error) {
out := make([][]pact.RowState, len(records))
_, locales := c.mail.mailLocales(ctx, c.mail.db())
groups := make([]string, 0, len(records))
for _, record := range records {
t, err := asMailTemplate(record)
if err != nil {
return nil, err
}
groups = append(groups, templateGroup(t, locales))
}
if len(groups) == 0 || db == nil {
return out, nil
}
var rows []struct {
BaseCode string
Custom bool
Outdated bool
}
table := postcard.TemplatesTable
q := db.Session(&gorm.Session{NewDB: true}).Table(table).
Select("base_code, BOOL_OR(is_custom) AS custom, BOOL_OR(is_custom AND base_hash IS DISTINCT FROM file_hash) AS outdated").
Where(table+".base_code IN ?", groups)
if err := c.mail.scopeTemplateVersions(q).Group("base_code").Scan(&rows).Error; err != nil {
return nil, err
}
states := map[string][]pact.RowState{}
for _, r := range rows {
switch {
case r.Outdated:
states[r.BaseCode] = []pact.RowState{pact.RowStateCustomized, pact.RowStateOutdated}
case r.Custom:
states[r.BaseCode] = []pact.RowState{pact.RowStateCustomized}
}
}
for i, group := range groups {
out[i] = states[group]
}
return out, nil
}
// FilterOptions serves the status filter.
func (mailTemplatesAdmin) FilterOptions(scope string) []pact.Option {
if scope == mailFilterStatus {
return mailStatusOptions()
}
return nil
}
// AdminRecordActions is Reset to file version on a customized template.
func (c mailTemplatesAdmin) AdminRecordActions() []pact.AdminRecordAction {
return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindTemplate, PermissionManageMailTemplates, mailLang+"template.reset_confirm",
func(record any) (string, bool, error) {
t, err := asMailTemplate(record)
if err != nil {
return "", false, err
}
return t.Code, t.IsCustom, nil
})}
}
// PartialData serves the form's info and file_version partials.
func (c mailTemplatesAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
t, _ := record.(*MailTemplate)
if t == nil || t.ID == 0 {
return mailEmptyView(name)
}
// A locale that ships no file is based on the base template's file.
file, ok := c.mail.catalog().TemplateFor(t.Code)
switch name {
case mailPartialInfo:
view := mailInfoView{Template: true, Customized: t.IsCustom, Outdated: mailOutdated(t.IsCustom, t.BaseHash, t.FileHash)}
view.Status = mailStatusKey(t.IsCustom)
if ok {
view.Description = c.mail.message(ctx, mailLang+"info_description", map[string]string{"text": file.Description})
view.File = c.mail.fileLine(ctx, file.Name, file.PluginID)
for key := range file.Samples {
view.Variables = append(view.Variables, key)
}
sort.Strings(view.Variables)
}
if err := c.localeInfo(ctx, t, &view); err != nil {
return nil, err
}
return view, nil
case mailPartialFileVersion:
if !ok {
return mailFileVersionView{}, nil
}
layout, err := c.mail.layoutCodeRead(ctx, t.LayoutID)
if err != nil {
return nil, err
}
return mailFileVersion(t.IsCustom,
postcard.FormatTemplate(file.Subject, file.Layout, file.Body),
postcard.FormatTemplate(t.Subject, layout, t.Body), file.Source), nil
}
return nil, fmt.Errorf("cabana: mail templates: unknown partial %q", name)
}
// localeInfo sets the info partial's locale line of a template with two or
// more locale versions: the default line on the Default version, the
// fallback line (:locale) on a locale that ships no file.
func (c mailTemplatesAdmin) localeInfo(ctx context.Context, t *MailTemplate, view *mailInfoView) error {
db := c.mail.requestDB(ctx)
if db == nil {
return nil
}
def, locales := c.mail.mailLocales(ctx, db)
base := templateGroup(t, locales)
variants, err := c.mail.localeVariants(ctx, db, t, base, def, locales)
if err != nil || len(variants) < 2 {
return err
}
if t.Code == base {
view.LocaleDefault = true
return nil
}
if _, own := c.mail.catalog().Template(t.Code); !own {
locale := t.Code
if t.Locale != nil && *t.Locale != "" {
locale = *t.Locale
}
view.LocaleFallback = c.mail.message(ctx, mailLang+"info_locale_fallback", map[string]string{"locale": locale})
}
return nil
}
// adjustShownRecord shows a locale that ships no file and is not customized
// with what that locale sends now: the base template's current subject, body
// and layout (its customization when there is one). Only the shown record
// changes; nothing is written.
func (c mailTemplatesAdmin) adjustShownRecord(_ context.Context, tx *gorm.DB, record any) error {
t, err := asMailTemplate(record)
if err != nil || t.IsCustom {
return err
}
cat := c.mail.catalog()
if _, own := cat.Template(t.Code); own {
return nil
}
file, ok := cat.TemplateFor(t.Code)
if !ok {
return nil
}
var rows []struct {
Subject string
Body string
LayoutID *uint
}
if err := tx.Session(&gorm.Session{NewDB: true}).Table(postcard.TemplatesTable).
Select("subject, body, layout_id").Where("code = ?", file.Name).Scan(&rows).Error; err != nil {
return err
}
if len(rows) == 0 {
return nil
}
t.Subject, t.Body, t.LayoutID = rows[0].Subject, rows[0].Body, rows[0].LayoutID
t.Layout = MailLayout{}
return nil
}
// FormBeforeUpdate marks the row customized and stamps it with the hash of
// the file it is based on, which is what later shows a changed file (D-07).
func (c mailTemplatesAdmin) FormBeforeUpdate(_ context.Context, model any) error {
t, err := asMailTemplate(model)
if err != nil {
return err
}
// A fallback-locale row is based on the base template's file.
file, ok := c.mail.catalog().TemplateFor(t.Code)
if !ok {
return &ForbiddenError{Message: mailLang + "file_missing"}
}
now := time.Now().UTC()
hash := file.Hash
t.IsCustom = true
t.BaseHash = &hash
t.FileHash = &hash
t.CustomizedAt = &now
return nil
}
// FormAfterUpdate validates the saved override through postcard, after the
// layout relation was assigned and inside the save's transaction: a draft
// postcard would not send rolls the save back with a field line (D-13).
func (c mailTemplatesAdmin) FormAfterUpdate(ctx context.Context, model any) error {
t, err := asMailTemplate(model)
if err != nil {
return err
}
layout, err := c.mail.layoutCode(ctx, t.LayoutID)
if err != nil {
return err
}
draft := postcard.Draft{Kind: postcard.KindTemplate, Name: t.Code, Subject: t.Subject, Body: t.Body, Layout: layout}
if de := c.mail.editor.Validate(ctx, draft); de != nil {
return c.mail.draftFailure(ctx, de)
}
return nil
}
// layoutCode reads the code of the layout row id through the request's
// transaction; "" when id is nil.
func (m *mailScreens) layoutCode(ctx context.Context, id *uint) (string, error) {
if id == nil || *id == 0 {
return "", nil
}
db := m.requestDB(ctx)
if db == nil {
return "", errors.New("cabana: mail: database handle is missing")
}
var codes []string
if err := db.Table(postcard.LayoutsTable).Where("id = ?", *id).Pluck("code", &codes).Error; err != nil {
return "", err
}
if len(codes) == 0 {
return "", &ValidationError{Details: map[string]any{mailLayoutField: []string{m.message(ctx, mailLang+"invalid_layout", nil)}}}
}
return codes[0], nil
}
// layoutCodeRead is layoutCode for display: "" when the row is gone.
func (m *mailScreens) layoutCodeRead(ctx context.Context, id *uint) (string, error) {
code, err := m.layoutCode(ctx, id)
var invalid *ValidationError
if errors.As(err, &invalid) {
return "", nil
}
return code, err
}
// recordDeletable is implemented by the mail controllers, which decide per
// record whether the form offers Delete; the show response then carries
// meta.deletable. Other controllers do not implement it and send no key.
type recordDeletable interface {
recordDeletable(record any) bool
}
// recordLocaleVariants is implemented by the mail templates controller,
// whose records are the locale versions of a template: the show response
// then carries meta.localeVariants, the versions of the record's template
// for the form's locale switcher. Unexported: no other controller's payload
// changes.
type recordLocaleVariants interface {
recordLocaleVariants(ctx context.Context, tx *gorm.DB, record any) ([]RecordLocaleVariant, error)
}
// recordShowAdjuster is implemented by the mail templates controller: the
// show response of a locale version that is not customized and ships no
// file shows the default version instead of its stored copy. It runs in the
// show's transaction after the record is loaded and only changes the loaded
// value. Unexported: no other controller's payload changes.
type recordShowAdjuster interface {
adjustShownRecord(ctx context.Context, tx *gorm.DB, record any) error
}
// formFooterActions marks a controller whose config_form.yaml declares
// recordActions without a preview block: the admin offers them in the
// update form's footer instead. Only the mail controllers implement it.
type formFooterActions interface {
formFooterActions()
}
// The mail list filter scope and values.
const (
mailFilterStatus = "filterStatus"
mailStatusCustomized = "customized"
mailStatusNotCustomized = "not_customized"
mailStatusOutdated = "outdated"
)
// mailStatusOptions are the status filter's choices.
func mailStatusOptions() []pact.Option {
return []pact.Option{
{Value: mailStatusCustomized, Label: mailLang + "filter_customized"},
{Value: mailStatusNotCustomized, Label: mailLang + "filter_not_customized"},
{Value: mailStatusOutdated, Label: mailLang + "filter_outdated"},
}
}
// mailStatusScope narrows a mail list on table to one status: customized
// (a file-backed row with an override), not customized, or outdated (an
// override whose file changed since). Any other scope matches nothing.
func mailStatusScope(db *gorm.DB, name, table, value string) *gorm.DB {
if name != mailFilterStatus {
return db.Where("1 = 0")
}
switch value {
case mailStatusCustomized:
return db.Where(table + ".is_custom AND " + table + ".source IS NOT NULL")
case mailStatusNotCustomized:
return db.Where("NOT " + table + ".is_custom")
case mailStatusOutdated:
return db.Where(table + ".is_custom AND " + table + ".source IS NOT NULL AND " + table + ".base_hash IS DISTINCT FROM " + table + ".file_hash")
}
return db
}
// mailOutdated reports an override whose file changed after it was saved.
func mailOutdated(custom bool, base, file *string) bool {
if !custom {
return false
}
if base == nil || file == nil {
return base != file
}
return *base != *file
}
// mailRowStates are a file-backed row's states: customized while it holds
// an override, and outdated as well when its file changed since.
func mailRowStates(fileBacked, custom bool, base, file *string) []pact.RowState {
if !fileBacked || !custom {
return nil
}
if mailOutdated(custom, base, file) {
return []pact.RowState{pact.RowStateCustomized, pact.RowStateOutdated}
}
return []pact.RowState{pact.RowStateCustomized}
}
// mailStatusKey is the info partial's status line.
func mailStatusKey(custom bool) string {
if custom {
return mailLang + "info_customized"
}
return mailLang + "info_not_customized"
}
// resetAction is Reset to file version for kind: offered on a file-backed
// row that holds an override (row reports the code and whether it applies),
// it returns the row to its file through postcard.ResetOverride inside the
// action's transaction.
func (m *mailScreens) resetAction(kind postcard.Kind, permission, confirm string, row func(record any) (string, bool, error)) pact.AdminRecordAction {
return pact.AdminRecordAction{
Name: "reset",
Label: mailLang + "reset",
Confirm: confirm,
Permissions: []string{permission},
Danger: true,
Applies: func(_ context.Context, record any) (bool, error) {
_, applies, err := row(record)
return applies, err
},
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
code, applies, err := row(in.Record)
if err != nil {
return pact.AdminRecordActionResult{}, err
}
if !applies {
return pact.AdminRecordActionResult{}, &ForbiddenError{Message: mailLang + "reset_unavailable"}
}
tx, ok := TxFromContext(ctx)
if !ok {
return pact.AdminRecordActionResult{}, errors.New("cabana: mail: a reset needs its transaction")
}
if err := postcard.ResetOverride(ctx, tx.Session(&gorm.Session{NewDB: true}), m.catalog(), kind, code); err != nil {
return pact.AdminRecordActionResult{}, err
}
return pact.AdminRecordActionResult{Message: mailLang + "reset_done"}, nil
},
}
}
// stamp marks a file-backed row customized against the file hash.
func stamp(custom *bool, base, file **string, at **time.Time, hash string) {
now := time.Now().UTC()
*custom = true
value := hash
*base = &value
current := hash
*file = &current
*at = &now
}
// MailLayout methods: the layouts screen's form, rules and filter.
// Fillable lists the columns the layout form writes. code is written only
// when a custom layout is created (its field's context is create).
func (MailLayout) Fillable() []string {
return []string{"name", "code", "content_html", "content_text", "content_css", "disable_auto_inline_css"}
}
// Rules require a name and a code.
func (MailLayout) Rules() map[string]string {
return map[string]string{"name": "required|max:255", "code": "required|max:255"}
}
// FilterScopes lists the layouts list filter scope.
func (MailLayout) FilterScopes() []string { return []string{mailFilterStatus} }
// FilterScope narrows the layouts list to one status.
func (MailLayout) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
if db == nil {
return db
}
return mailStatusScope(db, name, postcard.LayoutsTable, strings.TrimSpace(fmt.Sprint(value)))
}
// mailLayoutsAdmin is the Mail layouts screen (summercms.cabana.maillayouts):
// every file layout, which can be customized and reset, and the custom
// layouts that exist only in the database, which can be created and
// deleted. Every route needs system.manage_mail_layouts.
type mailLayoutsAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailLayoutsAdmin{}
_ pact.AdminPermissioned = mailLayoutsAdmin{}
_ pact.AdminRecordSource = mailLayoutsAdmin{}
_ pact.FormRecordTitle = mailLayoutsAdmin{}
_ pact.ListExtendQuery = mailLayoutsAdmin{}
_ pact.ListExtendRecords = mailLayoutsAdmin{}
_ pact.FormExtendQuery = mailLayoutsAdmin{}
_ pact.FormBeforeCreate = mailLayoutsAdmin{}
_ pact.FormAfterCreate = mailLayoutsAdmin{}
_ pact.FormBeforeUpdate = mailLayoutsAdmin{}
_ pact.FormAfterUpdate = mailLayoutsAdmin{}
_ pact.FormBeforeDelete = mailLayoutsAdmin{}
_ pact.ListRowStates = mailLayoutsAdmin{}
_ pact.FilterOptions = mailLayoutsAdmin{}
_ pact.HasAdminRecordActions = mailLayoutsAdmin{}
_ pact.AdminPartialData = mailLayoutsAdmin{}
_ recordDeletable = mailLayoutsAdmin{}
_ formFooterActions = mailLayoutsAdmin{}
)
func (mailLayoutsAdmin) ID() string { return MailLayoutsControllerID }
func (mailLayoutsAdmin) ModelName() string { return `System\Models\MailLayout` }
func (mailLayoutsAdmin) ConfigDir() string { return "controllers/maillayouts" }
func (mailLayoutsAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailLayouts}
}
func (mailLayoutsAdmin) NewRecord() any { return &MailLayout{} }
func (mailLayoutsAdmin) formFooterActions() {}
func asMailLayout(model any) (*MailLayout, error) {
l, ok := model.(*MailLayout)
if !ok || l == nil {
return nil, errors.New("cabana: mail layouts: record is not a mail layout")
}
return l, nil
}
// recordDeletable: only a custom layout can be deleted.
func (mailLayoutsAdmin) recordDeletable(record any) bool {
l, err := asMailLayout(record)
return err == nil && l.Source == nil
}
// FormRecordTitle names a layout by its name.
func (mailLayoutsAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) {
l, err := asMailLayout(record)
if err != nil {
return "", err
}
return l.Name, nil
}
// mailDefaultLayout is postcard's built-in default layout, listed first.
const mailDefaultLayout = "postcard::mail.layouts.default"
// ListExtendQuery retries the index sync, lists the layouts this process can
// send and puts postcard's default layout first.
func (c mailLayoutsAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
c.mail.ensureSynced(ctx)
// A raw column: an OrderBy expression would be dropped when the list's
// own sort is merged into the clause. The SQL is a constant.
return c.mail.scopeLayouts(db).Order(clause.OrderByColumn{Column: clause.Column{
Name: "CASE WHEN " + postcard.LayoutsTable + ".code = '" + mailDefaultLayout + "' THEN 0 ELSE 1 END", Raw: true,
}})
}
// FormExtendQuery applies the catalog scope to every record lookup.
func (c mailLayoutsAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
return c.mail.scopeLayouts(db)
}
// ListExtendRecords shows a custom layout's source as Custom.
func (c mailLayoutsAdmin) ListExtendRecords(ctx context.Context, _ *gorm.DB, records []any) error {
label := c.mail.message(ctx, mailLang+"source_custom", nil)
for _, record := range records {
l, err := asMailLayout(record)
if err != nil {
return err
}
if l.Source == nil {
value := label
l.Source = &value
}
}
return nil
}
// ListRowStates marks customized file layouts (and outdated ones); custom
// layouts carry no state.
func (mailLayoutsAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) {
out := make([][]pact.RowState, len(records))
for i, record := range records {
l, err := asMailLayout(record)
if err != nil {
return nil, err
}
out[i] = mailRowStates(l.Source != nil, l.IsCustom, l.BaseHash, l.FileHash)
}
return out, nil
}
// FilterOptions serves the status filter.
func (mailLayoutsAdmin) FilterOptions(scope string) []pact.Option {
if scope == mailFilterStatus {
return mailStatusOptions()
}
return nil
}
// mailLayoutCode is the format of a custom layout's code.
var mailLayoutCode = regexp.MustCompile(`^[a-z0-9-]+$`)
// FormBeforeCreate creates a custom layout: the code must be lowercase
// letters, digits and dashes and free, and the row has no source.
func (c mailLayoutsAdmin) FormBeforeCreate(ctx context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
l.Code = strings.TrimSpace(l.Code)
if !mailLayoutCode.MatchString(l.Code) {
return &ValidationError{Details: map[string]any{"code": []string{c.mail.message(ctx, mailLang+"layout.code_format", nil)}}}
}
db := c.mail.requestDB(ctx)
if db == nil {
return errors.New("cabana: mail layouts: database handle is missing")
}
var taken int64
if err := db.Table(postcard.LayoutsTable).Where("code = ?", l.Code).Count(&taken).Error; err != nil {
return err
}
if taken > 0 {
return &ValidationError{Details: map[string]any{"code": []string{c.mail.message(ctx, mailLang+"layout.code_taken", nil)}}}
}
now := time.Now().UTC()
l.Source = nil
l.IsCustom = true
l.FileHash, l.BaseHash = nil, nil
l.CustomizedAt = &now
return nil
}
// FormAfterCreate validates the new layout through postcard.
func (c mailLayoutsAdmin) FormAfterCreate(ctx context.Context, model any) error {
return c.validate(ctx, model)
}
// FormBeforeUpdate stamps a file layout customized against its file (its
// name stays the file's: the index sync owns it); a custom layout records
// when it was saved.
func (c mailLayoutsAdmin) FormBeforeUpdate(_ context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
if l.Source == nil {
now := time.Now().UTC()
l.IsCustom = true
l.CustomizedAt = &now
return nil
}
file, ok := c.mail.catalog().Layout(l.Code)
if !ok {
return &ForbiddenError{Message: mailLang + "file_missing"}
}
l.Name = mailRowName(file.Title, file.Name)
stamp(&l.IsCustom, &l.BaseHash, &l.FileHash, &l.CustomizedAt, file.Hash)
return nil
}
// FormAfterUpdate validates the saved layout through postcard (D-13).
func (c mailLayoutsAdmin) FormAfterUpdate(ctx context.Context, model any) error {
return c.validate(ctx, model)
}
func (c mailLayoutsAdmin) validate(ctx context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
draft := postcard.Draft{Kind: postcard.KindLayout, Name: l.Code, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS, DisableAutoInlineCSS: l.DisableAutoInlineCSS}
if de := c.mail.editor.Validate(ctx, draft); de != nil {
return c.mail.draftFailure(ctx, de)
}
return nil
}
// FormBeforeDelete refuses a file layout and a custom layout that templates
// still use, naming the layout and how many (D-08). The foreign key's ON
// DELETE RESTRICT stays the backstop.
func (c mailLayoutsAdmin) FormBeforeDelete(ctx context.Context, model any) error {
l, err := asMailLayout(model)
if err != nil {
return err
}
if l.Source != nil {
return &ForbiddenError{Message: mailLang + "file_delete"}
}
db := c.mail.requestDB(ctx)
if db == nil {
return errors.New("cabana: mail layouts: database handle is missing")
}
var users int64
if err := db.Table(postcard.TemplatesTable).Where("layout_id = ?", l.ID).Count(&users).Error; err != nil {
return err
}
if users == 0 {
return nil
}
return &ForbiddenError{Message: c.mail.choice(ctx, mailLang+"layout.delete_in_use", users, map[string]string{"name": l.Name, "count": strconv.FormatInt(users, 10)})}
}
// AdminRecordActions is Reset to file version on a customized file layout.
func (c mailLayoutsAdmin) AdminRecordActions() []pact.AdminRecordAction {
return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindLayout, PermissionManageMailLayouts, mailLang+"layout.reset_confirm",
func(record any) (string, bool, error) {
l, err := asMailLayout(record)
if err != nil {
return "", false, err
}
return l.Code, l.Source != nil && l.IsCustom, nil
})}
}
// PartialData serves the form's info and file_version partials.
func (c mailLayoutsAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
l, _ := record.(*MailLayout)
if l == nil || l.ID == 0 {
return mailEmptyView(name)
}
if l.Source == nil {
switch name {
case mailPartialInfo:
return mailInfoView{CustomCode: l.Code}, nil
case mailPartialFileVersion:
return mailFileVersionView{CustomLayout: true}, nil
}
return nil, fmt.Errorf("cabana: mail layouts: unknown partial %q", name)
}
file, ok := c.mail.catalog().Layout(l.Code)
switch name {
case mailPartialInfo:
view := mailInfoView{Customized: l.IsCustom, Status: mailStatusKey(l.IsCustom), Outdated: mailOutdated(l.IsCustom, l.BaseHash, l.FileHash)}
if ok {
view.File = c.mail.fileLine(ctx, l.Code, file.PluginID)
}
return view, nil
case mailPartialFileVersion:
if !ok {
return mailFileVersionView{}, nil
}
return mailFileVersion(l.IsCustom,
postcard.FormatLayout(mailRowName(file.Title, file.Name), file.Text, file.HTML, ""),
postcard.FormatLayout(l.Name, l.ContentText, l.ContentHTML, l.ContentCSS), file.Source), nil
}
return nil, fmt.Errorf("cabana: mail layouts: unknown partial %q", name)
}
// mailRowName is the name of a file layout's or partial's row: the file
// header's name, else the full name (as postcard.SyncIndex writes it).
func mailRowName(title, full string) string {
if title != "" {
return title
}
return full
}
// MailPartial is a row of postcard's partials table: one per file partial,
// its content columns holding the override while it is customized.
type MailPartial struct {
ID uint `gorm:"column:id;primaryKey"`
Code string `gorm:"column:code"`
Source string `gorm:"column:source"`
Name string `gorm:"column:name"`
ContentHTML string `gorm:"column:content_html"`
ContentText string `gorm:"column:content_text"`
IsCustom bool `gorm:"column:is_custom"`
FileHash *string `gorm:"column:file_hash"`
BaseHash *string `gorm:"column:base_hash"`
CustomizedAt *time.Time `gorm:"column:customized_at"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (MailPartial) TableName() string { return postcard.PartialsTable }
// Fillable lists the columns the partial form writes.
func (MailPartial) Fillable() []string { return []string{"content_html", "content_text"} }
// Rules has no base rule: postcard's draft check validates a partial.
func (MailPartial) Rules() map[string]string { return map[string]string{} }
// FilterScopes lists the partials list filter scope.
func (MailPartial) FilterScopes() []string { return []string{mailFilterStatus} }
// FilterScope narrows the partials list to one status.
func (MailPartial) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
if db == nil {
return db
}
return mailStatusScope(db, name, postcard.PartialsTable, strings.TrimSpace(fmt.Sprint(value)))
}
// mailPartialsAdmin is the Mail partials screen
// (summercms.cabana.mailpartials): every file partial, customized and reset
// here, never created or deleted. Every route needs
// system.manage_mail_layouts.
type mailPartialsAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailPartialsAdmin{}
_ pact.AdminPermissioned = mailPartialsAdmin{}
_ pact.AdminRecordSource = mailPartialsAdmin{}
_ pact.FormRecordTitle = mailPartialsAdmin{}
_ pact.ListExtendQuery = mailPartialsAdmin{}
_ pact.FormExtendQuery = mailPartialsAdmin{}
_ pact.FormBeforeCreate = mailPartialsAdmin{}
_ pact.FormBeforeUpdate = mailPartialsAdmin{}
_ pact.FormAfterUpdate = mailPartialsAdmin{}
_ pact.FormBeforeDelete = mailPartialsAdmin{}
_ pact.ListRowStates = mailPartialsAdmin{}
_ pact.FilterOptions = mailPartialsAdmin{}
_ pact.HasAdminRecordActions = mailPartialsAdmin{}
_ pact.AdminPartialData = mailPartialsAdmin{}
_ recordDeletable = mailPartialsAdmin{}
_ formFooterActions = mailPartialsAdmin{}
)
func (mailPartialsAdmin) ID() string { return MailPartialsControllerID }
func (mailPartialsAdmin) ModelName() string { return `System\Models\MailPartial` }
func (mailPartialsAdmin) ConfigDir() string { return "controllers/mailpartials" }
func (mailPartialsAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailLayouts}
}
func (mailPartialsAdmin) NewRecord() any { return &MailPartial{} }
func (mailPartialsAdmin) recordDeletable(any) bool { return false }
func (mailPartialsAdmin) formFooterActions() {}
func asMailPartial(model any) (*MailPartial, error) {
p, ok := model.(*MailPartial)
if !ok || p == nil {
return nil, errors.New("cabana: mail partials: record is not a mail partial")
}
return p, nil
}
// FormRecordTitle names a partial by its code.
func (mailPartialsAdmin) FormRecordTitle(_ context.Context, _ *gorm.DB, record any) (string, error) {
p, err := asMailPartial(record)
if err != nil {
return "", err
}
return p.Code, nil
}
// scopePartials hides the rows of partials this process's catalog does not
// hold.
func (c mailPartialsAdmin) scopePartials(db *gorm.DB) *gorm.DB {
if db == nil {
return db
}
files := c.mail.catalog().Partials()
codes := make([]string, 0, len(files))
for _, f := range files {
codes = append(codes, f.Name)
}
return db.Where(postcard.PartialsTable+".code IN ?", nonEmpty(codes))
}
// ListExtendQuery retries the index sync and lists the catalog's partials.
func (c mailPartialsAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
c.mail.ensureSynced(ctx)
return c.scopePartials(db)
}
// FormExtendQuery applies the catalog scope to every record lookup.
func (c mailPartialsAdmin) FormExtendQuery(_ context.Context, db *gorm.DB) *gorm.DB {
return c.scopePartials(db)
}
// ListRowStates marks customized partials (and outdated ones).
func (mailPartialsAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) {
out := make([][]pact.RowState, len(records))
for i, record := range records {
p, err := asMailPartial(record)
if err != nil {
return nil, err
}
out[i] = mailRowStates(true, p.IsCustom, p.BaseHash, p.FileHash)
}
return out, nil
}
// FilterOptions serves the status filter.
func (mailPartialsAdmin) FilterOptions(scope string) []pact.Option {
if scope == mailFilterStatus {
return mailStatusOptions()
}
return nil
}
// FormBeforeCreate refuses: partials come from files.
func (mailPartialsAdmin) FormBeforeCreate(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "partial.no_create"}
}
// FormBeforeDelete refuses: a partial's row belongs to its file.
func (mailPartialsAdmin) FormBeforeDelete(context.Context, any) error {
return &ForbiddenError{Message: mailLang + "file_delete"}
}
// FormBeforeUpdate stamps the partial customized against its file.
func (c mailPartialsAdmin) FormBeforeUpdate(_ context.Context, model any) error {
p, err := asMailPartial(model)
if err != nil {
return err
}
file, ok := c.mail.catalog().Partial(p.Code)
if !ok {
return &ForbiddenError{Message: mailLang + "file_missing"}
}
stamp(&p.IsCustom, &p.BaseHash, &p.FileHash, &p.CustomizedAt, file.Hash)
return nil
}
// FormAfterUpdate validates the saved partial through postcard (D-13).
func (c mailPartialsAdmin) FormAfterUpdate(ctx context.Context, model any) error {
p, err := asMailPartial(model)
if err != nil {
return err
}
draft := postcard.Draft{Kind: postcard.KindPartial, Name: p.Code, HTML: p.ContentHTML, Text: p.ContentText}
if de := c.mail.editor.Validate(ctx, draft); de != nil {
return c.mail.draftFailure(ctx, de)
}
return nil
}
// AdminRecordActions is Reset to file version on a customized partial.
func (c mailPartialsAdmin) AdminRecordActions() []pact.AdminRecordAction {
return []pact.AdminRecordAction{c.mail.resetAction(postcard.KindPartial, PermissionManageMailLayouts, mailLang+"partial.reset_confirm",
func(record any) (string, bool, error) {
p, err := asMailPartial(record)
if err != nil {
return "", false, err
}
return p.Code, p.IsCustom, nil
})}
}
// PartialData serves the form's info and file_version partials.
func (c mailPartialsAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
p, _ := record.(*MailPartial)
if p == nil || p.ID == 0 {
return mailEmptyView(name)
}
file, ok := c.mail.catalog().Partial(p.Code)
switch name {
case mailPartialInfo:
view := mailInfoView{Customized: p.IsCustom, Status: mailStatusKey(p.IsCustom), Outdated: mailOutdated(p.IsCustom, p.BaseHash, p.FileHash)}
if ok {
view.File = c.mail.fileLine(ctx, p.Code, file.PluginID)
view.Usage = partialUsage(p.Code, file.HTML+"\n"+file.Text)
}
return view, nil
case mailPartialFileVersion:
if !ok {
return mailFileVersionView{}, nil
}
return mailFileVersion(p.IsCustom,
postcard.FormatPartial(mailRowName(file.Title, file.Name), file.Text, file.HTML),
postcard.FormatPartial(p.Name, p.ContentText, p.ContentHTML), file.Source), nil
}
return nil, fmt.Errorf("cabana: mail partials: unknown partial %q", name)
}
// The form partials of the mail screens (controllers/mail*/_info.htm and
// _file_version.htm).
const (
mailPartialInfo = "info"
mailPartialFileVersion = "file_version"
)
// mailInfoView is the view model of _info.htm, the lines at the top of a
// mail form: the template's description, the file it comes from (or a
// custom layout's code), the status, the template's sample variables, a
// partial's call, and the drift callout.
type mailInfoView struct {
Template bool
// LocaleDefault marks the Default version of a template with locale
// versions; LocaleFallback is the translated line of a locale that
// ships no file.
LocaleDefault bool
LocaleFallback string
Description string
File []mailTextPart
CustomCode string
Customized bool
Status string
Variables []string
Usage string
Outdated bool
}
// mailTextPart is a piece of a translated line; Code pieces are shown as
// code.
type mailTextPart struct {
Text string
Code bool
}
// mailFileVersionView is the view model of _file_version.htm: the line diff
// of the override against the file and the file's own text. A custom layout
// has no file.
type mailFileVersionView struct {
Show bool
CustomLayout bool
Customized bool
Identical bool
Diff []mailDiffRow
Content []string
}
// mailDiffRow is one rendered diff line: its class and its prefixed text.
type mailDiffRow struct {
Class string
Text string
}
// mailEmptyView is the view of a partial without a record (a create form).
func mailEmptyView(name string) (any, error) {
switch name {
case mailPartialInfo:
return mailInfoView{}, nil
case mailPartialFileVersion:
return mailFileVersionView{}, nil
}
return nil, fmt.Errorf("cabana: mail: unknown partial %q", name)
}
// diffContext is the number of unchanged lines kept around each change.
const diffContext = 3
// mailFileVersion compares the serialized override (mine) with the
// serialized file (theirs); source is the file's own text.
func mailFileVersion(custom bool, theirs, mine, source string) mailFileVersionView {
view := mailFileVersionView{Show: true, Customized: custom, Content: splitLines(source)}
if !custom {
return view
}
if theirs == mine {
view.Identical = true
return view
}
for _, line := range lineDiff(splitLines(theirs), splitLines(mine), diffContext) {
switch line.Kind {
case diffAdd:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__add", Text: "+ " + line.Text})
case diffDel:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__del", Text: "− " + line.Text})
case diffGap:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__ctx", Text: " …"})
default:
view.Diff = append(view.Diff, mailDiffRow{Class: "summer-diff__ctx", Text: " " + line.Text})
}
}
return view
}
// splitLines splits text into lines; a trailing newline adds no empty line,
// and an empty line is a space so that it keeps its height.
func splitLines(text string) []string {
text = strings.TrimSuffix(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
if text == "" {
return nil
}
lines := strings.Split(text, "\n")
for i, line := range lines {
if line == "" {
lines[i] = " "
}
}
return lines
}
// fileLine is the translated "File: :path in :plugin" line, with the path
// and the plugin as code pieces.
func (m *mailScreens) fileLine(ctx context.Context, code, plugin string) []mailTextPart {
const pathMark, pluginMark = "\x00path\x00", "\x00plugin\x00"
text := m.message(ctx, mailLang+"info_file", map[string]string{"path": pathMark, "plugin": pluginMark})
path := mailFilePath(code)
var out []mailTextPart
for text != "" {
i := strings.IndexByte(text, 0)
if i < 0 {
out = append(out, mailTextPart{Text: text})
break
}
if i > 0 {
out = append(out, mailTextPart{Text: text[:i]})
}
rest := text[i:]
switch {
case strings.HasPrefix(rest, pathMark):
out = append(out, mailTextPart{Text: path, Code: true})
text = rest[len(pathMark):]
case strings.HasPrefix(rest, pluginMark):
out = append(out, mailTextPart{Text: plugin, Code: true})
text = rest[len(pluginMark):]
default:
out = append(out, mailTextPart{Text: rest[1:]})
text = ""
}
}
return out
}
// mailFilePath is the file of a mail name inside its plugin:
// acme.blog::mail.layouts.blog is views/mail/layouts/blog.htm.
func mailFilePath(code string) string {
_, rest, ok := strings.Cut(code, "::")
if !ok {
return code
}
rest = strings.TrimPrefix(rest, "mail.")
return "views/mail/" + strings.ReplaceAll(rest, ".", "/") + ".htm"
}
// builtinPartialPrefix is the name prefix of postcard's own partials, which
// a call names by their bare name.
const builtinPartialPrefix = "postcard::mail.partials."
// partialArg matches a top-level variable (.name) inside a template action.
var (
partialAction = regexp.MustCompile(`\{\{-?(.*?)-?\}\}`)
partialArg = regexp.MustCompile(`(?:^|[\s(|])\.([A-Za-z_][A-Za-z0-9_]*)`)
)
// partialUsage is the call of a partial in a body or a layout: its bare
// name for a built-in, else its full name, then a key and a value for every
// variable its sections read.
func partialUsage(code, sections string) string {
name := strings.TrimPrefix(code, builtinPartialPrefix)
seen := map[string]bool{}
var keys []string
for _, action := range partialAction.FindAllStringSubmatch(sections, -1) {
for _, arg := range partialArg.FindAllStringSubmatch(action[1], -1) {
if !seen[arg[1]] {
seen[arg[1]] = true
keys = append(keys, arg[1])
}
}
}
sort.Strings(keys)
var b strings.Builder
b.WriteString(`{{ partial "` + name + `"`)
for _, key := range keys {
b.WriteString(` "` + key + `" .` + key)
}
b.WriteString(" }}")
return b.String()
}
// MailBrandSetting is the settings form over postcard's branding row (id 1).
// Saving it switches mail from mail.brandCss to the compiled colours.
type MailBrandSetting struct {
ID uint `gorm:"column:id;primaryKey"`
LogoFileID *uint `gorm:"column:logo_file_id"`
SiteName string `gorm:"column:site_name"`
BodyBg string `gorm:"column:body_bg"`
ContentBg string `gorm:"column:content_bg"`
HeaderColor string `gorm:"column:header_color"`
FooterColor string `gorm:"column:footer_color"`
HeadingColor string `gorm:"column:heading_color"`
TextColor string `gorm:"column:text_color"`
LinkColor string `gorm:"column:link_color"`
ButtonTextColor string `gorm:"column:button_text_color"`
ButtonPrimaryBg string `gorm:"column:button_primary_bg"`
ButtonPositiveBg string `gorm:"column:button_positive_bg"`
ButtonNegativeBg string `gorm:"column:button_negative_bg"`
PanelBg string `gorm:"column:panel_bg"`
TableBorderColor string `gorm:"column:table_border_color"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (MailBrandSetting) TableName() string { return postcard.BrandTable }
func (MailBrandSetting) Fillable() []string {
return []string{
"logo_file_id", "site_name", "body_bg", "content_bg", "header_color", "footer_color",
"heading_color", "text_color", "link_color", "button_text_color",
"button_primary_bg", "button_positive_bg", "button_negative_bg",
"panel_bg", "table_border_color",
}
}
func (MailBrandSetting) Rules() map[string]string {
return map[string]string{
"logo_file_id": "nullable",
"site_name": "nullable|max:255",
"body_bg": "nullable",
"content_bg": "nullable",
"header_color": "nullable",
"footer_color": "nullable",
"heading_color": "nullable",
"text_color": "nullable",
"link_color": "nullable",
"button_text_color": "nullable",
"button_primary_bg": "nullable",
"button_positive_bg": "nullable",
"button_negative_bg": "nullable",
"panel_bg": "nullable",
"table_border_color": "nullable",
}
}
var brandColourPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`)
// BeforeValidate trims the site name and refuses a name mail could not show
// (postcard's UnsafeText), lower-cases colours, refuses anything but #rrggbb
// or empty, and checks logo_file_id is null or a library image. One refusal
// lists every field at fault.
func (b *MailBrandSetting) BeforeValidate(tx *gorm.DB) error {
b.SiteName = strings.TrimSpace(b.SiteName)
details := map[string]any{}
if postcard.UnsafeText(b.SiteName) {
details["site_name"] = []string{"backend::lang.mail.brand.site_name_unsafe"}
}
for _, col := range []struct {
name string
value *string
}{
{"body_bg", &b.BodyBg},
{"content_bg", &b.ContentBg},
{"header_color", &b.HeaderColor},
{"footer_color", &b.FooterColor},
{"heading_color", &b.HeadingColor},
{"text_color", &b.TextColor},
{"link_color", &b.LinkColor},
{"button_text_color", &b.ButtonTextColor},
{"button_primary_bg", &b.ButtonPrimaryBg},
{"button_positive_bg", &b.ButtonPositiveBg},
{"button_negative_bg", &b.ButtonNegativeBg},
{"panel_bg", &b.PanelBg},
{"table_border_color", &b.TableBorderColor},
} {
colour := strings.ToLower(strings.TrimSpace(*col.value))
*col.value = colour
if colour == "" {
continue
}
if !brandColourPattern.MatchString(colour) {
details[col.name] = []string{"backend::lang.colorpicker.invalid"}
}
}
if b.LogoFileID != nil {
var n int64
if err := tx.Session(&gorm.Session{NewDB: true}).
Table("system_files").
Where("id = ? AND attachment_type = ? AND field = ?", *b.LogoFileID, mailImageLibraryMorph, "images").
Count(&n).Error; err != nil {
return err
}
if n == 0 {
details["logo_file_id"] = []string{"backend::lang.mailimage.missing"}
}
}
if len(details) > 0 {
return &ValidationError{Details: details}
}
return nil
}
// mailImageLibraryMorph is the attachment_type of the mail image library host.
const mailImageLibraryMorph = `System\Models\MailImageLibrary`
// MailImageLibrary is the one-row host of the mail image library's attachMany
// images relation.
type MailImageLibrary struct {
ID uint `gorm:"column:id;primaryKey"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (MailImageLibrary) TableName() string { return postcard.ImageLibraryTable }
func (MailImageLibrary) MorphName() string { return mailImageLibraryMorph }
func (MailImageLibrary) AttachRelations() []attach.Relation {
return []attach.Relation{{Name: "images", Many: true, Public: true}}
}
func (MailImageLibrary) Fillable() []string { return nil }
func (MailImageLibrary) Rules() map[string]string { return nil }
// mailImagesAdmin is the Mail images singleton screen.
type mailImagesAdmin struct {
mail *mailScreens
}
var (
_ pact.AdminController = mailImagesAdmin{}
_ pact.AdminPermissioned = mailImagesAdmin{}
_ pact.AdminSingleton = mailImagesAdmin{}
)
func (mailImagesAdmin) ID() string { return MailImagesControllerID }
func (mailImagesAdmin) ModelName() string { return `System\Models\MailImageLibrary` }
func (mailImagesAdmin) ConfigDir() string { return "controllers/mailimages" }
func (mailImagesAdmin) RequiredPermissions() []string {
return []string{PermissionManageMailLayouts}
}
func (mailImagesAdmin) NewRecord() any { return &MailImageLibrary{} }
// SingletonRecord returns the library host row, creating it when absent.
func (mailImagesAdmin) SingletonRecord(ctx context.Context, db *gorm.DB) (any, error) {
var row MailImageLibrary
err := db.WithContext(ctx).Order("id").Limit(1).Take(&row).Error
if err == nil {
return &row, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
row = MailImageLibrary{}
if err := db.WithContext(ctx).Create(&row).Error; err != nil {
return nil, err
}
return &row, nil
}
// injectLayoutCreateDefaults copies postcard's default layout into the create
// form defaults of the layouts controller, so the YAML carries no copy of it.
func injectLayoutCreateDefaults(reg *Registry, editor *postcard.Editor) {
if reg == nil || editor == nil {
return
}
cc, ok := reg.Get(MailLayoutsControllerID)
if !ok || cc == nil || cc.Form == nil {
return
}
file, ok := editor.Catalog().Layout(mailDefaultLayout)
if !ok {
return
}
set := map[string]string{
"content_html": file.HTML,
"content_text": file.Text,
"content_css": "",
}
for i := range cc.Form.Fields {
if raw, ok := set[cc.Form.Fields[i].Name]; ok {
encoded, err := json.Marshal(raw)
if err != nil {
continue
}
cc.Form.Fields[i].Default = &jsonScalar{raw: encoded}
}
}
}
// templateVersion is one row of a template's locale group.
type templateVersion struct {
ID uint
Code string
Locale *string
IsCustom bool
BaseHash *string
FileHash *string
}
// recordLocaleVariants lists the locale versions of the record's template
// for the switcher. It first gives the template's missing locales their rows
// (postcard.EnsureLocaleRows, idempotent), so a locale enabled since the last
// sync can be opened without a restart.
func (c mailTemplatesAdmin) recordLocaleVariants(ctx context.Context, tx *gorm.DB, record any) ([]RecordLocaleVariant, error) {
t, err := asMailTemplate(record)
if err != nil {
return nil, err
}
def, locales := c.mail.mailLocales(ctx, tx)
base := templateGroup(t, locales)
cat := c.mail.catalog()
if _, ok := cat.Template(base); ok {
// Under a savepoint: a failure leaves the show working.
if err := tx.Transaction(func(sp *gorm.DB) error {
return postcard.EnsureLocaleRows(ctx, sp, cat, def, locales, base)
}); err != nil {
moduleLog.WarnContext(ctx, "cabana: mail locale rows", "template", base, "error", err)
}
}
return c.mail.localeVariants(ctx, tx, t, base, def, locales)
}
// localeVariants are the locale versions of template base, t being the one
// shown, in switcher order: Default (the base file), then by locale code
// every locale with its own file, every other mail locale except the
// default, and any customized version of a locale that is no longer enabled.
func (m *mailScreens) localeVariants(ctx context.Context, db *gorm.DB, t *MailTemplate, base, def string, locales []string) ([]RecordLocaleVariant, error) {
var rows []templateVersion
q := db.Session(&gorm.Session{NewDB: true}).Table(postcard.TemplatesTable).
Select("id, code, locale, is_custom, base_hash, file_hash").
Where(postcard.TemplatesTable+".base_code = ? OR "+postcard.TemplatesTable+".code = ?", base, base)
if err := m.scopeTemplateVersions(q).Order("code").Scan(&rows).Error; err != nil {
return nil, err
}
cat := m.catalog()
enabled := map[string]bool{}
for _, l := range locales {
enabled[strings.ToLower(l)] = true
}
var head *RecordLocaleVariant
var rest []RecordLocaleVariant
for _, r := range rows {
_, fileBacked := cat.Template(r.Code)
v := RecordLocaleVariant{ID: r.ID, States: []string{}, Current: r.ID == t.ID}
if r.IsCustom {
v.States = append(v.States, m.message(ctx, mailLang+"state_customized", nil))
if mailOutdated(true, r.BaseHash, r.FileHash) {
v.States = append(v.States, m.message(ctx, mailLang+"state_outdated", nil))
}
}
if r.Code == base {
v.Label = m.message(ctx, mailLang+"template.locale_default", nil)
head = &v
continue
}
if r.Locale != nil {
v.Locale = *r.Locale
}
v.Label = v.Locale
if v.Label == "" {
v.Label = r.Code
}
if !fileBacked && !r.IsCustom && (!enabled[strings.ToLower(v.Locale)] || strings.EqualFold(v.Locale, def)) {
// A fallback row of a locale no longer enabled, not customized.
continue
}
rest = append(rest, v)
}
sort.SliceStable(rest, func(i, j int) bool { return rest[i].Locale < rest[j].Locale })
out := make([]RecordLocaleVariant, 0, len(rest)+1)
if head != nil {
out = append(out, *head)
}
return append(out, rest...), nil
}