interfaces

package
v0.1.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 54 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// FormMenuLink - a menu link's form (ref - the link's id).
	FormMenuLink = "menu_link"
	// FormBlock - a custom block's form (ref - the block's id).
	FormBlock = "block"
	// FormBlockPlacement - a block placement's form (ref - its id): a
	// custom block's page has it too.
	FormBlockPlacement = "block_placement"
	// FormTerm - a taxonomy term's form (ref - the term's id).
	FormTerm = "term"
	// FormSiteInformation - Site information (ref - entity.SiteTextRef).
	FormSiteInformation = "site_information"
	// FormView - a View display's settings (ref - its id): a modal's
	// form, Bootstrap's form layout rather than the settings rows.
	FormView = "view"
	// FormField - a content type's field's form (ref - the field
	// instance's id).
	FormField = "field"
)

The core's admin forms with module sections (FormSection.Form).

View Source
const (
	PathOwnerRoutes  = "routes"
	PathOwnerContent = "content"
	PathOwnerTerms   = "terms"
	PathOwnerViews   = "views"
)

Owners of the core's addresses (PathOwner's names).

View Source
const RecentChangesPath = "/admin/content/changes"

RecentChangesPath - the recent changes of the content (Content → Changes).

View Source
const RecentChangesPerPage = 50

RecentChangesPerPage - revisions on a page of the recent changes.

View Source
const RevisionsPerPage = 25

RevisionsPerPage - the history's page size.

View Source
const SearchMaxChars = 100

SearchMaxChars - the longest query searched; a longer one is cut (a query is matched with LIKE, as one substring, against every searched field).

View Source
const TwoFactorPath = "/me/two-factor"

TwoFactorPath - the user's own two-factor sign-in page.

Variables

View Source
var ErrNodeNotCopyable = errors.New("the node can't be copied")

ErrNodeNotCopyable - CopyNode's node can't be copied.

View Source
var OAuthProviderLabels = map[string]string{
	entity.OAuthProviderGoogle: "Google",
	entity.OAuthProviderVK:     i18n.N("VK"),
	entity.OAuthProviderYandex: i18n.N("Yandex"),
}

OAuthProviderLabels - the providers as the settings page and the login buttons name them.

Functions

func AbsoluteAssetURL

func AbsoluteAssetURL(base, uri string) string

AbsoluteAssetURL - uri absolute under base (an absolute http(s) URL as it is).

func AddAccountSettingsSection

func AddAccountSettingsSection(s AccountSettingsSection)

AddAccountSettingsSection registers a module's section of the "Account settings" page (called at startup; used only while the module is on).

func AddContentTypeSettings

func AddContentTypeSettings(s ContentTypeSettings)

AddContentTypeSettings registers a module's section of the content type form (called at startup; used only while the module is on).

func AddCreateLinks(fn func(ctx context.Context, user *entity.User, auth service.AuthService) []entity.CreatableMaterialLink)

AddCreateLinks registers a module's entries of the "Create content" menu for a signed-in user (called at startup; the hook checks its module is on and the user may create).

func AddFormSection

func AddFormSection(s FormSection)

AddFormSection registers a module's section of a core admin form (called at startup; used only while the module is on).

func AddNodeFormSaved

func AddNodeFormSaved(module string, fn func(ctx context.Context, node entity.Node, isNew bool) error)

AddNodeFormSaved registers fn, called while module is on after a node's own form (create or edit) saved it, in the save's transaction: its error fails the save. Not called for changes made elsewhere - the bulk actions, publishing, the schedule, a copy.

func AddNodePage

func AddNodePage(module string, fn func(ctx context.Context, node entity.Node) NodePageParts)

AddNodePage registers a module's part of node pages (called at startup; it runs only while the module is on).

func AddNodeSettings

func AddNodeSettings(s NodeSettings)

AddNodeSettings registers a module's section of node forms (called at startup; used only while the module is on).

func AddPageData

func AddPageData(fn func(r *http.Request, data map[string]any))

AddPageData registers a module's addition to every page's data (e.g. what its page_end partial needs); called at startup. A module needing the reCAPTCHA script on every page sets data["recaptchaScript"].

func AddPathOwner

func AddPathOwner(name string, answers func(ctx context.Context, path string) (bool, error))

AddPathOwner registers answers, telling whether name (the core's PathOwner* or a module's name) answers path (no leading "/"); one registered under the same name before is replaced.

func AddProfileTab

func AddProfileTab(t ProfileTab)

AddProfileTab registers a module's profile tab (called at startup, from Wire); its path is reserved for the user_tab displays (entity.ReserveProfileTabPath).

func AddSitemapPaths

func AddSitemapPaths(fn func(ctx context.Context) ([]string, error))

AddSitemapPaths registers a module's pages for the sitemap (paths from the site root, escaped; called at startup - the hook checks its module is on).

func AddStatusCounts

func AddStatusCounts(r *http.Request, data map[string]any)

AddStatusCounts - the warning bar's counts on an admin page, for those who may open the status report.

func AddTermPage

func AddTermPage(module string, fn func(ctx context.Context, term entity.TaxonomyTerm) any)

AddTermPage registers a module's part of term pages: fn's result is the data of its templates there (.moduleTerm.<module>, e.g. its "term_actions_<module>"). Called at startup; it runs only while the module is on.

func AddUserMenuCount

func AddUserMenuCount(data map[string]any, n int)

AddUserMenuCount adds n to the number on the user menu's toggle (data["userMenuCount"]: the core's header and admin header show it when it is above 0) - e.g. a module's unread items, from its AddPageData.

func AddUserSettingsSection

func AddUserSettingsSection(s UserSettingsSection)

AddUserSettingsSection registers a module's section of the profile form (called at startup; used only while the module is on).

func ApplyPaginationToPageSEO

func ApplyPaginationToPageSEO(seo *entity.PageSEO, canonicalPath string, page int, query url.Values)

ApplyPaginationToPageSEO resets Canonical and OGURL and adds a page suffix to Title for page > 1, for SEO built separately (e.g. term pages).

func AsGuest

func AsGuest(ctx context.Context) (context.Context, error)

AsGuest - ctx whose node and comment queries see only what a guest may view: for what is public by nature and kept by any cache, whoever asks (feeds, the sitemap).

func AsGuestHandler

func AsGuestHandler(next http.Handler) http.Handler

AsGuestHandler serves next as for a guest (AsGuest); a failed check is a 500.

func Captcha

func Captcha() *service.CaptchaService

Captcha - the reCAPTCHA in effect (nil - none set).

func ChangeNode

func ChangeNode(ctx context.Context, nodeID int, user *entity.User, change func(ctx context.Context) error) error

ChangeNode runs change of the node nodeID by user in one transaction, recorded in its history (a revision, the action log, the published hooks) as the bulk actions' are.

func CopyNode

func CopyNode(ctx context.Context, nodeID int, user *entity.User, title string) (int, error)

CopyNode - a copy of the node nodeID by user (DynamicContentController. CopyNode): its id.

func EscapePathSegments

func EscapePathSegments(rel string) string

EscapePathSegments - a relative path with each segment URL-escaped.

func ExpiredFormMessage

func ExpiredFormMessage(r *http.Request) string

ExpiredFormMessage - what a visitor whose form has expired is told.

func FieldUploadTokens

func FieldUploadTokens(contentType string, userID int) files.FileDirectoryTokens

FieldUploadTokens - token values for a field upload's directory (files.ResolveFileDirectory): now, the node's content type, the uploading user.

func FormPreviewPath

func FormPreviewPath(contentType string, nodeID int) string

FormPreviewPath - where the form of a new item of type (nodeID 0) or of the item nodeID sends its preview (the Preview button's formaction).

func ImageMIME

func ImageMIME(uri string) string

ImageMIME - the media type of the image at uri by its extension (JPEG when none of WebP, PNG, GIF).

func MailBaseURL

func MailBaseURL() string

MailBaseURL - the site's origin for links in e-mails ("" - the site URL isn't set), never the request's host (mailBaseURL).

func MaxFileSizeBytesFromMBForm

func MaxFileSizeBytesFromMBForm(raw string) int

MaxFileSizeBytesFromMBForm - a size limit typed in megabytes in an admin form, in bytes.

func ModuleNodeData

func ModuleNodeData(ctx context.Context, node entity.Node) map[string]any

ModuleNodeData - the modules' data for a node's page (.moduleNode: what their "node_actions_<module>" and other templates read), for a module's own page of its content type (a poll, a form).

func ModuleTermData

func ModuleTermData(ctx context.Context, term entity.TaxonomyTerm) map[string]any

ModuleTermData - the enabled modules' data for a term's page, by module.

func NotFoundBreadcrumbs

func NotFoundBreadcrumbs() []entity.BreadcrumbItem

NotFoundBreadcrumbs - the 404 page's trail (no JSON-LD). Other pages' trails come from service.BreadcrumbService via the BaseController helpers below. No request context here: labels use the site default language.

func PageSEO

func PageSEO(provider SEOProvider) entity.PageSEO

PageSEO builds a PageSEO from an entity's data.

func PageSEOForHome

func PageSEOForHome(site *entity.SiteInformation, page int) entity.PageSEO

PageSEOForHome - the home page: title is "site_name | slogan", description is the slogan. For page > 1, canonical and og:url are https://…/?page=N.

func PageSEOForList

func PageSEOForList(title, path string) entity.PageSEO

PageSEOForList builds PageSEO for list pages without pagination in the URL. title is the page title; path is the page URL path (e.g. "/articles").

func PageSEOForPaginatedList

func PageSEOForPaginatedList(title, path string, page int, query url.Values) entity.PageSEO

PageSEOForPaginatedList - PageSEO for paginated lists (canonical/og:url, title on page 2+). path is the path without query (as r.URL.Path).

func PageSEOForProfileEdit

func PageSEOForProfileEdit(u *entity.User, path string) entity.PageSEO

PageSEOForProfileEdit - SEO for /me/edit and /user/{id}/edit.

func PageSEOForUserProfile

func PageSEOForUserProfile(u *entity.User, path string) entity.PageSEO

PageSEOForUserProfile - SEO for /me and /users/{alias} (its tabs: PageSEOForUserProfileTab).

func PageSEOForUserProfileTab

func PageSEOForUserProfileTab(u *entity.User, tabLabel, path string) entity.PageSEO

PageSEOForUserProfileTab - a profile's View tab (user_tab display).

func ParseExtensionsForm

func ParseExtensionsForm(raw string) []string

ParseExtensionsForm - the file extensions typed in an admin form (space separated, without dots, lowercase), forbidden ones dropped.

func PathOwner

func PathOwner(ctx context.Context, path, except string) (string, error)

PathOwner - the name of the first owner but except that answers path ("" - none): the address is free for except. A disabled module's addresses are free.

func PublicBaseURL

func PublicBaseURL(r *http.Request) string

PublicBaseURL - the site's canonical origin (the site URL, else as the request reached it), for absolute links in feeds.

func RSSPostURL

func RSSPostURL(base string, n entity.Node) string

RSSPostURL - n's absolute address under base (entity.Node.URL: a module type's path prefix included).

func ReadRequiredFields

func ReadRequiredFields(ctx context.Context, fields *accounts.UserFieldService, get func(string) string) (map[int]string, string, error)

ReadRequiredFields reads the required profile fields of a form creating a user: their values, or the message of the one to correct.

func RedirectToStore

func RedirectToStore(w http.ResponseWriter, r *http.Request, base, key string)

RedirectToStore sends the visitor to the file key at base, the address the public files' store serves its files at itself (paths.PublicStoreURL), with the request's query (a derivative's ?v=…). Browsers and CDNs keep the redirect for a day.

func RequestThemeRegions

func RequestThemeRegions(ctx context.Context, logger *slog.Logger) entity.ThemeInfo

RequestThemeRegions - the regions of the theme ctx renders in (a previewed one, else the active one).

func RequiredFieldInputs

func RequiredFieldInputs(r *http.Request, fields *accounts.UserFieldService) []entity.UserFieldValue

RequiredFieldInputs - the required profile fields with r's submitted values: the inputs of a form creating a user.

func ResetModuleHooks

func ResetModuleHooks()

ResetModuleHooks drops every module hook registered so far (AddPageData, AddNodePage, AddTermPage, AddContentTypeSettings, AddAccountSettingsSection, AddUserSettingsSection, AddNodeSettings, AddNodeFormSaved, AddFormSection, SetNodeWorkflow, AddCreateLinks, AddSitemapPaths, AddProfileTab, the modules' View criteria, the action listeners, the 404 hooks, the dashboard blocks, the published-node hooks). The app's wiring calls it before the modules register theirs, so wiring the app again (a test serving another database) doesn't keep hooks bound to the previous one.

func SaveAccountSettingsSections

func SaveAccountSettingsSections(ctx context.Context, r *http.Request) error

SaveAccountSettingsSections stores the enabled modules' sections of the submitted "Account settings" page.

func SaveContentTypeSettings

func SaveContentTypeSettings(ctx context.Context, ct entity.ContentTypeDef, r *http.Request) error

SaveContentTypeSettings stores the enabled modules' sections of the submitted content type form.

func SaveFieldFileWithPolicy

func SaveFieldFileWithPolicy(ctx context.Context, fileUploadService fieldFileUploader, fileRepo entity.FileRepository, file multipart.File, header *multipart.FileHeader, tokens files.FileDirectoryTokens, field entity.FieldInstanceDef) (int, error)

SaveFieldFileWithPolicy saves a generic (non-image) upload for a FieldTypeFile field, validated against the field's extension and size settings (see files.FileUploadService.UploadFileField). Unlike image uploads it keeps entity.File.OriginalFilename for the download link.

func SaveFieldImageWithPolicy

func SaveFieldImageWithPolicy(ctx context.Context, fileUploadService fieldImageUploader, fileRepo entity.FileRepository, file multipart.File, header *multipart.FileHeader, tokens files.FileDirectoryTokens, field entity.FieldInstanceDef) (int, error)

SaveFieldImageWithPolicy saves an image upload for a specific FieldTypeImage field, validated against that field's upload settings (see files.FileUploadService.ValidateAndProcessImageField) rather than only the sitewide policy. Used for field values and field default images.

func SaveFormSections

func SaveFormSections(ctx context.Context, form, ref string, r *http.Request) error

SaveFormSections stores the enabled modules' sections of the submitted form for ref.

func SetCaptcha

func SetCaptcha(s *service.CaptchaService)

SetCaptcha sets the reCAPTCHA service (wiring).

func SetErrorPageRenderer

func SetErrorPageRenderer(f func(w http.ResponseWriter, r *http.Request, status int) bool)

SetErrorPageRenderer sets the renderer of the configured 404/403 pages.

func SetGuestVisitor

func SetGuestVisitor(f func(ctx context.Context) (entity.ContentVisitor, error))

SetGuestVisitor sets what of the content a guest may not view (wiring: service.ContentAccess.Visitor for nil).

func SetNodeCopier

func SetNodeCopier(fn func(ctx context.Context, nodeID int, user *entity.User, title string) (int, error))

SetNodeCopier sets what copies a node for the modules: the content form's controller (DynamicContentController.CopyNode), at startup.

func SetNodeTracker

func SetNodeTracker(fn func(ctx context.Context, nodeID int, user *entity.User, change func(ctx context.Context) error) error)

SetNodeTracker sets what records a change of a node (the node history's Track), at startup.

func SetNodeWorkflow

func SetNodeWorkflow(w NodeWorkflow)

SetNodeWorkflow sets the site's editorial workflow (one; called at startup, used only while its module is on); the core's own publishing leaves its types' items alone (service.PublishingManaged).

func SetOAuthProviders

func SetOAuthProviders(providers func() []string)

SetOAuthProviders sets the source of the OAuth providers offered on the login and registration pages (wiring).

func SetSiteJSONLD

func SetSiteJSONLD(fn func(ctx context.Context) template.JS)

SetSiteJSONLD gives the front page its schema.org markup (wiring).

func SetStatusReport

func SetStatusReport(r *service.StatusReport, s StatusSources)

SetStatusReport sets the status checks and sources (wiring).

func SetTimeouts

func SetTimeouts(dbQuery, serverWrite time.Duration)

SetTimeouts sets the handlers' timeouts from the config: the database work of a page and the server's write timeout (the time a response has; StepBudget is derived from it).

func StepBudget

func StepBudget() time.Duration

StepBudget - how long one request of a step-by-step job (deleting a user's or a module's content) may work before answering "go on": half the server's write timeout, so the answer always gets out.

func ThemeRegions

func ThemeRegions(logger *slog.Logger) entity.ThemeInfo

ThemeRegions - the active theme's regions (the rendered layout).

func ThemeRegionsFor

func ThemeRegionsFor(logger *slog.Logger, themeKey string) entity.ThemeInfo

ThemeRegionsFor - the regions of the theme with placement key themeKey (theme.yaml, themes.LoadInfoFor); an error is logged and leaves no regions, so the block pages refuse to place anything rather than guess.

func TranslatedRegionLabels

func TranslatedRegionLabels(ctx context.Context, theme entity.ThemeInfo) map[entity.Region]string

TranslatedRegionLabels - theme.Labels() translated: the regions' labels of theme.yaml (English, in the engine's or the theme's catalog) and the "Hidden" one (entity.RegionDisabled).

func TruncateMeta

func TruncateMeta(s string, n int) string

TruncateMeta - s cut for a meta description of at most n characters.

Types

type AccountSettingsSection

type AccountSettingsSection struct {
	Module string
	Load   func(ctx context.Context) (any, error)
	Save   func(ctx context.Context, r *http.Request) error
}

AccountSettingsSection - a module's section of the "Account settings" page (its settings of accounts), rendered by its template "account_settings_<module>" (moduleHook) from .moduleSettings.<module>, what Load returns. Save stores the submitted form once the page's own settings are saved.

type BaseController

type BaseController struct {
	// contains filtered or unexported fields
}

BaseController holds dependencies and helpers shared by all controllers.

func NewBaseController

func NewBaseController(d BaseDeps) *BaseController

NewBaseController - the base of a controller (embedded by each).

func (*BaseController) AddFormSectionsData

func (c *BaseController) AddFormSectionsData(ctx context.Context, data map[string]any, form, ref string)

AddFormSectionsData puts form's sections for ref in a page's data (.moduleForms.<form>.<module>).

func (*BaseController) AdminPageData

func (c *BaseController) AdminPageData(r *http.Request) map[string]any

AdminPageData - the common data of an admin page (a service page: the theme decides what it leaves out, see data["servicePage"]).

func (*BaseController) ApplyEditorPageSEOFromTitle

func (c *BaseController) ApplyEditorPageSEOFromTitle(data map[string]any, r *http.Request)

ApplyEditorPageSEOFromTitle sets data["pageSEO"] from data["title"] (create/edit forms).

func (*BaseController) AuthService

func (c *BaseController) AuthService() service.AuthService

AuthService - the authentication and permissions service.

func (*BaseController) CommentsService

func (c *BaseController) CommentsService() service.CommentsService

CommentsService returns the comments service for use by embedding controllers

func (*BaseController) CreateMaterialsHub

func (c *BaseController) CreateMaterialsHub(w http.ResponseWriter, r *http.Request)

CreateMaterialsHub renders GET /create: list of material types the user may create.

func (*BaseController) DBContext

DBContext derives a request-scoped context bounded by the database query timeout (config timeouts.database_query, SetTimeouts), for handlers that cap how long their database work may run.

func (*BaseController) EditDeletePermissions

func (c *BaseController) EditDeletePermissions(ctx context.Context, node *entity.Node, user *entity.User) (canEdit, canDelete bool)

EditDeletePermissions reports whether user may edit/delete node. An anonymous user (nil) can do neither.

func (*BaseController) EditorPageSEO

func (c *BaseController) EditorPageSEO(r *http.Request, actionTitle string) entity.PageSEO

EditorPageSEO fills site_name from settings (if the repository is set on BaseController).

func (*BaseController) GetCommonData

func (c *BaseController) GetCommonData(r *http.Request) map[string]any

GetCommonData - the data every page shares (GetCommonDataWithUser) for r's signed-in user.

func (*BaseController) GetCommonDataWithUser

func (c *BaseController) GetCommonDataWithUser(r *http.Request, user *entity.User) map[string]any

GetCommonDataWithUser builds the shared header/sidebar data; user is the already-loaded user (or nil), so GetCurrentUser isn't called again.

func (*BaseController) GetCurrentUser

func (c *BaseController) GetCurrentUser(r *http.Request) (*entity.User, error)

GetCurrentUser returns the current user from the session.

func (*BaseController) GetPageNumber

func (c *BaseController) GetPageNumber(r *http.Request) int

GetPageNumber reads the page number from the query string: 1 when it's missing, not a number, below 1 or above maxPageNumber.

func (*BaseController) IsNodeVisible

func (c *BaseController) IsNodeVisible(ctx context.Context, node *entity.Node, user *entity.User) bool

IsNodeVisible reports whether user may see node - the gate every detail page applies (AuthService.CanViewNode): its type lets them view its content (or they may edit it), and it is public - published and not on moderation - or they may see unpublished content, or it is theirs on moderation.

func (*BaseController) IsViewVisible

func (c *BaseController) IsViewVisible(ctx context.Context, view *entity.ViewDisplayDef, user *entity.User) bool

IsViewVisible mirrors IsNodeVisible for entity.ViewDisplayDef: enabled (Status == 1), or the user is an admin or moderator previewing a disabled View's page (hidden from everyone else).

func (*BaseController) LoadAccountSettingsSections

func (c *BaseController) LoadAccountSettingsSections(ctx context.Context) map[string]any

LoadAccountSettingsSections - the enabled modules' data of the "Account settings" page's sections (a failing one is left out).

func (*BaseController) LoadContentTypeSettings

func (c *BaseController) LoadContentTypeSettings(ctx context.Context, ct entity.ContentTypeDef) map[string]any

LoadContentTypeSettings - the enabled modules' data of the content type form's sections (a failing one is left out).

func (*BaseController) LoadFormSections

func (c *BaseController) LoadFormSections(ctx context.Context, form, ref string) map[string]any

LoadFormSections - the enabled modules' data of form's sections for ref (a failing one is left out).

func (*BaseController) LogFailure

func (c *BaseController) LogFailure(err error, msg string, args ...any)

LogFailure logs an error the handler deals with itself (a redirect with an error, a JSON answer, a fallback): a missing record at debug level (the visitor's mistake or a stale link), anything else as an error. Nil - nothing. The services wrap their errors with what they were doing; the handler is where an error is logged, once.

func (*BaseController) Logger

func (c *BaseController) Logger() *slog.Logger

Logger - the controller's logger.

func (*BaseController) MayViewRevisions

func (c *BaseController) MayViewRevisions(ctx context.Context, node *entity.Node, user *entity.User) bool

MayViewRevisions - user may see the history of node: "view content revisions" and editing the node.

func (*BaseController) NodeRepo

func (c *BaseController) NodeRepo() entity.NodesRepository

NodeRepo - the nodes repository.

func (*BaseController) PathID

func (c *BaseController) PathID(r *http.Request) (int, bool)

PathID parses the "id" path value as a positive int; ok is false if missing or invalid (callers should respond with RenderNotFound).

func (*BaseController) RenderBadForm

func (c *BaseController) RenderBadForm(w http.ResponseWriter, r *http.Request)

RenderBadForm - the submitted form couldn't be read (a broken or cut body).

func (*BaseController) RenderBadRequest

func (c *BaseController) RenderBadRequest(w http.ResponseWriter, r *http.Request, message string)

RenderBadRequest - RenderRejected with 400.

func (*BaseController) RenderExpiredForm

func (c *BaseController) RenderExpiredForm(w http.ResponseWriter, r *http.Request)

RenderExpiredForm - the form's CSRF token doesn't match the session (the page was open too long or the session ended).

func (*BaseController) RenderForbidden

func (c *BaseController) RenderForbidden(w http.ResponseWriter, r *http.Request)

RenderForbidden sends HTTP 403 and renders the site access-denied page: the configured 403 page (Site information), else errors/forbidden.html.

func (*BaseController) RenderLoadFailure

func (c *BaseController) RenderLoadFailure(w http.ResponseWriter, r *http.Request, err error, msg string, args ...any)

RenderLoadFailure answers a failed load of what the page shows: a missing record is the visitor's 404 (logged at debug level), any other error the server's - logged and a 500, not hidden behind a 404.

func (*BaseController) RenderNotFound

func (c *BaseController) RenderNotFound(w http.ResponseWriter, r *http.Request)

RenderNotFound sends HTTP 404 and renders the site not-found HTML page.

func (*BaseController) RenderOrFail

func (c *BaseController) RenderOrFail(w http.ResponseWriter, r *http.Request, tmpl string, data map[string]any) bool

RenderOrFail renders tmpl with data to w. On error it logs the failure, writes a 500 via httputil.TemplateExecutionError and returns false; callers should return immediately since a response has been written.

func (*BaseController) RenderRejected

func (c *BaseController) RenderRejected(w http.ResponseWriter, r *http.Request, status int, message string)

RenderRejected sends status and renders errors/bad_request.html: what the visitor sent can't be taken (a form that can't be read, has expired or lacks what's required); message, in the visitor's language, says why, with a link back to the page they came from.

func (*BaseController) RenderTooLarge

func (c *BaseController) RenderTooLarge(w http.ResponseWriter, r *http.Request)

RenderTooLarge sends HTTP 413 and renders errors/too_large.html: the request (a form with its files) is past the size the site reads.

func (*BaseController) RequireVisibleOrModerator

func (c *BaseController) RequireVisibleOrModerator(w http.ResponseWriter, r *http.Request, node *entity.Node, user *entity.User) bool

RequireVisibleOrModerator renders 404 and returns false if user may not see node (IsNodeVisible). Callers should return immediately when this returns false.

func (*BaseController) SetChildTrail

func (c *BaseController) SetChildTrail(data map[string]any, parents []entity.BreadcrumbItem, title string)

SetChildTrail - the breadcrumbs of a page under parents.

func (*BaseController) SetCreateFormTrail

func (c *BaseController) SetCreateFormTrail(data map[string]any, title string)

SetCreateFormTrail - the breadcrumbs of a create form under /create.

func (*BaseController) SetLogger

func (c *BaseController) SetLogger(l *slog.Logger)

SetLogger replaces the controller's logger (e.g. with the module's component attribute).

func (*BaseController) SetNodeRefTrail

func (c *BaseController) SetNodeRefTrail(ctx context.Context, data map[string]any, node entity.Node)

SetNodeRefTrail - the breadcrumbs of a node page without loaded fields.

func (*BaseController) SetNodeSubpageTrail

func (c *BaseController) SetNodeSubpageTrail(ctx context.Context, data map[string]any, node entity.Node, title string, extra ...entity.BreadcrumbItem)

SetNodeSubpageTrail - the breadcrumbs of a node's subpage (title under the node).

func (*BaseController) SetPathTrail

func (c *BaseController) SetPathTrail(data map[string]any, path, title string)

SetPathTrail - the breadcrumbs of a page at path (by the menus), or just its title.

func (*BaseController) SetViewTrackNID

func (c *BaseController) SetViewTrackNID(data map[string]any, node entity.Node)

SetViewTrackNID sets data["viewTrackNID"] for client-side view POST when counting is enabled and node is public.

func (*BaseController) Store

func (c *BaseController) Store() *sessions.CookieStore

Store - the session store (CSRF checks of JSON requests).

func (*BaseController) TemplateService

func (c *BaseController) TemplateService() service.TemplateService

TemplateService - the template renderer.

func (*BaseController) UserService

func (c *BaseController) UserService() service.UserService

UserService - the users service.

type BaseDeps

type BaseDeps struct {
	Auth      service.AuthService
	Templates service.TemplateService
	Users     service.UserService
	Comments  service.CommentsService
	// Cache - the blocks' cache (nil - the pages render without blocks).
	Cache           BlockCache
	ViewCounting    service.ViewCountingService
	Store           *sessions.CookieStore
	Logger          *slog.Logger
	SiteInformation entity.SiteInformationRepository
	Nodes           entity.NodesRepository
	// Breadcrumbs - the pages' trails (nil - the pages render none).
	Breadcrumbs *service.BreadcrumbService
}

BaseDeps - what every controller's base needs: the wiring builds it once and passes it to each controller's constructor.

type BlockCache

type BlockCache interface {
	SidebarDataFor(ctx context.Context) service.SidebarData
	ViewBlockContentFor(ctx context.Context, zone *time.Location) map[int]template.HTML
	ViewBlockPage(ctx context.Context, view entity.ViewDisplayDef, placementID, page int, zone *time.Location) (template.HTML, bool, error)
}

BlockCache - what of the blocks' cache (service.CacheService) the pages read: their sidebar data, View blocks and a View block's pages.

type CommentController

type CommentController struct {
	*BaseController
	// contains filtered or unexported fields
}

CommentController serves the comments' pages: a comment's link, the recent comments, a node's comments, posting, editing and deleting one.

func NewCommentController

func NewCommentController(deps BaseDeps) *CommentController

NewCommentController creates a CommentController on deps.

func (*CommentController) Create

Create handles POST /comment/create.

func (*CommentController) Delete

Delete handles POST /comment/{id}/delete.

func (*CommentController) DeleteConfirm

func (c *CommentController) DeleteConfirm(w http.ResponseWriter, r *http.Request)

DeleteConfirm handles GET /comment/{id}/delete - the confirmation page.

func (*CommentController) Edit

Edit handles GET/POST /comment/{id}/edit.

func (*CommentController) LoadComments

func (c *CommentController) LoadComments(w http.ResponseWriter, r *http.Request)

LoadComments handles AJAX requests to load comments for a node

func (*CommentController) Recent

Recent renders GET /comments/recent - site-wide published comments with pagination.

func (*CommentController) Redirect

func (c *CommentController) Redirect(w http.ResponseWriter, r *http.Request)

Redirect handles requests to /comment/{id} and redirects to the appropriate material page with the correct page number and comment anchor

type ContentTypeSettings

type ContentTypeSettings struct {
	Module string
	Load   func(ctx context.Context, ct entity.ContentTypeDef) (any, error)
	Save   func(ctx context.Context, ct entity.ContentTypeDef, r *http.Request) error
}

ContentTypeSettings - a module's section of the content type form, rendered by its template "content_type_settings_<module>" (moduleHook) from .moduleSettings.<module>, what Load returns. Save stores the submitted form once the type is saved.

type DynamicContentController

type DynamicContentController struct {
	*BaseController
	// contains filtered or unexported fields
}

DynamicContentController serves every admin-created content type through one shared handler set. It resolves the content type per request (from the "type" path value on create, from the node's Type otherwise) and builds the form adapter, service and repository for that type's fields on each request.

func NewDynamicContentController

func NewDynamicContentController(deps BaseDeps, d DynamicContentDeps) *DynamicContentController

NewDynamicContentController creates a DynamicContentController on deps and d.

func (*DynamicContentController) Clone

Clone handles POST /node/{id}/clone: a copy of the node (who may edit it and create its type's content) - its fields' values, the blocks of its blocks fields copied too, its flags, comment mode and view roles - titled "Copy of …", unpublished, by the user, with an address of its own; its form opens.

func (*DynamicContentController) CopyNode

func (c *DynamicContentController) CopyNode(ctx context.Context, nodeID int, user *entity.User, title string) (int, error)

CopyNode - a copy of the node nodeID of an admin-created type by user, titled title ("" - "Copy of …"), unpublished, in ctx's language: its id (ErrNodeNotCopyable - a field set's node or a module's type's).

func (*DynamicContentController) CreateForm

CreateForm renders GET /create/{type} for an admin-created type.

func (*DynamicContentController) CreatePreview

func (c *DynamicContentController) CreatePreview(w http.ResponseWriter, r *http.Request)

CreatePreview handles POST /create/{type}/preview: the new item of the type its form describes (CreateSubmit's), unsaved. A type without preview (ContentTypeDef.NoPreview) - not found.

func (*DynamicContentController) CreateSubmit

func (c *DynamicContentController) CreateSubmit(w http.ResponseWriter, r *http.Request)

CreateSubmit handles POST /create/{type} for an admin-created type: the form checked, the node created with its slug (nodeSlug), its SEO, terms and the modules' settings saved (saveContentExtras) in one transaction; to the new node.

func (*DynamicContentController) Delete

Delete handles POST /node/{id}/delete for a node of an admin-created type (the node - the access middleware's, NodeAccessByIDMiddleware): it goes to the trash.

func (*DynamicContentController) Detail

Detail renders the public detail page for a node of an admin-created type (web/templates/dynamic/page.html).

func (*DynamicContentController) EditForm

EditForm renders GET /node/{id}/edit for a node of an admin-created type.

func (*DynamicContentController) EditPreview

EditPreview handles POST /node/{id}/edit/preview: the item as its edit form would save it (Save's, applyEdit), unsaved; what the form doesn't touch (its address, its counts, its last change) as saved. A type without preview - not found.

func (*DynamicContentController) FrontFeedItems

func (c *DynamicContentController) FrontFeedItems(ctx context.Context, machineName string, limit int) ([]entity.TeaserItem, entity.FeedImage, error)

FrontFeedItems - the first limit items of the front page feed View (RSS), as teaser items, and the View's first image field: its machine_name and image style ("" - the original).

func (*DynamicContentController) MediaPick

MediaPick handles GET /api/media/pick?field=<field id>&q=&page=: the media library's files the field may take, the newest first, found by name or alt text - JSON {"items": [mediaPickerItem…], "more": bool}.

func (*DynamicContentController) Preview

Preview handles GET /preview/{token}: the content item a preview link shows (service.PreviewLinks), its page as it would be, to whoever has the link - published or not, whatever its view roles - while the link works; not indexed, kept by no cache. An unknown or expired link, an item in the trash or of a module's type - not found.

func (*DynamicContentController) PreviewLinkAction

func (c *DynamicContentController) PreviewLinkAction(w http.ResponseWriter, r *http.Request)

PreviewLinkAction handles POST /node/{id}/preview-link (who may edit the node): action=create - a new link (an earlier one gone), JSON {"url", "expires" (RFC 3339)}; action=revoke - none left, JSON {}.

func (*DynamicContentController) ProfileTabCount

func (c *DynamicContentController) ProfileTabCount(ctx context.Context, view entity.ViewDisplayDef, userID int) (int, error)

ProfileTabCount - how many results a user_tab display has for the profile of userID (for the tab label).

func (*DynamicContentController) RenderFrontFeed

func (c *DynamicContentController) RenderFrontFeed(ctx context.Context, machineName string, page int, basePath string, query url.Values) (template.HTML, bool, error)

RenderFrontFeed renders the front page feed - the View named by SiteInformation.FrontFeedView - with its pager; ok is false when there is no such enabled View.

func (*DynamicContentController) RenderProfileTab

func (c *DynamicContentController) RenderProfileTab(ctx context.Context, view entity.ViewDisplayDef, userID, page int, basePath string, query url.Values) (template.HTML, int, error)

RenderProfileTab renders a user_tab display (entity.ViewDisplayTypeUserTab) for the profile of userID - the created_by contextual filter is that user - as the View's own list markup with pagination (basePath and query build the page links). Returns the total number of results.

func (*DynamicContentController) Save

Save handles POST /node/{id}/edit for a node of an admin-created type: as CreateSubmit, over the node's own values (applyEdit); the old address redirects to a changed slug.

func (*DynamicContentController) ViewPageFallback

func (c *DynamicContentController) ViewPageFallback(w http.ResponseWriter, r *http.Request) bool

ViewPageFallback serves an admin-created View page (GET /{view.URLPath}) when the slug lookup finds no node. It adds only an indexed lookup to the 404 path. url_path may have several segments; literal routes in router.go always take precedence, so a View can't shadow them.

func (*DynamicContentController) ViewPreview

ViewPreview handles POST /admin/config/views/{id}/preview, the admin live preview. Filters, fields and sorts are read from the DB (the admin UI saves them immediately); only the page settings in the request body may be unsaved.

type DynamicContentDeps

type DynamicContentDeps struct {
	ContentTypeService service.ContentTypeService
	TaxonomyService    service.TaxonomyService
	NodeService        service.NodesService
	FileUploadService  files.FileUploadService
	FileRepo           entity.FileRepository
	UnitOfWork         entity.UnitOfWork
	DynamicRepoFactory func(entity.ContentTypeDef, entity.FieldInstanceDefs) entity.DynamicContentRepository
	ViewService        views.Service
	TextFormatService  service.TextFormatService
	ContentTypeRepo    entity.ContentTypeRepository
	NodeDeleter        *service.NodeDeleteService
	Redirects          service.RedirectService
	NodePaths          *service.NodePathService
	Teasers            *service.TeaserBuilder
	SEO                *service.SEOService
	// Revisions - the history of the types that keep one.
	Revisions *service.NodeRevisionService
	// Roles - the site's roles, those a node's view may be given to
	// (entity.Node.ViewRoles); AccessChanged - called when a node's view
	// roles change (who views what read again, the cached blocks
	// rendered again).
	Roles         func(ctx context.Context) (entity.Roles, error)
	AccessChanged func()
	// PreviewLinks - the links showing an item to whoever has them.
	PreviewLinks *service.PreviewLinks
	// Media - the media library an image or file field picks from.
	Media *service.MediaLibrary
	// CommentSettings - whether a page has its comments in its HTML
	// (CommentSettings.LoadWithPage).
	CommentSettings entity.CommentSettingsRepository
}

DynamicContentDeps - what NewDynamicContentController needs besides the BaseDeps.

type EmbedsController

type EmbedsController struct {
	*BaseController
	// contains filtered or unexported fields
}

EmbedsController - the editor's "Insert" window and the cards over the embed tags in a text (service.EmbedPickerKinds, SearchEmbeds, DescribeEmbed): JSON for whoever may write in a text format with "Embeds" on, the things as they may see them.

func NewEmbedsController

func NewEmbedsController(deps BaseDeps, formats service.TextFormatService) *EmbedsController

NewEmbedsController - the controller over the text formats (who may embed).

func (*EmbedsController) Describe

func (c *EmbedsController) Describe(w http.ResponseWriter, r *http.Request)

Describe handles GET /api/embeds/describe?tag=<kind>:<name>&tag=…: {"items": {"<kind>:<name>": {...}}}, the window's preview and the cards; a tag of nothing (missing, unknown) is left out.

func (*EmbedsController) Kinds

Kinds handles GET /api/embeds/kinds: {"kinds": [{name, label}]}, the window's choice.

func (*EmbedsController) Search

func (c *EmbedsController) Search(w http.ResponseWriter, r *http.Request)

Search handles GET /api/embeds/search?kind=&q=: {"options": [...]}, the window's list.

type FormSection

type FormSection struct {
	Module string
	Form   string
	Load   func(ctx context.Context, ref string) (any, error)
	Save   func(ctx context.Context, ref string, r *http.Request) error
}

FormSection - a module's section of one of the core's admin forms (Form - its name: FormMenuLink…) for a thing of it (ref - its id), rendered by the module's template "form_<Form>_<module>" (moduleHook) from .moduleForms.<Form>.<module>, what Load returns (nil - nothing to show); Save stores the submitted form once the form saved the thing. A page may hold several forms' sections (a custom block's: the block's and its placement's).

type IndexController

type IndexController struct {
	*BaseController
	// contains filtered or unexported fields
}

IndexController serves the home page and the pages of blocks loaded after the page: lazy block placements and View blocks' pages.

func NewIndexController

func NewIndexController(deps BaseDeps, d IndexDeps) *IndexController

NewIndexController creates an IndexController on deps and d.

func (*IndexController) BlockPlacementHTML

func (c *IndexController) BlockPlacementHTML(w http.ResponseWriter, r *http.Request)

BlockPlacementHTML - GET /api/block-placement/{id}: the content of a lazy block placement (entity.BlockPlacementDef.Lazy), which the page rendered as a placeholder (partials/region_blocks.html) and app.js loads when it scrolls near the viewport. Only lazy placements are served. The page decided the scope (its node and path); the roles condition is checked again, since this endpoint is public. ?path= is the page's own path for blocks that look at it.

func (*IndexController) Index

Index - GET /: the home page, with the front page feed View chosen in site information (SiteInformation.FrontFeedView) at its ?page=N.

func (*IndexController) ViewBlockPage

func (c *IndexController) ViewBlockPage(w http.ResponseWriter, r *http.Request)

ViewBlockPage - GET /api/view-block/{id}?page=N: a page of a paged View block (placement id) as JSON {"html": …}, the list and its pager that app.js swaps into the block (the block itself holds the first page, from the cache). The page decided where the block shows; the roles condition is checked again, since this endpoint is public.

type IndexDeps

type IndexDeps struct {
	// FrontFeed renders the front page feed View.
	FrontFeed frontFeedRenderer
}

IndexDeps - what NewIndexController needs besides the BaseDeps.

type NodeController

type NodeController struct {
	*BaseController
	// contains filtered or unexported fields
}

NodeController handles node deletion, publishing and unpublishing.

func NewNodeController

func NewNodeController(deps BaseDeps, d NodeDeps) *NodeController

NewNodeController creates a NodeController.

func (*NodeController) DeleteConfirm

func (c *NodeController) DeleteConfirm(w http.ResponseWriter, r *http.Request)

DeleteConfirm displays the delete confirmation page.

func (*NodeController) Publish

func (c *NodeController) Publish(w http.ResponseWriter, r *http.Request)

Publish publishes the node (sets status to 1).

func (*NodeController) RecentChanges

func (c *NodeController) RecentChanges(w http.ResponseWriter, r *http.Request)

RecentChanges renders GET /admin/content/changes: the saves of the content of every type keeping its history that the viewer may see the history of (editing it: any of the type's, or their own published ones), newest first, by days; the filter - a part of the title, the type, a part of the saver's name, the days.

func (*NodeController) RevisionRevert

func (c *NodeController) RevisionRevert(w http.ResponseWriter, r *http.Request)

RevisionRevert handles POST /node/{id}/revisions/{rev}/revert: the revision brought back as a new one; to the history.

func (*NodeController) Revisions

func (c *NodeController) Revisions(w http.ResponseWriter, r *http.Request)

Revisions renders GET /node/{id}/revisions: the node's history, newest first, a page at a time.

func (*NodeController) RevisionsCompare

func (c *NodeController) RevisionsCompare(w http.ResponseWriter, r *http.Request)

RevisionsCompare renders GET /node/{id}/revisions/compare?from=&to=: two revisions side by side, the older one first.

func (*NodeController) Unpublish

func (c *NodeController) Unpublish(w http.ResponseWriter, r *http.Request)

Unpublish unpublishes the node (sets status to 0).

type NodeDeps

type NodeDeps struct {
	NodeService service.NodesService
	// Revisions - the nodes' history: publishing recorded, its pages.
	Revisions *service.NodeRevisionService
	// Deleter - whether a node's deletion puts it in the trash (the
	// confirmation's wording).
	Deleter *service.NodeDeleteService
}

NodeDeps - what NewNodeController needs besides the BaseDeps.

type NodeDispatcher

type NodeDispatcher struct {
	// contains filtered or unexported fields
}

NodeDispatcher serves a node's pages and forms: by the controller its module registered for its type (RegisterType), else by the DynamicContentController.

func NewNodeDispatcher

func NewNodeDispatcher(dynamicCtrl *DynamicContentController) *NodeDispatcher

NewNodeDispatcher creates a NodeDispatcher serving the types without their own pages by dynamicCtrl.

func (*NodeDispatcher) Clone

func (nd *NodeDispatcher) Clone(w http.ResponseWriter, r *http.Request)

Clone - a content type's node copied (DynamicContentController.Clone); a module's type has no copying: not found.

func (*NodeDispatcher) Create

func (nd *NodeDispatcher) Create(w http.ResponseWriter, r *http.Request)

Create - POST /create/{type}: the new node's form submitted.

func (*NodeDispatcher) CreateForm

func (nd *NodeDispatcher) CreateForm(w http.ResponseWriter, r *http.Request)

CreateForm - GET /create/{type}: the form of a new node of the type.

func (*NodeDispatcher) CreatePreview

func (nd *NodeDispatcher) CreatePreview(w http.ResponseWriter, r *http.Request)

CreatePreview - POST /create/{type}/preview: the new node's form previewed, unsaved (DynamicContentController.CreatePreview; a module's type - its NodeFormPreviewer).

func (*NodeDispatcher) Delete

func (nd *NodeDispatcher) Delete(w http.ResponseWriter, r *http.Request)

Delete - POST /node/{id}/delete: the node deleted.

func (*NodeDispatcher) Edit

func (nd *NodeDispatcher) Edit(w http.ResponseWriter, r *http.Request)

Edit - GET /node/{id}/edit: the node's edit form.

func (*NodeDispatcher) EditPreview

func (nd *NodeDispatcher) EditPreview(w http.ResponseWriter, r *http.Request)

EditPreview - POST /node/{id}/edit/preview: the node's edit form previewed, unsaved (as CreatePreview).

func (*NodeDispatcher) MediaPick

func (nd *NodeDispatcher) MediaPick(w http.ResponseWriter, r *http.Request)

MediaPick - the media library's files a field may take (DynamicContentController.MediaPick).

func (*NodeDispatcher) Preview

func (nd *NodeDispatcher) Preview(w http.ResponseWriter, r *http.Request)

Preview - the item a preview link shows (DynamicContentController. Preview).

func (nd *NodeDispatcher) PreviewLink(w http.ResponseWriter, r *http.Request)

PreviewLink - a content type's node's preview link made or revoked (DynamicContentController.PreviewLinkAction); a module's type has none.

func (*NodeDispatcher) RegisterType

func (nd *NodeDispatcher) RegisterType(t entity.ContentType, c NodeTypeController)

RegisterType gives a module's content type its own pages.

func (*NodeDispatcher) RenderErrorPage

func (nd *NodeDispatcher) RenderErrorPage(w http.ResponseWriter, r *http.Request, status int) bool

RenderErrorPage renders one of the nodes configured for status (Site information → 404/403 page) as the response, with that status. False when none is configured or the chosen node is missing or unpublished.

func (*NodeDispatcher) Save

func (nd *NodeDispatcher) Save(w http.ResponseWriter, r *http.Request)

Save - POST /node/{id}/edit: the node's edit form submitted.

func (*NodeDispatcher) SetNodes

func (nd *NodeDispatcher) SetNodes(nodes entity.NodesRepository)

SetNodes gives the dispatcher the nodes repository (error pages).

func (*NodeDispatcher) View

func (nd *NodeDispatcher) View(w http.ResponseWriter, r *http.Request)

View - the node page. Types that redirect their page elsewhere do so via ContentTypeDef.RedirectField in dynamicCtrl.Detail; the registered module types have their own pages.

type NodeFormPreviewer

type NodeFormPreviewer interface {
	FormPreview(w http.ResponseWriter, r *http.Request)
}

NodeFormPreviewer - a module's content type (its NodeTypeController) whose form previews its item unsaved: FormPreview handles POST /create/{type}/preview and /node/{id}/edit/preview (the form's Preview button, FormPreviewPath; r.PathValue("id") empty on create). A type without it has no preview (404).

type NodeLink struct {
	URL   string
	Label string
}

NodeLink - a module's link on a node page (e.g. "Quotes (12)" on a person's page), shown under the node by node_module_links.

type NodePageParts

type NodePageParts struct {
	Data     any
	Links    []NodeLink
	Comments bool
}

NodePageParts - what a module adds to a node page. Data is what its templates read as .moduleNode.<module>: "node_links_<module>" (under the node, before Links), "node_actions_<module>" (next to Edit) and its plugin blocks (a block on the page, placed in a theme region; see entity.ModulePluginBlock.Region). Comments - the module shows the node's comments in place of the core's (a comments service): its "comments_<module>" with the page's data where the core's comments would be; the node's comment mode still applies (hidden - none). The first enabled module saying so wins.

type NodeSearchController

type NodeSearchController struct {
	// contains filtered or unexported fields
}

NodeSearchController serves GET /api/nodes/search - a generic title search across content types (see entity.NodesRepository.SearchByTitle), used by "link to a node" pickers in admin widgets.

func NewNodeSearchController

func NewNodeSearchController(nodeRepo entity.NodesRepository, baseLogger *slog.Logger) *NodeSearchController

NewNodeSearchController creates a NodeSearchController on nodeRepo.

func (*NodeSearchController) Search

Search handles GET /api/nodes/search?q=... (signed-in users only, see RegisterNodeSearchRoutes).

type NodeSettings

type NodeSettings struct {
	Module  string
	Load    func(ctx context.Context, contentType string, node *entity.Node, submitted url.Values) (any, error)
	Save    func(ctx context.Context, node entity.Node, r *http.Request) error
	Default func(ctx context.Context, node entity.Node) error
}

NodeSettings - a module's section of a node's form ("Settings"), rendered by its template "node_settings_<module>" (moduleHook) from .moduleSettings.<module>, what Load returns: for the node (nil - a new node of the type), or what was submitted (non-nil on a form shown again with errors). The section is shown to "administer content" only: Save stores the submitted form once the node is saved by such a user; for a new node saved by anyone else, Default (optional) gives it the section's defaults, and an existing node keeps its settings.

type NodeTypeController

type NodeTypeController interface {
	Detail(w http.ResponseWriter, r *http.Request)
	CreateForm(w http.ResponseWriter, r *http.Request)
	Create(w http.ResponseWriter, r *http.Request)
	Edit(w http.ResponseWriter, r *http.Request)
	Save(w http.ResponseWriter, r *http.Request)
	Delete(w http.ResponseWriter, r *http.Request)
}

NodeTypeController - a module's own pages of its content type (the node page and the create/edit/delete forms), registered with NodeDispatcher.RegisterType.

type NodeWorkflow

type NodeWorkflow struct {
	Module   string
	Handles  func(ctx context.Context, contentType string) bool
	Load     func(ctx context.Context, contentType string, node *entity.Node, user *entity.User) (any, error)
	Validate func(ctx context.Context, contentType string, node *entity.Node, user *entity.User, r *http.Request) string
	Apply    func(ctx context.Context, node entity.Node, user *entity.User, r *http.Request, isNew bool) error
}

NodeWorkflow - a module's editorial workflow: the items of the content types it Handles are published by it, not by their form - the form shows its "node_workflow_<module>" template (the item's state, the transitions the user may make) from .nodeWorkflow, what Load returns (node nil - a new item); Validate (optional) - why the transition submitted (r) can't be made ("" - it can), shown with the form's errors; Apply, after the form saved the item (in the save's transaction), makes it and sets the item's publishing - its error fails the save. The items' own publish/unpublish buttons are left out.

func NodeWorkflowFor

func NodeWorkflowFor(ctx context.Context, contentType string) *NodeWorkflow

NodeWorkflowFor - the workflow publishing contentType's items (nil - none: their form publishes them).

type OAuthController

type OAuthController struct {
	*BaseController
	// contains filtered or unexported fields
}

OAuthController serves the social sign-in: going to a provider, its callback, completing the profile it left unfilled and disconnecting a provider's account.

func NewOAuthController

func NewOAuthController(
	base *BaseController,
	oauthService *sociallogin.Service,
	userService service.UserService,
	templateService service.TemplateService,
	store *sessions.CookieStore,
	logger *slog.Logger,
) *OAuthController

NewOAuthController creates an OAuthController on the social sign-in service, the users, the templates and the session store.

func (*OAuthController) CompleteProfile

func (c *OAuthController) CompleteProfile(w http.ResponseWriter, r *http.Request)

CompleteProfile handles GET and POST /user/complete-profile: the required profile fields a social sign-up left empty, asked for and saved; a user with none to fill goes on to the destination.

func (*OAuthController) Disconnect

func (c *OAuthController) Disconnect(w http.ResponseWriter, r *http.Request)

Disconnect handles POST /auth/{provider}/disconnect: the provider's account no longer signs in to the user's (not when the account has no address a password reset could reach). Back to the profile form.

func (*OAuthController) OAuthCallback

func (c *OAuthController) OAuthCallback(w http.ResponseWriter, r *http.Request)

OAuthCallback handles GET /auth/{provider}/callback: the provider's answer checked against the session's state, then the user signed in, signed up or their account connected (sociallogin.Service.HandleCallback); a refusal goes to the sign-in or profile form with its message.

func (*OAuthController) OAuthStart

func (c *OAuthController) OAuthStart(w http.ResponseWriter, r *http.Request)

OAuthStart handles GET /auth/{provider}: off to the provider - to sign in, or, signed in, to connect its account to theirs (the callback decides).

type PrivateFilesController

type PrivateFilesController struct {
	*BaseController
	// contains filtered or unexported fields
}

PrivateFilesController serves the private files of file and image fields at paths.PrivateFilesURL - an image's style derivatives too (imageurl.Styled) - only to those service.PrivateFileAccess lets download the file, from the private files' store, never cached by anyone but the browser.

func NewPrivateFilesController

func NewPrivateFilesController(base *BaseController, files entity.FileRepository, access service.PrivateFileAccess, store func() filestore.Store, styles *imagestyle.StyleService) *PrivateFilesController

NewPrivateFilesController creates a PrivateFilesController on the files, the access check, the private files' store and the image styles.

func (*PrivateFilesController) Serve

Serve handles GET {PrivateFilesURL}{key...} - a file, or styles/<style>/<key>, a private image's derivative: a visitor without access is sent to sign in, a signed-in user without it gets 403; a file the site doesn't know is 404.

type ProfileTab

type ProfileTab struct {
	// Module - the module's name.
	Module string
	// Path - the URL segment of the tab.
	Path string
	// Label - the tab's name in English, translated with i18n.T when
	// shown.
	Label string
	// Allowed - whether viewer (nil - a guest) may open the tab on
	// profile's page; isOwner - it is the viewer's own profile,
	// canAdminister - the viewer may administer users. False: the tab
	// isn't listed and its URL answers 403 (a guest is offered to log
	// in). Nil - everyone may.
	Allowed func(ctx context.Context, viewer, profile *entity.User, isOwner, canAdminister bool) bool
	// Badge - a number next to the label on the viewer's own profile (0 -
	// none), e.g. their unread items. Nil - none.
	Badge func(ctx context.Context, viewer *entity.User) int
	// Load fills data - the profile page's data (profileUser, pageSEO…
	// set) - for the tab's content: the module's template
	// "profile_tab_<module>" renders it (renderOptional). An error is
	// logged and the tab rendered with what data has.
	Load func(ctx context.Context, w http.ResponseWriter, r *http.Request, profile *entity.User, data map[string]any) error
}

ProfileTab - a module's tab of the user profile, at /me/<Path> and /<profile>/<Path> (the core's profile routes serve it). Only an enabled module's tabs count. A View's user_tab display can't take a module tab's path; one that has it anyway (saved before the module was there) isn't listed - the module's tab is served.

type RSSChannel

type RSSChannel struct {
	Title         string    `xml:"title"`
	Link          string    `xml:"link"`
	Description   string    `xml:"description"`
	Language      string    `xml:"language"`
	LastBuildDate string    `xml:"lastBuildDate"`
	Items         []RSSItem `xml:"item"`
}

RSSChannel - the feed's <channel>: the site and its items.

type RSSDoc

type RSSDoc struct {
	XMLName xml.Name   `xml:"rss"`
	Version string     `xml:"version,attr"`
	Channel RSSChannel `xml:"channel"`
}

RSSDoc - the RSS 2.0 document (<rss>).

type RSSEnclosure

type RSSEnclosure struct {
	URL    string `xml:"url,attr"`
	Length string `xml:"length,attr"`
	Type   string `xml:"type,attr"`
}

RSSEnclosure - an item's <enclosure>: its image.

type RSSGUID

type RSSGUID struct {
	IsPermaLink string `xml:"isPermaLink,attr"`
	Value       string `xml:",chardata"`
}

RSSGUID - an item's <guid>.

type RSSItem

type RSSItem struct {
	Title       string        `xml:"title"`
	Link        string        `xml:"link"`
	Description string        `xml:"description"`
	PubDate     string        `xml:"pubDate"`
	GUID        RSSGUID       `xml:"guid"`
	Enclosure   *RSSEnclosure `xml:"enclosure,omitempty"`
}

RSSItem - a feed's <item>: a content item.

type RssController

type RssController struct {
	// contains filtered or unexported fields
}

RssController serves the RSS 2.0 feed of the front page feed View (SiteInformation.FrontFeedView).

func NewRssController

func NewRssController(
	siteInformationRepo entity.SiteInformationRepository,
	baseLogger *slog.Logger,
	feed frontFeedSource,
) *RssController

NewRssController creates an RssController on the site information and the front page feed's items (feed).

func (*RssController) Feed

func (c *RssController) Feed(w http.ResponseWriter, r *http.Request)

Feed - GET /rss.xml: the latest items of the front page feed View as RSS 2.0, the channel named after the site.

type SEOProvider

type SEOProvider interface {
	GetNode() entity.Node
	GetContent() string
	GetAltTitle() string // may be empty
}

SEOProvider is implemented by entities that can provide SEO data.

type SearchController

type SearchController struct {
	*BaseController
	// contains filtered or unexported fields
}

SearchController handles the live search API and the search results page.

func NewSearchController

func NewSearchController(base *BaseController, searchService *service.SearchService) *SearchController

NewSearchController creates a SearchController.

func (*SearchController) LiveSearch

func (c *SearchController) LiveSearch(w http.ResponseWriter, r *http.Request)

LiveSearch handles GET /api/search?q=. With q shorter than 3 characters it returns categories, otherwise search results.

func (*SearchController) SearchPage

func (c *SearchController) SearchPage(w http.ResponseWriter, r *http.Request)

SearchPage handles GET /search?q=: the search results page - the same results as the live search, for the search form without JavaScript or on Enter. Never indexed (one page per query).

type SitemapController

type SitemapController struct {
	// contains filtered or unexported fields
}

SitemapController serves sitemap index and urlset fragments for search engines.

func NewSitemapController

func NewSitemapController(
	site entity.SiteInformationRepository,
	nodeRepo entity.NodesRepository,
	views views.Service,
	menus service.MenuService,
	baseLogger *slog.Logger,
) *SitemapController

NewSitemapController creates a SitemapController on the site information, the nodes, the Views and the menus.

func (*SitemapController) Index

Index - GET /sitemap.xml: the sitemap index - the static pages' sitemap and one sitemap per sitemapChunkMax public content items.

func (*SitemapController) NodesChunk

func (c *SitemapController) NodesChunk(w http.ResponseWriter, r *http.Request)

NodesChunk - GET /sitemap/nodes/{n}: the n-th chunk (from 1) of the public content's addresses.

func (*SitemapController) Robots

Robots serves GET/HEAD /robots.txt (service.RobotsTxt): the engine's and the modules' rules, the sitemap, the site's own rules from the admin.

func (*SitemapController) Static

Static - GET /sitemap/static.xml: the site's pages other than its content: the Views' public pages (without a "%" argument), the modules' pages (AddSitemapPaths) and the links of the menus marked for the sitemap.

type StatusSources

type StatusSources struct {
	Modules  func(ctx context.Context) ([]entity.StatusModule, error)
	Database func(ctx context.Context) (driver, version string, err error)
}

StatusSources - what the status report shows besides its checks: the modules' state and the database (wiring).

func StatusReportSources

func StatusReportSources() (*service.StatusReport, StatusSources)

StatusReportSources - the status checks and sources SetStatusReport set (the admin's status report page).

type StyleguideController

type StyleguideController struct {
	*BaseController
	// contains filtered or unexported fields
}

StyleguideController - the active theme's style guide: the engine's markup in one page of the site's own layout - headings and text, buttons, forms, alerts, tables, pagination and a View list of cards - to see the theme style all of it alike.

func NewStyleguideController

func NewStyleguideController(base *BaseController, textFormats service.TextFormatService) *StyleguideController

NewStyleguideController creates a StyleguideController.

func (*StyleguideController) Page

Page handles GET /admin/config/appearance/styleguide: the page in the site's layout (styleguide.html, a theme may replace it), not the admin one. Never indexed.

type StylesController

type StylesController struct {
	// contains filtered or unexported fields
}

StylesController serves the public images in their image styles.

func NewStylesController

func NewStylesController(
	s *imagestyle.StyleService,
	logger *slog.Logger,
) *StylesController

NewStylesController creates a StylesController on the image styles service s.

func (StylesController) ServeStyledImage

func (c StylesController) ServeStyledImage(w http.ResponseWriter, r *http.Request)

ServeStyledImage serves an image rendered with an image style.

type TaxonomyController

type TaxonomyController struct {
	*BaseController
	// contains filtered or unexported fields
}

TaxonomyController serves the term pages and the content forms' tag autocomplete.

func NewTaxonomyController

func NewTaxonomyController(deps BaseDeps, d TaxonomyDeps) *TaxonomyController

NewTaxonomyController creates a TaxonomyController on deps and d.

func (*TaxonomyController) Autocomplete

func (c *TaxonomyController) Autocomplete(w http.ResponseWriter, r *http.Request)

Autocomplete handles AJAX autocomplete requests for taxonomy terms.

func (*TaxonomyController) TermPageFallback

func (c *TaxonomyController) TermPageFallback(w http.ResponseWriter, r *http.Request) bool

TermPageFallback serves a term page from the site-wide catch-all route (after nodes and View pages found nothing): the URL path is the term's slug, and only vocabularies with public term pages are served (TaxonomyVocabulary.PublicTermPages). Returns false - nothing written - when there is no such public term, so the caller renders its 404.

type TaxonomyDeps

type TaxonomyDeps struct {
	TaxonomyService service.TaxonomyService
	ViewService     views.Service
	Teasers         *service.TeaserBuilder
	SEO             *service.SEOService
}

TaxonomyDeps - what NewTaxonomyController needs besides the BaseDeps.

type UnsavedPreview

type UnsavedPreview struct {
	Errors    []string
	FilesLeft bool
}

UnsavedPreview - the strip over a previewed item's page (the page's data "unsavedPreview", html.html's "unsaved_preview"): Errors - what saving would refuse, to correct in the form; FilesLeft - files chosen in the form, shown once saved (a preview doesn't store them).

type UserController

type UserController struct {
	*BaseController
	// contains filtered or unexported fields
}

UserController serves the account pages: sign-in (and its second factor), sign-out, sign-up, email confirmation, password reset, invitations, the profiles, their editing and cancelling an account.

func NewUserController

func NewUserController(deps BaseDeps, d UserDeps) *UserController

NewUserController creates a UserController on deps and d.

func (*UserController) AcceptInvite

func (c *UserController) AcceptInvite(w http.ResponseWriter, r *http.Request)

AcceptInvite handles GET/POST /user/invite?token=…: the invited person chooses their login (the one made for them offered) and sets their password; the account saved, they are signed in. A link no good - the page says so.

func (*UserController) CancelAccount

func (c *UserController) CancelAccount(w http.ResponseWriter, r *http.Request)

CancelAccount handles POST /me/cancel: the signed-in user deletes their own account - with the permission, their password and the "can't be undone" tick; signed out, to the sign-in page saying so. A wrong password or no tick - back to the profile form with the reason.

func (*UserController) ConfirmEmail

func (c *UserController) ConfirmEmail(w http.ResponseWriter, r *http.Request)

ConfirmEmail - GET /user/confirm-email?token=: the account's email address confirmed by the link's token, the user signed in when the account may sign in (else the sign-in page says why not).

func (*UserController) EditForm

func (c *UserController) EditForm(w http.ResponseWriter, r *http.Request)

EditForm - GET /me/edit and /user/{id}/edit: the profile edit form of the signed-in user, or of another one for who administers users.

func (*UserController) EditSave

func (c *UserController) EditSave(w http.ResponseWriter, r *http.Request)

EditSave - POST /me/edit and /user/{id}/edit: the profile edit form saved (the account, its fields and the modules' sections), back to the profile or to the form with its error.

func (*UserController) Login

func (c *UserController) Login(w http.ResponseWriter, r *http.Request)

Login - GET and POST /login: the sign-in form, and its submission (CAPTCHA, then AuthService.Login; on to the second factor when the account has one); a signed-in user goes on to the destination or /me.

func (*UserController) LoginCode

func (c *UserController) LoginCode(w http.ResponseWriter, r *http.Request)

LoginCode handles GET/POST /login/code, the second step of a sign-in: the code of the app (or a recovery code, ?recovery=1 says so) for the pending sign-in; right - signed in, to the destination; wrong - again; too many or too late, or none pending - the login page.

func (*UserController) LoginOnce

func (c *UserController) LoginOnce(w http.ResponseWriter, r *http.Request)

LoginOnce exchanges a one-time login token for a session and redirects to profile edit.

func (*UserController) Logout

func (c *UserController) Logout(w http.ResponseWriter, r *http.Request)

Logout - POST /logout.

func (*UserController) LogoutConfirm

func (c *UserController) LogoutConfirm(w http.ResponseWriter, r *http.Request)

LogoutConfirm - GET /logout: a page with the logout button (Logout is a POST, checked by CSRFMiddleware, so another site can't log a visitor out); a visitor who isn't logged in goes to the front page.

func (*UserController) PasswordRequest

func (c *UserController) PasswordRequest(w http.ResponseWriter, r *http.Request)

PasswordRequest shows forgot-password form (GET) or sends reset email (POST).

func (*UserController) Profile

func (c *UserController) Profile(w http.ResponseWriter, r *http.Request)

Profile - GET /me, /me/{tab}, /users/{alias} and /users/{alias}/{tab}: a user's profile (/me - the signed-in user's) with its tabs: the files (/me/files), a module's (AddProfileTab) or a View's (user_tab display).

func (*UserController) ResetPassword

func (c *UserController) ResetPassword(w http.ResponseWriter, r *http.Request)

ResetPassword shows form to set new password (GET) or saves it (POST).

func (*UserController) SearchUsers

func (c *UserController) SearchUsers(w http.ResponseWriter, r *http.Request)

SearchUsers handles AJAX requests to search for users (for autocomplete): ?q= (2-50 characters), &roles=1,2 - of those roles only (a user field's picker). Requires authentication; never exposes email addresses.

func (*UserController) Signup

func (c *UserController) Signup(w http.ResponseWriter, r *http.Request)

Signup - GET and POST /user/register: the sign-up form (or a page saying sign-up is closed), and its submission (handleSignupPost); a signed-in user goes to /me.

func (*UserController) TwoFactor

func (c *UserController) TwoFactor(w http.ResponseWriter, r *http.Request)

TwoFactor renders GET /me/two-factor: while it's off, turning it on - a new secret (kept in the session) as a QR code and as text, the code confirming it; while on, since when, the recovery codes left, new ones, turning it off (not while the role needs it).

func (*UserController) TwoFactorCodes

func (c *UserController) TwoFactorCodes(w http.ResponseWriter, r *http.Request)

TwoFactorCodes handles POST /me/two-factor/codes: new recovery codes, once a code proves it's the user; shown once.

func (*UserController) TwoFactorDisable

func (c *UserController) TwoFactorDisable(w http.ResponseWriter, r *http.Request)

TwoFactorDisable handles POST /me/two-factor/disable: off, once a code proves it's the user - not while their role needs it.

func (*UserController) TwoFactorEnable

func (c *UserController) TwoFactorEnable(w http.ResponseWriter, r *http.Request)

TwoFactorEnable handles POST /me/two-factor/enable: the code confirms the session's secret - on, and the recovery codes shown once.

type UserDeps

type UserDeps struct {
	FileUploadService *files.FileUploadService
	RoleRepo          entity.RoleRepository
	UserTokenService  *accounts.UserAuthTokenService
	UserFields        *accounts.UserFieldService
	ProfileViews      views.Service
	ProfileTabs       profileTabRenderer
	UserTimezones     interface{ Forget(userID int) }
	Registration      *accounts.RegistrationService
	PasswordReset     *accounts.PasswordResetService
	TwoFactor         *twofactor.Service
	SocialLogin       *sociallogin.Service
	// AccountCancel, AccountPolicy - a user deleting their own account.
	AccountCancel *service.UserDeletionService
	AccountPolicy *accounts.AccountPolicyService
}

UserDeps - what NewUserController needs besides the BaseDeps.

type UserFilesController

type UserFilesController struct {
	// contains filtered or unexported fields
}

UserFilesController is the JSON API for per-user files under the public files directory (u{userID}/).

func NewUserFilesController

func NewUserFilesController(
	svc *files.UserFilesService,
	store *sessions.CookieStore,
	logger *slog.Logger,
	auth service.AuthService,
	usage *files.UserFileUsageService,
	formats textFormatByID,
) *UserFilesController

NewUserFilesController creates a UserFilesController on the users' files service, the session store, the auth service, the files' usage and the text formats (their upload rules).

func (*UserFilesController) List

List GET /api/user/files?path=

func (*UserFilesController) Mkdir

Mkdir POST /api/user/files/mkdir

func (*UserFilesController) Rename

Rename POST /api/user/files/rename (path, name): a file or folder gets a new name in the same folder; returns its new path.

func (*UserFilesController) Rmdir

Rmdir POST /api/user/files/rmdir

func (*UserFilesController) Tree

Tree GET /api/user/files/tree - nested folders for sidebar navigation.

Unlink POST /api/user/files/unlink

func (*UserFilesController) Upload

Upload POST /api/user/files/upload (multipart: file, csrf_token, optional path=subdir, optional text_format_id for the per-format image policy of FileUploadService.ValidateAndProcessTextFormatImage; invalid means 0). Images and the upload policy's document types are accepted.

func (*UserFilesController) Usage

Usage GET /api/user/files/usage?path= - where a file is linked from right now (read from the texts).

type UserSettingsSection

type UserSettingsSection struct {
	Module string
	Load   func(ctx context.Context, user entity.User) (any, error)
	Save   func(ctx context.Context, user entity.User, r *http.Request) error
}

UserSettingsSection - a module's section of a user's profile form (/me/edit, /user/{id}/edit: the user's own settings in the module, such as its e-mails), rendered by its template "user_settings_<module>" (moduleHook) from .moduleSettings.<module>, what Load returns for the user edited. Save stores the submitted form once the profile is saved.

type ViewCountController

type ViewCountController struct {
	// contains filtered or unexported fields
}

ViewCountController handles POST /api/node/view for node_counter increments.

func NewViewCountController

func NewViewCountController(logger *slog.Logger, viewCounting service.ViewCountingService) *ViewCountController

NewViewCountController creates a ViewCountController.

func (*ViewCountController) PostView

func (c *ViewCountController) PostView(w http.ResponseWriter, r *http.Request)

PostView handles POST /api/node/view (application/x-www-form-urlencoded: nid).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL