entity

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RegistrationModeAdminOnly        = "admin_only"
	RegistrationModeVisitors         = "visitors"
	RegistrationModeVisitorsApproval = "visitors_approval"
)

Registration modes (stored in account_settings.registration_mode).

View Source
const (
	CancelKeepContent   = "keep"
	CancelDeleteContent = "delete"
)

What a user's own account deletion does with their content (AccountSettings.CancelContent).

View Source
const (
	CopyrightHolderKey = "holder"
	CopyrightSinceKey  = "since"
)

The copyright block's settings (PluginConfig keys).

View Source
const (
	CaptchaFormLogin    = "login"
	CaptchaFormRegister = "register"
	CaptchaFormPassword = "password"
	// CaptchaFormComment - the comment form, for authors without a
	// published comment yet.
	CaptchaFormComment = "comment"
)

The core's forms that can show the CAPTCHA (CaptchaSettings.Forms); modules add theirs (Module.CaptchaForms).

View Source
const (
	AdminCommentsSortCreated = "created"
	AdminCommentsSortUpdated = "updated"
)

Admin comments list sort keys (query param sort=)

View Source
const (
	CommentPending   int8 = 0
	CommentPublished int8 = 1
	CommentSpam      int8 = 2
)

A comment's Status: waiting for approval (shown to its author only), published, spam (shown to nobody; the admin's "Spam" tab).

View Source
const (
	// CommentReasonNewAuthor - among its author's first comments
	// (CommentSettings.NewAuthorChecks).
	CommentReasonNewAuthor = "new_author"
	// CommentReasonMarked - marked as spam by hand.
	CommentReasonMarked = "marked"
	// CommentReasonLinks - more links than allowed: "links:<count>".
	CommentReasonLinks = "links"
	// CommentReasonStopWord - a stop word: "word:<the word>".
	CommentReasonStopWord = "word"
	// CommentReasonReported - visitors reported it (a module's
	// complaints): "reported:<how many>".
	CommentReasonReported = "reported"
)

Why a comment waits for approval or is spam (Comment.HoldReason).

View Source
const (
	StopWordsHold   = "hold"
	StopWordsReject = "reject"
)

What a stop word in a comment does (CommentSettings.StopWordsAction).

View Source
const (
	PublicScheme  = "public://"
	PrivateScheme = "private://"
)

PublicScheme - the prefix of a public file's URI ("public://<path>"); the URL path it is served at is the config's (templates: publicFileURL, imageurl.PublicURI). PrivateScheme - a private file's ("private://<path>", in the private files' store): the site serves it only to those who may see a content item it is attached to.

View Source
const (
	// TextMenuLinkTitle - a menu link's title (ref - its id).
	TextMenuLinkTitle = "menu_link.title"
	// VisibilityMenuLink - a menu link (ref - its id).
	VisibilityMenuLink = "menu_link"
	// TextBlockTitle - a custom block's title (ref - the block's id).
	TextBlockTitle = "block.title"
	// TextPlacementTitle - a block placement's title (ref - its id): a
	// View's, a menu's, a module's block.
	TextPlacementTitle = "block_placement.title"
	// VisibilityBlockPlacement - a block placement (ref - its id).
	VisibilityBlockPlacement = "block_placement"
	// TextTermName, TextTermDescription - a taxonomy term's name and
	// description (ref - its id).
	TextTermName        = "term.name"
	TextTermDescription = "term.description"
	// TextSiteName, TextSiteSlogan - the site's name and slogan (ref -
	// "site").
	TextSiteName   = "site.name"
	TextSiteSlogan = "site.slogan"
	// TextViewTitle, TextViewDescription - a View display's title (its
	// page's heading, its block's default title) and meta description
	// (ref - its id).
	TextViewTitle       = "view.title"
	TextViewDescription = "view.description"
	// TextFieldLabel - a content type's field's label (ref - the field
	// instance's id).
	TextFieldLabel = "field.label"
)

Kinds of the site's own texts and things shown by language.

View Source
const (
	// MailStatusSent - the transport took it.
	MailStatusSent = "sent"
	// MailStatusFailed - the transport refused it (MailLogEntry.Error).
	MailStatusFailed = "failed"
	// MailStatusUnsent - email is off or not configured: nothing was sent.
	MailStatusUnsent = "unsent"
)

What came of an email (MailLogEntry.Status).

View Source
const (
	FeatureBackToTop = "back_to_top"
	FeatureSearch    = "search"
)

Feature switches: smaller engine features turned on and off in their own admin sections (not on the Modules page). Their states are stored with the modules' (ModuleRepository); a missing state means enabled.

View Source
const (
	ModuleCategoryContent        = "content"
	ModuleCategoryMedia          = "media"
	ModuleCategoryCommunity      = "community"
	ModuleCategoryAdministration = "administration"
	ModuleCategoryIntegrations   = "integrations"
	ModuleCategoryOther          = "other"
)

The groups of the Modules page (Module.Category), in its order (ModuleCategories): the engine's set, a module picks one of them.

View Source
const (
	AdminNodesSortTitle      = "title"
	AdminNodesSortStatus     = "status"
	AdminNodesSortModeration = "moderation"
	AdminNodesSortCreated    = "created"
	AdminNodesSortUpdated    = "updated"
	AdminNodesSortViews      = "views"
	// AdminNodesSortPath - by the address (the URL aliases page).
	AdminNodesSortPath = "path"
)

Admin content list sort keys (query param sort=)

View Source
const (
	SnapshotTitle           = "title"
	SnapshotStatus          = "status"
	SnapshotOnModeration    = "on_moderation"
	SnapshotPromote         = "promote"
	SnapshotSticky          = "sticky"
	SnapshotCommentMode     = "comment_mode"
	SnapshotSlug            = "slug"
	SnapshotAuthor          = "author"
	SnapshotMetaTitle       = "meta_title"
	SnapshotMetaDescription = "meta_description"
)

The keys of a NodeSnapshot's own parts, as NodeSnapshot.Diff names them; a field is SnapshotFieldKey(its machine name).

View Source
const (
	RoleUser      = "user"
	RoleModerator = "moderator"
	RoleAdmin     = "admin"
	// RoleAnonymous - the pseudo role of guests (not signed in), for
	// conditions like block visibility; never stored on a user.
	RoleAnonymous = "anonymous"
)

Common role names

View Source
const (
	SchemaOrgOrganization  = "Organization"
	SchemaOrgLocalBusiness = "LocalBusiness"
	SchemaOrgPerson        = "Person"
)

Who runs the site (SiteSchemaOrg.Kind).

View Source
const (
	TagCloudVocabularyKey = "vocabulary"
	TagCloudCountKey      = "count"
	TagCloudLevelsKey     = "levels"
)

The tag cloud's settings (PluginConfig keys): the vocabulary whose terms it shows ("0" - every vocabulary), how many and in how many size levels.

View Source
const (
	AdminPeopleSortCreated    = "created"
	AdminPeopleSortLastAccess = "last_access"
)

Admin people list sort keys (query param sort=...).

View Source
const (
	UserStatusBlocked = 0
	UserStatusActive  = 1
	UserStatusPending = 2 // awaiting admin approval
)

User status constants (users.status).

View Source
const (
	UserAuthTokenKindOneTimeLogin  = "one_time_login"
	UserAuthTokenKindPasswordReset = "password_reset"
	// UserAuthTokenKindEmailConfirm - the link confirming an account's
	// e-mail address.
	UserAuthTokenKindEmailConfirm = "email_confirm"
	// UserAuthTokenKindInvite - an invitation: the link by which the
	// person an administrator created sets their own password.
	UserAuthTokenKindInvite = "invite"
)

The one-time tokens' kinds: a login link, a password reset, an e-mail confirmation, an invitation.

View Source
const (
	UserFileSourceNodeField = "node_field"
	UserFileSourceComment   = "comment"
	UserFileSourceSignature = "signature"
	UserFileSourceUserField = "user_field"
	UserFileSourceBlock     = "block"
	UserFileSourceView      = "view"
)

The core's texts that can link to users' files (UserFileUsage.Source); modules add theirs (Module.FileSources).

View Source
const (
	OAuthProviderGoogle = "google"
	OAuthProviderVK     = "vk"
	OAuthProviderYandex = "yandex"
)

The supported social login providers' names (OAuthProviders).

View Source
const (
	ViewGroupDateYear  = "year"
	ViewGroupDateMonth = "month"
	ViewGroupDateDay   = "day"
)

View group heading formats for a date field (ViewDisplayDef. GroupDateFormat); "" - the rendered field.

View Source
const (
	ViewPageParam   = "page"
	ViewLetterParam = "letter"
)

The other query parameters a View page reads itself: the page of the list, the glossary's letter. No exposed filter takes them (nor sort).

View Source
const AvatarPlaceholderURL = "/static/images/no_avatar.png"

AvatarPlaceholderURL - the engine's picture for a user without an avatar.

View Source
const DateTimeFormat = "datetime"

DateTimeFormat - the format of a date with its time where the engine shows one (comments, messages, the admin's lists); without it the default format is used.

View Source
const DefaultDateFormat = "short"

DefaultDateFormat - the format of a date with none chosen; can't be deleted.

View Source
const DefaultSearchLimit = 5

DefaultSearchLimit - the results of a type from the field search, for a type searched with the defaults.

View Source
const DefaultTheme = "default"

DefaultTheme - the placement theme key of the engine's own templates (no theme directory). Every other theme's placements are keyed by its directory under themes/.

View Source
const ImageStyleAnchorFocal = "focal"

ImageStyleAnchorFocal - the anchor cropping at the image's focal point (File.Focal), at its center when it has none.

View Source
const LightboxStyle = "lightbox"

LightboxStyle - the image style the lightbox opens an image in (the engine's own: a large WebP copy instead of the original, which may be a camera's megabytes); gone - the originals.

View Source
const MailTemplatesPath = "/admin/config/mail/templates"

MailTemplatesPath - the Mail page's "Emails" tab.

View Source
const MailTransportSMTP = "smtp"

MailTransportSMTP - MailSettings.Transport of the engine's own way of sending: an SMTP server. The others are the modules' (their names).

View Source
const MaxMetaDesc = 160

MaxMetaDesc - the longest meta description, in characters.

View Source
const MediaThumbnailStyle = "media_library"

MediaThumbnailStyle - the image style of the media library's tiles (the engine's own, like the avatars'); gone - the originals.

View Source
const MinPasswordLength = 6

MinPasswordLength - the fewest characters (not bytes) of a password, wherever one is set.

View Source
const ModuleCategoryContext = "module category"

ModuleCategoryContext - the translation context of the categories' labels.

View Source
const PasswordUnset = "!"

PasswordUnset - the password hash of an account whose password isn't set yet (an invitation not accepted): no password matches it.

View Source
const PluginBlockTargetKey = "target"

PluginBlockTargetKey - the PluginConfig key of the thing a block shows (PluginBlockTargets).

View Source
const SEOTemplateDefaultScope = "node"

SEOTemplateDefaultScope - the scope of the template every node falls back to ("Content").

View Source
const SEOTemplateTermScope = "taxonomy_term"

SEOTemplateTermScope - the template every taxonomy term page falls back to ("Taxonomy term").

View Source
const SchemaNone = "none"

SchemaNone - a content type's markup switched off (SEOTemplate.SchemaType); "" is the default scope's.

View Source
const SessionName = csrf.SessionName

SessionName - the site's session cookie: who is signed in, the 2FA step, the theme preview, the CSRF token (pkg/csrf keeps it there).

View Source
const SiteTextRef = "site"

SiteTextRef - the ref of the site's own texts (TextSiteName…).

View Source
const UserMetadataKeyOAuthProvider = "oauth_provider"

UserMetadataKeyOAuthProvider records which OAuth provider created the account.

View Source
const UserMetadataKeyRegistrationIP = "registration_ip"

UserMetadataKeyRegistrationIP is stored in User.Metadata for self-service signup.

View Source
const UserPathPrefix = "users"

UserPathPrefix - the engine's path of user profiles: /users/<alias> (like /login or /admin, not a site setting). users.slug stores the path without the leading slash: "users/<alias>".

View Source
const ViewModuleKeyMaxLen = 32

ViewModuleKeyMaxLen - the longest Key (the builtin_field column).

View Source
const ViewSortParam = "sort"

ViewSortParam - the query parameter of a View page naming the visitor's choice of its exposed sort criteria (ViewSortDef.ExposedKey).

View Source
const ViewURLArgument = "%"

ViewURLArgument - a URLPath segment taking a value from the request path (a "%" argument): the user with that alias, which the created_by contextual filter then uses ("User from URL"). At most one per path.

Variables

View Source
var (
	AdminGroupSite  = i18n.N("Site")
	AdminGroupTexts = i18n.N("Texts and files")

	AdminGroupModules = i18n.N("Modules")
)

Admin menu groups (AdminMenuItem.Group) of the Configuration section; AdminGroupModules - the modules' settings pages, AdminGroupTexts - the texts' and files', AdminGroupSite - the site's own (a module's page may join them too).

View Source
var (
	AdminSectionContent       = i18n.N("Content")
	AdminSectionStructure     = i18n.N("Structure")
	AdminSectionConfiguration = i18n.N("Configuration")
	AdminSectionReports       = i18n.N("Reports")
)

Admin menu sections a module's page joins (ModuleMenuItem.Section): their labels.

View Source
var CommentsPerPage = 50

CommentsPerPage - how many comments a page of a node's comments shows.

ConsentGroups - the groups a code can be in, in the banner's order.

View Source
var CoreCaptchaForms = []ModuleCaptchaForm{
	{CaptchaFormLogin, i18n.N("Login form"), true},
	{CaptchaFormRegister, i18n.N("Registration"), true},
	{CaptchaFormPassword, i18n.N("Password reset"), true},
	{CaptchaFormComment, i18n.N("Comment form (authors without a published comment)"), false},
}

CoreCaptchaForms - the core's CAPTCHA forms with their labels (translation sources), shown by default.

DateParts - the choices of a DatePart setting, in the order shown.

View Source
var ErrEntityNotFound = apperrors.ErrNotFound

ErrEntityNotFound - a missing record: the engine's one sentinel for it, apperrors.ErrNotFound itself (the handlers answer it 404); ent's not-found errors match it (generated.NotFoundError.Is), the modules' too (schemakit.ErrEntityNotFound).

View Source
var FeaturePluginBlocks = map[PluginBlockID]string{
	PluginBlockSearchForm: FeatureSearch,
}

FeaturePluginBlocks - plugin blocks provided by feature switches (not modules).

FieldLayouts - the choices of FieldLayout, in the order shown.

FieldTypes - every field type, in the order the admin offers them. A new type goes here and into fieldTypeDefs; the completeness tests of each layer (storage, revisions, the form, the page, Views) then fail until it's handled there.

View Source
var ForbiddenUserFileExtensions = map[string]bool{
	"htm": true, "html": true, "xhtml": true, "shtml": true, "svg": true, "svgz": true, "xml": true,
	"js": true, "mjs": true, "css": true, "php": true, "phtml": true, "phar": true, "cgi": true, "pl": true,
	"py": true, "sh": true, "exe": true, "dll": true, "bat": true, "cmd": true, "com": true, "msi": true,
	"jar": true, "swf": true, "htaccess": true,
}

ForbiddenUserFileExtensions - extensions never accepted for an upload (a browser or the server could execute them), whatever the policy says.

View Source
var ImageStyleAnchors = []string{
	ImageStyleAnchorFocal, "center", "top-left", "top", "top-right",
	"left", "right", "bottom-left", "bottom", "bottom-right",
}

ImageStyleAnchors - ImageStyleAnchorFocal and the 9 imaging.Anchor values, in disintegration/imaging order.

View Source
var ImageStyleFormats = []string{"webp", "jpeg"}

ImageStyleFormats - allowed Format values.

View Source
var ImageStyleResizeModes = []string{"fill", "fit", "resize"}

ImageStyleResizeModes - allowed Mode values (the imagestyle.ResizeMode* constants).

LinkTitleModes - the choices of a link field's title setting, in the order shown.

View Source
var MailSitePlaceholders = []string{"[site:name]", "[site:slogan]", "[site:url-brief]", "[site:login-url]"}

MailSitePlaceholders - the placeholders every email may use: the site's.

View Source
var MailUserPlaceholders = []string{"[user:name]", "[user:email]", "[user:edit-url]"}

MailUserPlaceholders - the placeholders of an email about a user (to them or of them): their name, address and profile's edit page.

View Source
var Modules []Module

Modules - the registered modules, in the order of the Modules page (RegisterModule; filled at startup).

View Source
var OAuthConsoleURLs = map[string]string{
	OAuthProviderGoogle: "https://console.cloud.google.com/apis/credentials",
	OAuthProviderVK:     "https://id.vk.com/about/business/go",
	OAuthProviderYandex: "https://oauth.yandex.ru/",
}

OAuthConsoleURLs - where each provider's app (client ID and secret) is registered, for the settings page.

OAuthProviders - the supported social login providers, in the order the UI lists them.

PopularPeriods - the periods in the order the report offers them.

View Source
var ProfileBuiltinTabPaths = []string{"edit", "files"}

ProfileBuiltinTabPaths - the user profile's own tab paths (the core's routes), which a user_tab display can't take.

View Source
var SchemaTypes = []SchemaTypeDef{
	{Name: "Article", Label: i18n.N("Article"), Creative: true, Article: true, Props: articleProps},
	{Name: "NewsArticle", Label: i18n.N("News article"), Creative: true, Article: true, Props: articleProps},
	{Name: "BlogPosting", Label: i18n.N("Blog post"), Creative: true, Article: true, Props: articleProps},
	{Name: "WebPage", Label: i18n.N("Web page"), Creative: true, Props: []SchemaPropDef{
		{Name: "keywords", Label: i18n.N("Keywords"), Hint: i18n.N("Comma-separated, e.g. a tags field.")},
	}},
	{Name: "Event", Label: i18n.N("Event"), Objects: map[string]string{"location": "Place"}, Props: []SchemaPropDef{
		{Name: "startDate", Label: i18n.N("Start"), Hint: i18n.N("A date field with :iso, e.g. [node:field:date:iso].")},
		{Name: "endDate", Label: i18n.N("End"), Hint: i18n.N("A date field with :iso.")},
		{Name: "location.name", Label: i18n.N("Place"), Hint: i18n.N("Its name.")},
		{Name: "location.address", Label: i18n.N("Place's address")},
	}},
	{Name: "Product", Label: i18n.N("Product or service"), Objects: map[string]string{"offers": "Offer", "brand": "Brand"}, Props: []SchemaPropDef{
		{Name: "brand.name", Label: i18n.N("Brand")},
		{Name: "sku", Label: i18n.N("SKU")},
		{Name: "offers.price", Label: i18n.N("Price"), Hint: i18n.N("A number field.")},
		{Name: "offers.priceCurrency", Label: i18n.N("Currency"), Hint: i18n.N("ISO 4217, e.g. EUR.")},
		{Name: "offers.availability", Label: i18n.N("Availability"), Hint: i18n.N("A schema.org address, e.g. https://schema.org/InStock.")},
	}},
}

SchemaTypes - the types offered, in the order shown.

ViewModuleChoiceOperators - what a choice filter compares: its value with the filter's (eq - one, in - one of a comma-separated list), or whether the node has one.

ViewModuleFilterOperators - what a module's filter compares: its number with the filter's Value, or whether the node has one.

Functions

func AdminMenuCurrent

func AdminMenuCurrent(menu []AdminMenuSection, path string) (AdminMenuSection, AdminMenuItem, bool)

AdminMenuCurrent - the section and item of menu path belongs to: the item whose Path is path or a prefix of it at a "/" (the longest such); a section that is a link counts as its own item. False - none.

func ApplyFieldFallbacks

func ApplyFieldFallbacks(fields FieldInstanceDefs, values map[int]any)

ApplyFieldFallbacks fills empty field values from another field: for each field with a FallbackFieldKey whose value is empty, it copies the value of the field whose MachineName matches the key (same namespace as RewriteHTML's {{field:<key>}} tokens). Missing or empty targets are ignored. values is mutated in place; call it after all values are resolved.

func BlockItemIDs

func BlockItemIDs(v any) []int

BlockItemIDs - the saved items of a blocks field's value, in order.

func CaptchaFormNames

func CaptchaFormNames() []string

CaptchaFormNames - the keys of CaptchaForms().

func ClampMenuLevelSettings

func ClampMenuLevelSettings(startLevel, levelsToShow int) (int, int)

ClampMenuLevelSettings clamps menu placement settings to their supported ranges (startLevel 1-10, levelsToShow 0-9, 0 = unlimited).

func CommentReason

func CommentReason(code, detail string) string

CommentReason - a reason with its detail ("links:3"); SplitCommentReason takes it apart.

func DateStart

func DateStart(v any) (time.Time, bool)

DateStart - the start of a date field's value (a time.Time, a DateValue, the first of a []DateValue); false - none.

func FileIDs

func FileIDs(v any) []int

FileIDs - the files of an image or file field's value: one (an int) or, for a field with several values, a slice in the editor's order; none for anything else.

func FirstFileID

func FirstFileID(v any) int

FirstFileID - the first file of an image or file field's value (FileIDs), 0 - none: where one picture stands for the content (a teaser, a feed item, a search result).

func ForgetMemoizedUsers

func ForgetMemoizedUsers(ctx context.Context)

ForgetMemoizedUsers drops the users ctx's request kept: one was written.

func Found

func Found[T any](v T, err error, what string, args ...any) (T, error)

Found - v a repository looked up (err its error): a missing record as it is (IsNotFound), another error wrapped with what was looked for (a format of args).

func HiddenNodeTypes

func HiddenNodeTypes(ctx context.Context) []string

HiddenNodeTypes - the types ctx's queries leave out (its visitor's; none under WithAllNodeTypes).

func InstanceDateFormatKey

func InstanceDateFormatKey(contentType string, fieldStorageID int) string

InstanceDateFormatKey - the key of DateFormatRepository. InstanceDateFormats: a content type and a field storage.

func IsDuplicateKey

func IsDuplicateKey(err error) bool

IsDuplicateKey detects a unique-constraint violation wrapped by ent: MySQL's "Duplicate entry", PostgreSQL's SQLSTATE 23505. Ent has no typed error for it (its ConstraintError is any constraint), so it matches the driver's text, keeping the drivers out of the domain.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound - err says the record is missing (ErrEntityNotFound, which ent's not-found errors match, wrapped or not).

func IsValidCommentMode

func IsValidCommentMode(s string) bool

IsValidCommentMode reports whether s is one of the three CommentMode values (used to validate admin form input).

func IsValidTitleDisplay

func IsValidTitleDisplay(v string) bool

IsValidTitleDisplay reports whether v is one of the TitleDisplay values.

func LanguageOfPrefix

func LanguageOfPrefix(prefix string) (string, bool)

LanguageOfPrefix - the language whose addresses start with prefix; false for none.

func LanguagePrefix

func LanguagePrefix(code string) string

LanguagePrefix - the prefix of code's addresses, "en"; "" for the default language or one the site hasn't.

func LocalPath

func LocalPath(code, path string) string

LocalPath - path ("/news/x", "/") in code's addresses: with its prefix ("/en/news/x", "/en/"), as is for the default language.

func LocalizePath

func LocalizePath(code, path string) string

LocalizePath - an address of the site (path, "/news?page=2") for a page in code: LocalPath's, unless it isn't the site's own ("", "//host", "https://…", "#…") or already starts with a language's prefix.

func LocalizeSelfURL

func LocalizeSelfURL(code, u, current string) string

LocalizeSelfURL - u, a page's own address (its canonical, og:url: the site URL and a path) under code's prefix when its path is current, the request's path without its language prefix (a list's, a View's, the front page's); any other u - content with its language's address - as it is.

func MailTemplatePath

func MailTemplatePath(key string) string

MailTemplatePath - the edit page of the email key.

func MatchURLArgument

func MatchURLArgument(pattern, path string) (string, bool)

MatchURLArgument - whether path matches pattern (a URLPath with one "%" segment) and the argument value.

func MemoizeUser

func MemoizeUser(ctx context.Context, u User)

MemoizeUser keeps a copy of u for the rest of ctx's request.

func ModuleNodeTypeCreatePaths

func ModuleNodeTypeCreatePaths() map[string]string

ModuleNodeTypeCreatePaths - standalone create pages of the modules' node types (types without one are left out).

func ModuleNodeTypeLabels

func ModuleNodeTypeLabels() map[string]string

ModuleNodeTypeLabels - labels of the modules' node types (they have no content_types row; every other type's label is its ContentTypeDef.Label).

func ModuleNodeTypePathPrefix

func ModuleNodeTypePathPrefix(nodeType string) string

ModuleNodeTypePathPrefix - the path prefix of a module's node type ("" - none, or not a module's type).

func ModuleNodeTypes

func ModuleNodeTypes() []string

ModuleNodeTypes - every module-provided node type, in module order.

func ModuleOfNodeType

func ModuleOfNodeType(nodeType string) (string, bool)

ModuleOfNodeType - the module that provides the node type.

func ModuleOfPermission

func ModuleOfPermission(key string) (string, bool)

ModuleOfPermission - the module that adds the permission.

func ModuleOfPluginBlock

func ModuleOfPluginBlock(id PluginBlockID) (string, bool)

ModuleOfPluginBlock - the module or feature switch that provides the plugin block.

func ModuleOfTable

func ModuleOfTable(table string) string

ModuleOfTable - the module that owns the table ("" for a core table).

func ModuleRequirementsMissing

func ModuleRequirementsMissing(states map[string]bool) map[string][]string

ModuleRequirementsMissing - for each module enabled in states, the modules it requires that are off (a name missing from states counts as enabled).

func ModulesRequiring

func ModulesRequiring(name string) []string

ModulesRequiring - the modules that require name.

func NodeDeletePath

func NodeDeletePath(nodeType string, id int) string

NodeDeletePath - a node's delete page: its module type's own (ModuleNodeType.DeletePath) or the core's.

func NodeEditPath

func NodeEditPath(nodeType string, id int) string

NodeEditPath / NodeDeletePath - a node's edit and delete pages: its module type's own (ModuleNodeType.EditPath/DeletePath) or the core's.

func NodeRelPath

func NodeRelPath(nodeType ContentType, slug string) string

NodeRelPath returns a node's public URL path relative to the site root (no leading "/"), path-escaped. Slug is usually the full relative path ("articles/foo"); a module's node type with a PathPrefix (a forum topic's bare slug under "forum/") gets the prefix unless the slug already carries it (imported topics). Build node links through this function - using Slug alone breaks such links.

func NodeURLsInLanguage

func NodeURLsInLanguage(ctx context.Context, ids []int, lang string) map[int]string

NodeURLsInLanguage - the addresses of the items among ids that have a public version in lang (SetNodeURLsInLanguage), by id; the others are left out.

func NormalizeEmail

func NormalizeEmail(email string) string

NormalizeEmail - an email as users.email stores it: trimmed and in lower case, so the unique index holds one address once on every database (PostgreSQL compares case-sensitively).

func NormalizeImageStyleFormat

func NormalizeImageStyleFormat(f string) string

NormalizeImageStyleFormat - f if it's one of ImageStyleFormats, else "webp".

func OwnDiscussionNodeTypes

func OwnDiscussionNodeTypes() []string

OwnDiscussionNodeTypes - the modules' node types whose comments are a discussion of their own (ModuleNodeType.OwnDiscussion).

func ParseFileExtensions

func ParseFileExtensions(s string) []string

ParseFileExtensions splits a list of extensions (spaces or commas, an optional leading dot) into lower-case names; empty items are dropped.

func ParseHosts

func ParseHosts(raw string) []string

ParseHosts - the hosts of an "Allowed sites" input (space, comma or newline separated; an address is cut to its host), lower case, without "www.", each once.

func ParseRelativeDate

func ParseRelativeDate(expr string, now time.Time) (time.Time, error)

ParseRelativeDate resolves a relative date expression ("now", "+7 days", "-1 month", "+2 weeks", "+1 year"; empty = "now") against today's date in the site time zone, returned as UTC midnight - the same date-only precision FieldValueDate stores, so comparisons match literal dates. Used by both the query layer and the save-time validator.

func ParseTermIDs

func ParseTermIDs(csv string) []int

ParseTermIDs - comma-separated term IDs (invalid entries skipped).

func PluginBlockLabels

func PluginBlockLabels() map[PluginBlockID]string

PluginBlockLabels - the admin label (translation source) of each plugin block, the modules' included.

func ProfileTabPathReserved

func ProfileTabPathReserved(path string) bool

ProfileTabPathReserved - whether path is a built-in tab's or a module's (a user_tab display can't take it).

func RegisterModule

func RegisterModule(m Module)

RegisterModule adds a module to the registry (at startup, before anything reads it); a second module with the same name panics.

func RegistrationIPFromMetadata

func RegistrationIPFromMetadata(md map[string]any) string

RegistrationIPFromMetadata returns the registration IP string for templates and admin UI.

func RegistrationOpen

func RegistrationOpen() bool

RegistrationOpen - whether visitors may sign up (SetRegistrationMode).

func ReserveProfileTabPath

func ReserveProfileTabPath(path string)

ReserveProfileTabPath - a module's profile tab has path (its wiring, interfaces.AddProfileTab): no user_tab display may take it.

func ReservedContentTypeMachineNames

func ReservedContentTypeMachineNames() []string

ReservedContentTypeMachineNames - machine names a content type can't take: the built-in modules' node types (ModuleNodeTypeLabels), and "node" and "default", the suffixes of the templates for every type (page_node, teaser_default…).

func ResetProfileTabPaths

func ResetProfileTabPaths()

ResetProfileTabPaths forgets the modules' tab paths (wiring the app again).

func SEOTemplateTypeScope

func SEOTemplateTypeScope(machineName string) string

SEOTemplateTypeScope - the scope of a content type's template (e.g. "Content: Article" is node__article).

func SEOTemplateVocabularyScope

func SEOTemplateVocabularyScope(vocabularyID int) string

SEOTemplateVocabularyScope - a vocabulary's term pages template (e.g. "Taxonomy term: Tags").

func SetLanguageVisibility

func SetLanguageVisibility(fn func(kind, ref, lang string) bool)

SetLanguageVisibility sets what says whether a thing (kind, ref) shows on a page in lang.

func SetLanguagesSwitch

func SetLanguagesSwitch(on func() bool)

SetLanguagesSwitch sets what says whether the site's languages besides the default one are in use (the languages module is enabled); none set - they are not.

func SetNodeURLsInLanguage

func SetNodeURLsInLanguage(fn func(ctx context.Context, ids []int, lang string) map[int]string)

SetNodeURLsInLanguage sets what gives content items' addresses in a language: their public versions in it (translations).

func SetRegistrationMode

func SetRegistrationMode(mode string)

SetRegistrationMode makes mode the process's (at start and on saving the account settings), for the pages' "Register" links.

func SetSiteDomain

func SetSiteDomain(domain string)

SetSiteDomain sets the canonical origin NewSystemSettings returns: at startup from the config, then by service.SiteURL.Apply (the config's address, else the one saved in Site information).

func SetSiteLanguages

func SetSiteLanguages(def string, others []SiteLanguage)

SetSiteLanguages sets the site's languages: def - the default one, others - with their prefixes (one equal to def, or without a prefix, is left out).

func SetTextTranslator

func SetTextTranslator(fn func(lang, kind, ref string) (string, bool))

SetTextTranslator sets what gives a text of the site in a language (false - none: the text as entered).

func SnapshotFieldKey

func SnapshotFieldKey(machineName string) string

SnapshotFieldKey - the Diff key of the field machineName.

func SnapshotFieldName

func SnapshotFieldName(key string) (string, bool)

SnapshotFieldName - the field machine name of a Diff key; false - one of the node's own parts.

func SplitCommentReason

func SplitCommentReason(reason string) (code, detail string)

SplitCommentReason - reason's code and detail ("" - none).

func ThemeDir

func ThemeDir(key string) string

ThemeDir - the theme directory of a placement theme key.

func ThemeKey

func ThemeKey(dir string) string

ThemeKey - the placement theme key of a theme directory ("" - the engine's templates).

func Today

func Today(now time.Time, zone *time.Location) time.Time

Today - the date of now in zone, at UTC midnight: what a date without a time (DateValue.WithTime false) compares with.

func TranslatedText

func TranslatedText(lang, kind, ref, fallback string) string

TranslatedText - the text kind of ref in lang (SetTextTranslator), else fallback (the text as entered).

func TrashVisible

func TrashVisible(ctx context.Context) bool

TrashVisible - whether ctx's node queries keep the nodes in the trash (WithTrashed, or the site's own lookups - WithAllNodeTypes: a slug a node in the trash has stays taken).

func UserAlias

func UserAlias(slug string) string

UserAlias - the <alias> of a stored slug.

func UserIDs

func UserIDs(v any) []int

UserIDs - a user field's value: its users' IDs in the editor's order (a field with one value holds at most one); none for anything else.

func UserRoleNames

func UserRoleNames(user *User) []string

UserRoleNames - the roles a visitor has for role conditions: guests - RoleAnonymous; signed-in users - the base role plus their own.

func UserSlug

func UserSlug(username string) string

UserSlug - the path of a user's profile for the username: the name with spaces as dashes under UserPathPrefix.

func UserSlugFromAlias

func UserSlugFromAlias(alias string) string

UserSlugFromAlias - the stored slug of the profile /users/<alias>.

func UserURL

func UserURL(slug string) string

UserURL - the profile's URL for a stored slug.

func ValidViewGroupDateFormat

func ValidViewGroupDateFormat(f string) bool

ValidViewGroupDateFormat - f is "" or one of ViewGroupDate*.

func ViewDay

func ViewDay(t time.Time) int

ViewDay - t's day of the site (its time zone) as the views by day keep it: YYYYMMDD.

func ViewModuleChoiceMatch

func ViewModuleChoiceMatch(op ViewFilterOperator, value, v string, has bool) bool

ViewModuleChoiceMatch - whether a node's value v (has - it has one) passes a choice filter's operator against value ("" - no constraint).

func ViewModuleFilterMatch

func ViewModuleFilterMatch(op ViewFilterOperator, value string, v float64, has bool) bool

ViewModuleFilterMatch - whether a node's value (has - it has one) passes a module filter's operator against value (a number; "" or not a number - no constraint, the node passes).

func ViewModuleParams

func ViewModuleParams(params []ViewModuleParam, stored map[string]string) map[string]string

ViewModuleParams - the values of params from stored: each param's own when the param accepts it, else its Default. A value of no param is dropped.

func VisibleInLanguage

func VisibleInLanguage(kind, ref, lang string) bool

VisibleInLanguage - the thing (kind, ref) shows on a page in lang (SetLanguageVisibility; none set - everywhere).

func WithAllNodeTypes

func WithAllNodeTypes(ctx context.Context) context.Context

WithAllNodeTypes - ctx whose queries see all the content whatever the request's visitor may view: the site's own lookups, never shown as they are (a path taken, a menu link's address).

func WithContentVisitor

func WithContentVisitor(ctx context.Context, v ContentVisitor) context.Context

WithContentVisitor - ctx whose node and comment queries leave out what v may not view.

func WithTrashed

func WithTrashed(ctx context.Context) context.Context

WithTrashed - ctx whose node queries keep the nodes in the trash (Node.DeletedAt): the trash's own page, restoring, deleting for good.

func WithUserMemo

func WithUserMemo(ctx context.Context) context.Context

WithUserMemo - ctx keeping the users loaded by ID until it ends (a request's: the middleware chain sets it). A write of any user clears it (ForgetMemoizedUsers).

func Wrapped

func Wrapped[T any](v T, err error, what string, args ...any) (T, error)

Wrapped - v a repository returned, its error wrapped with what was done (a format of args).

Types

type AccountSettings

type AccountSettings struct {
	RegistrationMode         string
	RequireEmailVerification bool
	// UserTimezones - users may set their own time zone in the profile; off -
	// every page uses the site's zone.
	UserTimezones              bool
	RegistrationBlockedDomains string
	// AvatarAllowedExtensions/AvatarMaxFileSizeBytes - the avatar upload
	// policy, independent of the sitewide UploadSettings. nil/0 means unset -
	// see ResolveAvatarUploadPolicy. The resize target is the fixed
	// MaxAvatarDimension constant (a layout concern, not validation).
	AvatarAllowedExtensions []string
	AvatarMaxFileSizeBytes  int
	// TwoFactorRoles - the roles (ids) whose users must use two-factor
	// sign-in; TwoFactorIssuer - the site's name in the authenticator
	// ("" - the site's name).
	TwoFactorRoles  []int
	TwoFactorIssuer string
	// CancelContent - what a user deleting their own account (the
	// permission "cancel own account") leaves: CancelKeepContent - their
	// content, without an author (their comments go with the account);
	// CancelDeleteContent - none.
	CancelContent      string
	SubjWelcomeAdmin   string
	BodyWelcomeAdmin   string
	SubjWelcomePending string
	BodyWelcomePending string
	SubjWelcomeOpen    string
	BodyWelcomeOpen    string
	SubjActivation     string
	BodyActivation     string
	SubjPasswordReset  string
	BodyPasswordReset  string
	SubjEmailConfirm   string
	BodyEmailConfirm   string
	SubjAdminNotify    string
	BodyAdminNotify    string
}

AccountSettings holds registration policy and all email templates (single DB row).

func (AccountSettings) AvatarAllowedExtensionsString

func (s AccountSettings) AvatarAllowedExtensionsString() string

AvatarAllowedExtensionsString - space-separated, the format the admin form posts back (same as FieldInstanceDef.AllowedFileExtensionsString).

func (AccountSettings) AvatarMaxFileSizeMB

func (s AccountSettings) AvatarMaxFileSizeMB() float64

AvatarMaxFileSizeMB - AvatarMaxFileSizeBytes in MB, for the admin form's megabyte-denominated input. 0 when unset.

func (AccountSettings) BlockedDomains

func (s AccountSettings) BlockedDomains() []string

BlockedDomains - RegistrationBlockedDomains as host suffixes: one domain per line, # starts a comment line, a leading @ is stripped, empty lines are skipped; lowercase.

func (AccountSettings) EmailDomainBlocked

func (s AccountSettings) EmailDomainBlocked(email string) bool

EmailDomainBlocked reports whether the email's domain may not register: a blocked domain or its subdomain (blocked "foo.com" matches "foo.com" and "x.foo.com").

type AccountSettingsRepository

type AccountSettingsRepository interface {
	Get(ctx context.Context) (*AccountSettings, error)
	Update(ctx context.Context, s *AccountSettings) error
}

AccountSettingsRepository persists account / email template settings.

type AdminCommentsListFilter

type AdminCommentsListFilter struct {
	Status int8   // Comment*: the list's tab
	SortBy string // AdminCommentsSort*; invalid/empty = created_at sort with Desc
	Desc   bool   // ascending when false (applies to default created_at sort too)
	Limit  int
	Offset int
}

AdminCommentsListFilter defines the status, sort and pagination of the admin comments list.

type AdminMenuItem

type AdminMenuItem struct {
	Label      string
	Path       string
	Group      string
	Module     string
	Feature    string
	Permission string
	Count      int
	CountLabel string
}

AdminMenuItem - a link in a section. Group starts a titled group within the dropdown; Module/Feature hide the item while that module or feature is off; Permission - needed besides access to the admin. Count - the number shown by it (what waits there, e.g. new reports): set for each page from its counter (service.RegisterAdminMenuCount), 0 - none; CountLabel - what the number counts where the Overview lists it ("" - the item's Label).

type AdminMenuSection

type AdminMenuSection struct {
	Label string
	Path  string
	// Exact - the section is current on its Path only, not the pages
	// under it (the Overview, /admin).
	Exact bool
	Items []AdminMenuItem
	// CreateContent - the section ends with the "Create content" submenu
	// (the user's creatable types).
	CreateContent bool
}

AdminMenuSection - a section of the admin toolbar: a link (Path set, no Items) or a dropdown of Items.

func AdminMenu

func AdminMenu() []AdminMenuSection

AdminMenu - the admin toolbar, in order: the core's sections with the registered modules' pages added to theirs (each item tagged with its module): after the last item of the item's group, else at the end. Labels are i18n.N sources, translated when rendered.

type AdminNodesFilter

type AdminNodesFilter struct {
	Status       *int // 0=unpublished, 1=published
	OnModeration *int // 0=not on moderation, 1=on moderation
	// Scheduled - only the nodes with a scheduled publishing or
	// unpublishing (PublishOn, UnpublishOn).
	Scheduled bool
	Type      *string
	// Path - a part of the address (nodes.slug); empty - any.
	Path string
	// Search - a part of the title (any case) or of the address; empty -
	// any.
	Search string
	SortBy string // AdminNodesSort*; empty = updated_at desc (default)
	Desc   bool   // ignored when SortBy is empty
	Limit  int
	Offset int
}

AdminNodesFilter defines filters for admin content list

type AdminPeopleListOpts

type AdminPeopleListOpts struct {
	SortBy string // AdminPeopleSortCreated or AdminPeopleSortLastAccess
	Desc   bool
	Status *int // if non-nil, filter by users.status (e.g. pending = 2)
	RoleID *int // if non-nil, filter by users.role_id
}

AdminPeopleListOpts controls ordering and optional filter for UserRepository.ListForAdmin.

type BlockDef

type BlockDef struct {
	ID    int
	Title string
	// MachineName - what a text or a template embeds the block by
	// ([[block:<name>]]): unique, [a-z][a-z0-9_]*; a new block without one
	// gets one from its title.
	MachineName string
	// ShowTitle - whether Title renders as an <h2> above the block. Title itself
	// is always required, so this is the only way to hide the heading.
	ShowTitle bool
	Body      string
	// TextFormatID - nil means Body is sanitized with htmlsanitize.SanitizeAdmin.
	// When set, the format's AllowedTags apply (htmlsanitize.SanitizeWithFormat),
	// e.g. to allow a raw <script> for an ad block. Not a FK: a deleted format
	// falls back to SanitizeAdmin on the next save.
	TextFormatID *int
	Status       bool
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

BlockDef - a custom block: rich text the administrator edits without a deploy. Body is sanitized on save (htmlsanitize.SanitizeAdmin by default, or the format chosen in TextFormatID).

func (BlockDef) TextFormatIDValue

func (b BlockDef) TextFormatIDValue() int

TextFormatIDValue returns TextFormatID dereferenced (0 = unset).

type BlockItem

type BlockItem struct {
	ID          int
	Type        string
	Fields      FieldInstanceDefs
	Values      map[int]any
	TextFormats map[int]int
	Snapshot    *NodeSnapshot
}

BlockItem - one item of a blocks field (FieldTypeBlocks): a node of a field set (a content type with Embedded) whose parent is the node holding the field. Type - the set's machine name; Fields, Values and TextFormats - its fields and their values by field instance ID, as a DynamicContent's. ID 0 - not saved yet. Snapshot - the item as a revision keeps it, when read from one (NodeSnapshot.Values): its values by machine name, resolved with the set's fields on reverting.

func BlockItems

func BlockItems(v any) []BlockItem

BlockItems - a blocks field's value: its items in order; the items of a list's batch (their IDs alone, []int) without their content.

func (BlockItem) MarshalJSON

func (b BlockItem) MarshalJSON() ([]byte, error)

MarshalJSON - the item as a revision keeps it (blockItemSnapshot).

func (BlockItem) Summary

func (b BlockItem) Summary() string

Summary - what an item is in a line: its first texts (an HTML one as text), "-" between them, up to blockSummaryLen characters; "" - no text. The item node's title, the heading of its folded card in the form.

func (*BlockItem) UnmarshalJSON

func (b *BlockItem) UnmarshalJSON(raw []byte) error

UnmarshalJSON - an item from a revision: its set and Snapshot.

type BlockPlacementDef

type BlockPlacementDef struct {
	ID     int
	Theme  string
	Region Region
	Weight int
	// PluginConfig - a plugin block's settings (key → value), e.g. the
	// "target" of a block that shows one thing (PluginBlockTargets); nil
	// on an update - kept as stored.
	PluginConfig map[string]string
	// PlacementType - exactly one of BlockID (custom), PluginID (plugin),
	// ViewDisplayID (view) or MenuID (menu) is set.
	PlacementType BlockPlacementType
	BlockID       *int
	PluginID      *PluginBlockID
	// ViewDisplayID - set only for BlockPlacementView; FK to a ViewDisplayDef.
	ViewDisplayID *int
	// MenuID - set only for BlockPlacementMenu; FK to a MenuDef.
	MenuID *int
	// MenuStartLevel - initial visibility level (1-10): 1 renders the menu tree
	// from the top; N>1 renders from the current page's active trail N-1 levels
	// down, and is empty when the page is not under that branch (see
	// service.ResolveMenuBlockRoot). Used only by menu placements.
	MenuStartLevel int
	// MenuLevelsToShow - number of levels to display (0-9); 0 means unlimited.
	MenuLevelsToShow int
	// Title/ShowTitle - the placement's own title, used by plugin placements
	// (custom blocks use BlockDef.Title; views and menus use their own labels).
	Title                 string
	ShowTitle             bool
	VisibilityScope       BlockVisibilityScope
	VisibilityContentType *string
	// VisibilityPages/VisibilityPagesMode - used only when
	// VisibilityScope==BlockVisibilityPages.
	VisibilityPages     string
	VisibilityPagesMode BlockVisibilityPagesMode
	// VisibilityRoles - role names the placement is shown to (comma-
	// separated, RoleAnonymous for guests), combined with the scope;
	// empty - everyone.
	VisibilityRoles string
	// Lazy - the page gets a placeholder (the theme's
	// block_placeholder_<region>) and the content is loaded when it
	// scrolls near the viewport (GET /api/block-placement/{id}).
	Lazy      bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

BlockPlacementDef - where a block is shown: theme region, order within the region (Weight) and visibility. Kept separate from BlockDef.

func (BlockPlacementDef) HasRole

func (p BlockPlacementDef) HasRole(name string) bool

HasRole reports whether name is in the roles condition.

func (BlockPlacementDef) IsMenu

func (p BlockPlacementDef) IsMenu() bool

IsMenu reports whether this is a menu placement.

func (BlockPlacementDef) IsPlugin

func (p BlockPlacementDef) IsPlugin() bool

IsPlugin reports whether this is a plugin placement.

func (BlockPlacementDef) IsView

func (p BlockPlacementDef) IsView() bool

IsView reports whether this is a View placement.

func (BlockPlacementDef) MatchesContentType

func (p BlockPlacementDef) MatchesContentType(contentType string) bool

MatchesContentType reports whether contentType is in VisibilityContentTypes; used for BlockVisibilityContentType.

func (BlockPlacementDef) MenuIDValue

func (p BlockPlacementDef) MenuIDValue() int

MenuIDValue returns MenuID dereferenced (0 = unset).

func (BlockPlacementDef) PluginIDValue

func (p BlockPlacementDef) PluginIDValue() PluginBlockID

PluginIDValue returns PluginID dereferenced ("" = unset).

func (BlockPlacementDef) PluginSetting

func (p BlockPlacementDef) PluginSetting(key string) string

PluginSetting - a plugin block's setting ("" - unset).

func (BlockPlacementDef) PluginSettingOr

func (p BlockPlacementDef) PluginSettingOr(s PluginBlockSetting) string

PluginSettingOr - the placement's value of setting s, its Default while unset or no longer valid (an option gone, a number out of range).

func (BlockPlacementDef) Roles

func (p BlockPlacementDef) Roles() []string

Roles - VisibilityRoles as a list.

func (BlockPlacementDef) ViewDisplayIDValue

func (p BlockPlacementDef) ViewDisplayIDValue() int

ViewDisplayIDValue returns ViewDisplayID dereferenced (0 = unset).

func (BlockPlacementDef) VisibilityContentTypeValue

func (p BlockPlacementDef) VisibilityContentTypeValue() string

VisibilityContentTypeValue returns VisibilityContentType dereferenced ("" = unset); templates can't compare a *string with a string.

func (BlockPlacementDef) VisibilityContentTypes

func (p BlockPlacementDef) VisibilityContentTypes() []string

VisibilityContentTypes splits VisibilityContentType (a comma-separated list of content type machine names).

func (BlockPlacementDef) VisibleToRoles

func (p BlockPlacementDef) VisibleToRoles(roles []string) bool

VisibleToRoles reports whether a visitor with these roles may see the placement: no roles condition, or one of the roles matches.

type BlockPlacementOrderUpdate

type BlockPlacementOrderUpdate struct {
	PlacementID int
	Region      Region
	Weight      int
}

BlockPlacementOrderUpdate - one row of a bulk reorder (see BlockRepository.ReorderPlacements).

type BlockPlacementType

type BlockPlacementType string

BlockPlacementType - what a BlockPlacementDef references: a BlockDef (custom), a PluginBlockID (plugin), a view display or a menu.

const (
	BlockPlacementCustom BlockPlacementType = "custom"
	BlockPlacementPlugin BlockPlacementType = "plugin"
	// BlockPlacementView - a View's "Block" display placed like any other block.
	BlockPlacementView BlockPlacementType = "view"
	// BlockPlacementMenu - a MenuDef placed as a block; every menu is placeable
	// without an extra "expose as block" step.
	BlockPlacementMenu BlockPlacementType = "menu"
)

The kinds of block placements (BlockPlacementDef's type).

type BlockRepository

type BlockRepository interface {
	// Blocks - every placement of one theme (with its block, View or menu).
	Blocks(ctx context.Context, theme string) ([]BlockWithPlacement, error)
	BlockByID(ctx context.Context, id int) (*BlockDef, error)
	// BlockByMachineName - the block named name (BlockDef.MachineName);
	// MachineNameTaken - whether a block other than excludeID has name.
	BlockByMachineName(ctx context.Context, name string) (*BlockDef, error)
	MachineNameTaken(ctx context.Context, name string, excludeID int) (bool, error)
	// SearchBlocks - the blocks whose title or machine name has query
	// ("" - any), by title, at most limit.
	SearchBlocks(ctx context.Context, query string, limit int) ([]BlockDef, error)
	// CreateBlock creates the block (named from its title when it has no
	// MachineName) and its placement.
	CreateBlock(ctx context.Context, b BlockDef, p BlockPlacementDef) (*BlockDef, error)
	UpdateBlock(ctx context.Context, b BlockDef) (*BlockDef, error)
	// DeleteBlock deletes a block together with its placements (cascaded in
	// application code, not by FK).
	DeleteBlock(ctx context.Context, id int) error

	// CreatePluginPlacement creates a plugin placement (no BlockDef row).
	CreatePluginPlacement(ctx context.Context, p BlockPlacementDef) (*BlockPlacementDef, error)
	// CreateViewPlacement creates a View placement (no BlockDef row).
	CreateViewPlacement(ctx context.Context, p BlockPlacementDef) (*BlockPlacementDef, error)
	// CreateMenuPlacement creates a menu placement (no BlockDef row).
	CreateMenuPlacement(ctx context.Context, p BlockPlacementDef) (*BlockPlacementDef, error)
	// DeletePlacement deletes any placement by its own ID without touching a
	// BlockDef; needed for placements that have no owning block.
	DeletePlacement(ctx context.Context, placementID int) error

	PlacementByBlockID(ctx context.Context, blockID int, theme string) (*BlockPlacementDef, error)
	ThemeHasPlacements(ctx context.Context, theme string) (bool, error)
	CopyPlacement(ctx context.Context, p BlockPlacementDef) (*BlockPlacementDef, error)
	// PlacementByID returns any placement by its own ID (PlacementByBlockID
	// only works for custom placements).
	PlacementByID(ctx context.Context, id int) (*BlockPlacementDef, error)
	UpdatePlacement(ctx context.Context, p BlockPlacementDef) (*BlockPlacementDef, error)
	// PublishedPlacementsByRegion returns published placements of one region,
	// ordered by Weight. Raw data for the cache: per-page visibility filtering
	// happens later, per request. A custom placement is published when
	// BlockDef.Status is set; other placements are published while they exist.
	PublishedPlacementsByRegion(ctx context.Context, theme string, region Region) ([]BlockWithPlacement, error)
	// ReorderPlacements bulk-updates Weight/Region after drag-and-drop.
	ReorderPlacements(ctx context.Context, updates []BlockPlacementOrderUpdate) error
}

BlockRepository - storage port for blocks and their placements.

type BlockVisibilityPagesMode

type BlockVisibilityPagesMode string

BlockVisibilityPagesMode - see BlockVisibilityPages.

const (
	// BlockVisibilityPagesShow - visible only on pages matching VisibilityPages.
	BlockVisibilityPagesShow BlockVisibilityPagesMode = "show"
	// BlockVisibilityPagesHide - visible everywhere except pages matching VisibilityPages.
	BlockVisibilityPagesHide BlockVisibilityPagesMode = "hide"
)

type BlockVisibilityScope

type BlockVisibilityScope string

BlockVisibilityScope - which pages a block placement is shown on.

const (
	BlockVisibilityAll         BlockVisibilityScope = "all"
	BlockVisibilityHomepage    BlockVisibilityScope = "homepage"
	BlockVisibilityContentType BlockVisibilityScope = "content_type"
	// BlockVisibilityPages - a path list (VisibilityPages, one pattern per line);
	// VisibilityPagesMode decides whether it is an allowlist or a blocklist.
	// See service.MatchesVisibilityPages.
	BlockVisibilityPages BlockVisibilityScope = "pages"
)

The block placements' visibility scopes: every page, the home page, the pages of the chosen content types, or a path list.

type BlockWithPlacement

type BlockWithPlacement struct {
	Block     BlockDef
	Placement BlockPlacementDef
	// ViewDisplay - the referenced display, eager-loaded; set only when Placement.IsView().
	ViewDisplay *ViewDisplayDef
	// Menu - the referenced menu, eager-loaded; set only when Placement.IsMenu().
	Menu *MenuDef
	// PluginData - a plugin block's data for its template, loaded by the
	// cache refresh from its settings (service.SetPluginBlockData); nil
	// for a block without one.
	PluginData any
}

BlockWithPlacement - a BlockDef with its placement, as used by the admin list and region rendering. Block is zero for non-custom placements.

type BlockedBot

type BlockedBot struct {
	ID        int
	Pattern   string // substring to match in User-Agent (case-insensitive)
	Comment   string // free-text note, e.g. why this was blocked
	CreatedAt time.Time
}

BlockedBot represents a User-Agent pattern to block

type BlockedBotRepository

type BlockedBotRepository interface {
	List(ctx context.Context) ([]BlockedBot, error)
	Create(ctx context.Context, pattern, comment string) (*BlockedBot, error)
	Delete(ctx context.Context, id int) error
}

BlockedBotRepository defines the interface for blocked bot data access

type BlockedIP

type BlockedIP struct {
	ID        int
	IP        string // single IP (192.168.1.1) or CIDR (192.168.0.0/24)
	Comment   string // free-text note, e.g. why this was blocked
	CreatedAt time.Time
}

BlockedIP represents an IP or CIDR range to block

type BlockedIPRepository

type BlockedIPRepository interface {
	List(ctx context.Context) ([]BlockedIP, error)
	Create(ctx context.Context, ip, comment string) (*BlockedIP, error)
	Delete(ctx context.Context, id int) error
}

BlockedIPRepository defines the interface for blocked IP data access

type BreadcrumbItem struct {
	URL   string
	Label string
}

BreadcrumbItem - one link of a page's breadcrumb trail; an empty URL is the current page (rendered as text).

type BreadcrumbRuleDef struct {
	ID          int
	ContentType string
	// FieldStorageID - the taxonomy field the condition reads; nil = the
	// rule matches every node of ContentType.
	FieldStorageID *int
	// TermIDs - comma-separated term IDs for the field condition.
	TermIDs    string
	MenuLinkID int
	Weight     int
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

BreadcrumbRuleDef - "content type + optional taxonomy field and its terms → menu link": a node page whose type matches, and whose taxonomy field holds one of TermIDs or a descendant of one, gets the trail of MenuLinkID plus its own title. The lowest Weight wins.

func (r BreadcrumbRuleDef) FieldStorageIDValue() int

FieldStorageIDValue - FieldStorageID or 0.

func (r BreadcrumbRuleDef) HasTerm(id int) bool

HasTerm reports whether id is one of the rule's terms.

func (r BreadcrumbRuleDef) TermIDList() []int

TermIDList - TermIDs parsed (invalid entries skipped).

type BreadcrumbRuleDefs []BreadcrumbRuleDef

BreadcrumbRuleDefs - a list of breadcrumb rules.

type BreadcrumbRuleRepository interface {
	// BreadcrumbRules - all rules ordered by weight, then id.
	BreadcrumbRules(ctx context.Context) (BreadcrumbRuleDefs, error)
	BreadcrumbRuleByID(ctx context.Context, id int) (*BreadcrumbRuleDef, error)
	CreateBreadcrumbRule(ctx context.Context, r BreadcrumbRuleDef) (*BreadcrumbRuleDef, error)
	UpdateBreadcrumbRule(ctx context.Context, r BreadcrumbRuleDef) (*BreadcrumbRuleDef, error)
	UpdateBreadcrumbRuleWeight(ctx context.Context, id, weight int) error
	DeleteBreadcrumbRule(ctx context.Context, id int) error
}

BreadcrumbRuleRepository - storage port for the breadcrumb rules.

type CaptchaSettings

type CaptchaSettings struct {
	// Enabled - the master switch: off means no CAPTCHA on any form; the
	// keys and Forms are kept.
	Enabled   bool
	SiteKey   string
	SecretKey string
	// Forms - form name (CaptchaForm*) → shown.
	Forms map[string]bool
}

CaptchaSettings - reCAPTCHA v2 keys and the forms that show it (one row). Empty keys mean the server config's keys apply.

type CaptchaSettingsRepository

type CaptchaSettingsRepository interface {
	Get(ctx context.Context) (*CaptchaSettings, error)
	Update(ctx context.Context, s *CaptchaSettings) error
}

CaptchaSettingsRepository stores the CAPTCHA settings row.

type Comment

type Comment struct {
	ID        int
	Nid       int
	ParentID  *int
	CreatedBy int
	Subject   *string
	Content   string
	CreatedAt time.Time
	UpdatedAt time.Time
	Status    int8 // CommentPublished, CommentPending, CommentSpam
	// HoldReason - why it waits for approval or is spam (CommentReason*),
	// "" - none.
	HoldReason string
	Depth      int // Nesting depth (0 = root comment)
	Node       *Node
	Author     *User
	Parent     *Comment
	Children   Comments
}

Comment - a comment on a node (Nid): a root one, or a reply to ParentID; Node, Author, Parent and Children are set where loaded.

func (Comment) Summary

func (c Comment) Summary() string

Summary - the comment in a list line: its subject, or the start of its text as plain text (cut at a word, with "…") when it has none, as new comments don't.

type CommentMode

type CommentMode string

CommentMode - per-node comment visibility: Open (comments shown, posting allowed), Closed (shown, posting disabled - enforced server-side too), Hidden (not rendered). ContentTypeDef.DefaultCommentMode is copied onto a new node at creation only; changing the type default later never touches existing nodes.

const (
	CommentModeOpen   CommentMode = "open"
	CommentModeClosed CommentMode = "closed"
	CommentModeHidden CommentMode = "hidden"
)

The comment modes (CommentMode).

func (CommentMode) OrDefault

func (m CommentMode) OrDefault() CommentMode

OrDefault - the mode as stored on a node: "" (a form that doesn't carry the mode) is open, so nodes.comment_mode never gets an empty string.

type CommentSettings

type CommentSettings struct {
	// NewAuthorChecks - how many of an author's first comments wait for
	// approval (counting their published ones): 0 - none, -1 - all.
	NewAuthorChecks int
	// LinksLimit - a comment with more links waits for approval (-1 - no
	// limit).
	LinksLimit int
	// StopWords - one per line; a comment with one (in its text or a
	// link's address, case aside) waits or is refused: StopWordsAction.
	StopWords       string
	StopWordsAction string
	// DuplicateHours - the same text by the same author again within that
	// is refused (0 - allowed).
	DuplicateHours int
	// SpamKeepDays - spam is deleted that long after it was marked (0 -
	// kept).
	SpamKeepDays int
	// BotTrap - the forms (a comment's, registration, web forms) carry a
	// field hidden from people that bots fill, and the time they took: one
	// sent sooner than BotMinSeconds is a bot's.
	BotTrap       bool
	BotMinSeconds int
	// LoadWithPage - a content page has its comments in its HTML (search
	// engines read them, they show without JavaScript); false - they load
	// once the visitor scrolls to them (ajax).
	LoadWithPage bool
}

CommentSettings - what is done with suspicious comments (one row, the page /admin/config/comments).

func DefaultCommentSettings

func DefaultCommentSettings() CommentSettings

DefaultCommentSettings - the settings until they are saved.

func (CommentSettings) StopWordList

func (s CommentSettings) StopWordList() []string

StopWordList - StopWords' words, lower-cased, without blank lines.

type CommentSettingsRepository

type CommentSettingsRepository interface {
	// Get - the settings; DefaultCommentSettings when none are saved.
	Get(ctx context.Context) (CommentSettings, error)
	Update(ctx context.Context, s CommentSettings) error
}

CommentSettingsRepository stores the comment settings row.

type Comments

type Comments []Comment

Comments - a list of comments.

type CommentsFilter

type CommentsFilter struct {
	Nid       *int
	ParentID  *int
	CreatedBy *int
	Status    *int8
	Offset    int
	Limit     int
}

CommentsFilter - the comments Find and TotalCount select: a nil field matches any; Offset and Limit page them.

type CommentsRepository

type CommentsRepository interface {
	Find(ctx context.Context, filter CommentsFilter) (Comments, error)
	ListForAdmin(ctx context.Context, filter AdminCommentsListFilter) (Comments, int, error)
	ByID(ctx context.Context, id int) (*Comment, error)
	ByNodeID(ctx context.Context, nid int, status int8) (Comments, error)
	ByCreatedByPaginated(ctx context.Context, userID int, status int8, limit int, offset int) (Comments, error)
	ByNodeIDPaginated(ctx context.Context, nid int, status int8, limit int, offset int) (Comments, error)
	TotalCount(ctx context.Context, filter CommentsFilter) (int, error)
	CountByNodeID(ctx context.Context, nid int, status int8, rootOnly bool) (int, error)
	CountByNodeIDs(ctx context.Context, nids []int, status int8, rootOnly bool) (map[int]int, error)
	GetLatestComments(ctx context.Context, limit int, status int8, excludeTypes []string) (Comments, error)
	// ListRecentPublished returns published comments site-wide (including forum), except on nodes of excludeTypes, newest first, with total count.
	ListRecentPublished(ctx context.Context, status int8, excludeTypes []string, limit int, offset int) (Comments, int, error)
	GetCommentPath(ctx context.Context, commentID int) (string, error)
	CountCommentsWithPathLEQ(ctx context.Context, nid int, status int8, path string) (int, error)
	Create(ctx context.Context, c *Comment) (*Comment, error)
	Update(ctx context.Context, id int, c *Comment) (*Comment, error)
	// SetStatus sets the comment's status and the reason for it ("" -
	// none).
	SetStatus(ctx context.Context, id int, status int8, reason string) error
	// Delete removes the comment together with all its replies (the whole
	// subtree).
	Delete(ctx context.Context, id int) error
	// DescendantIDs returns the IDs of all replies to the comment, at any
	// depth.
	DescendantIDs(ctx context.Context, id int) ([]int, error)
	// NodeIDsByAuthor - the nodes the user has comments on (each once).
	NodeIDsByAuthor(ctx context.Context, userID int) ([]int, error)
	DeleteByNodeID(ctx context.Context, nodeID int) error
	// HasDuplicate - the author has a comment with this very text since
	// then (any status).
	HasDuplicate(ctx context.Context, authorID int, content string, since time.Time) (bool, error)
	// SpamBefore - the spam comments last changed (marked) before then.
	SpamBefore(ctx context.Context, before time.Time) ([]int, error)
}

CommentsRepository - storage port for the comments.

type Consent struct {
	Enabled      bool
	Mode         ConsentMode
	Text         string
	PolicyURL    string
	Version      int
	MetrikaGroup ConsentGroup
	GAGroup      ConsentGroup
	HeadGroup    ConsentGroup
	BodyEndGroup ConsentGroup
}

Consent - the cookie banner (IntegrationSettings.Consent): on or off, its mode, its text ("" - the default, in the site's language), its "More" page, its version (raised - every visitor is asked again), and each code's group.

func (Consent) Waits

func (c Consent) Waits(g ConsentGroup) bool

Waits - whether a code of group g waits for the visitor's consent: the banner on, asking, g a group.

type ConsentGroup

type ConsentGroup string

ConsentGroup - a group of codes a visitor allows or not: "" (ConsentNone) - needs no consent, runs on every page.

const (
	ConsentNone      ConsentGroup = ""
	ConsentAnalytics ConsentGroup = "analytics"
	ConsentMarketing ConsentGroup = "marketing"
)

The consent groups: none (always runs), analytics, marketing.

func ParseConsentGroup

func ParseConsentGroup(g string) ConsentGroup

ParseConsentGroup - g if it's one of ConsentGroups, else ConsentNone.

type ConsentMode

type ConsentMode string

ConsentMode - what the banner asks: ConsentAsk - the codes of a group run only once the visitor allows it; ConsentNotice - they run at once, the banner tells about them.

const (
	ConsentAsk    ConsentMode = "consent"
	ConsentNotice ConsentMode = "notice"
)

The banner's modes (ConsentMode).

type ContentType

type ContentType string

ContentType - a content type's machine name (Node.Type).

func NodeTypesByLabel

func NodeTypesByLabel(labels map[string]string) []ContentType

NodeTypesByLabel - the node types of labels (machine name → label, ContentTypeService.NodeTypeLabels) sorted by label: a "Type" filter's options.

func (ContentType) ToString

func (c ContentType) ToString() string

ToString - the machine name as a string.

type ContentTypeDef

type ContentTypeDef struct {
	ID          int
	MachineName string
	Label       string
	// PathPattern - the URL alias pattern of this type's nodes, tokens in
	// brackets like the SEO templates' ([node:type]/[node:title]); "" -
	// DefaultNodePathPattern. A node follows it while its PathAuto is
	// on (service.NodePathService).
	PathPattern string
	Description string
	// Status - 1 enabled, 0 disabled: a disabled type takes no new
	// content (Creatable); its existing content is shown and edited as
	// before.
	Status int
	// DefaultPromote/DefaultSticky - a new node's Node.Promote ("on the
	// front page") and Node.Sticky; an editor without "administer
	// content" gets them as they are.
	DefaultPromote bool
	DefaultSticky  bool
	// DefaultPublishing - how a new node comes out: published, on
	// moderation or unpublished; an editor without "administer content"
	// gets it as it is (and keeps an edited node's own), who may sets it
	// in the form.
	DefaultPublishing NodePublishing
	// DefaultCommentMode is copied onto Node.CommentMode when a node of
	// this type is created; later changes never affect existing nodes.
	DefaultCommentMode CommentMode
	// HideEmptyComments hides the comments section (including the form)
	// while the node has no comments.
	HideEmptyComments bool
	// TitleDisplay - how the page heading combines the title and the
	// alternative title (AltTitleField).
	TitleDisplay TitleDisplay
	// RedirectField - machine_name of a text field holding a URL; the node
	// page redirects there instead of rendering. "" or an empty value
	// renders the page normally.
	RedirectField string
	// AltTitleField - machine_name of a text field holding the alternative
	// (e.g. translated) title, "" - none. Used by TitleDisplay, the default
	// page title, the Views title field and TeaserItem.AltTitle.
	AltTitleField string
	// ShowSubmitted shows author and dates on the node page.
	ShowSubmitted bool
	// ShowViewCount shows the view counter next to author and dates.
	ShowViewCount bool
	// Revisions - every save of the type's nodes is kept as a revision
	// (NodeRevision): compared, brought back.
	Revisions bool
	// RevisionsKeep - how many of a node's revisions are kept, the oldest
	// pruned beyond; 0 - all.
	RevisionsKeep int
	// Embedded - a field set: its nodes are items of the blocks fields
	// (FieldTypeBlocks) of other content, not content of their own -
	// no page, address, lists, search or permissions; ContentTypes leaves
	// it out (FieldSets lists them).
	Embedded bool
	// ViewRoles - the roles who may view the type's content (role names;
	// RoleAnonymous for guests, RoleUser for everyone signed in); empty -
	// everyone. Its pages, lists, search, feeds and files are kept from
	// the others (service.ContentAccess).
	ViewRoles []string
	CreatedBy int
	CreatedAt time.Time
	UpdatedAt time.Time
}

ContentTypeDef - an admin-defined content type. Its MachineName becomes node.Type at runtime without a Go constant. Not to be confused with ContentType (node.go): a node's type name, an admin-defined type's or one a module declares (Module.NodeTypes).

func (ContentTypeDef) Creatable

func (d ContentTypeDef) Creatable() bool

Creatable - new content of the type may be created: the type is enabled (Status).

func (ContentTypeDef) ViewableBy

func (d ContentTypeDef) ViewableBy(roles []string) bool

ViewableBy reports whether a visitor with roles (UserRoleNames) may view the type's content by its ViewRoles.

type ContentTypeDefs

type ContentTypeDefs []ContentTypeDef

ContentTypeDefs - a list of content types.

type ContentTypeFieldType

type ContentTypeFieldType string

ContentTypeFieldType - the field storage type; each maps to its own typed field_value_* table.

const (
	// FieldTypeText covers both short strings and rich long-form content
	// (stored in field_value_text). Editing/rendering is chosen by
	// Widget(), not by the storage type.
	FieldTypeText      ContentTypeFieldType = "text"
	FieldTypeNumber    ContentTypeFieldType = "number"
	FieldTypeDate      ContentTypeFieldType = "date"
	FieldTypeBool      ContentTypeFieldType = "bool"
	FieldTypeTaxonomy  ContentTypeFieldType = "taxonomy"
	FieldTypeReference ContentTypeFieldType = "reference"
	FieldTypeImage     ContentTypeFieldType = "image"
	// FieldTypeFile - a generic (non-image) upload such as PDF/DOCX/ZIP.
	// Stored like FieldTypeImage (value = entity.File ID); differs only in
	// upload validation (see ResolveFieldUploadPolicy) and display (a
	// download link instead of a thumbnail).
	FieldTypeFile ContentTypeFieldType = "file"
	// FieldTypeList - a fixed, admin-defined set of value/label pairs
	// (see AllowedValues). Stored in field_value_list, or
	// field_value_list_multi when Multiple(). Widget() picks the control:
	// WidgetSelect (any cardinality), WidgetRadio (single only) or
	// WidgetCheckboxes (multiple only).
	FieldTypeList ContentTypeFieldType = "list"
	// FieldTypeLink - web addresses with optional titles (Link), stored in
	// field_value_link in the editor's order whatever the cardinality.
	// Shown as links, or by a module's FieldFormatter (a video player,
	// say): the field instance's DetailFormatter, a View field's own.
	FieldTypeLink ContentTypeFieldType = "link"
	// FieldTypeUser - site users (their IDs, []int in the editor's order
	// whatever the cardinality, UserIDs), stored in field_value_user:
	// authors, members, the people in charge. Shown as links to their
	// profiles; a View's profile tab lists the content a user is in
	// (ViewFilterOperatorIsProfileUser).
	FieldTypeUser ContentTypeFieldType = "user"
	// FieldTypeEmail, FieldTypePhone - an e-mail address and a telephone
	// number, stored as text (field_value_text), checked on saving and
	// shown as a "write"/"call" link (an address hidden from harvesters
	// unless the field says otherwise: EmailPlain).
	FieldTypeEmail ContentTypeFieldType = "email"
	FieldTypePhone ContentTypeFieldType = "phone"
	// FieldTypeBlocks - composite blocks: items of a field set (a content
	// type with Embedded, BlockTypes), each a node of its own with its
	// parent (Node.ParentID), stored in field_value_block in the editor's
	// order. Its value - []BlockItem as DynamicContentRepository reads
	// it, item IDs in a list's batch (BlockItems).
	FieldTypeBlocks ContentTypeFieldType = "blocks"
	// FieldTypeGroup has no stored value. It is a container other fields
	// point at via FieldInstanceDef.ParentGroupID/FormGroupID so they
	// render as one section with a shared heading.
	FieldTypeGroup ContentTypeFieldType = "group"
)

The field storage types.

func (ContentTypeFieldType) AllowsMultiple

func (t ContentTypeFieldType) AllowsMultiple() bool

AllowsMultiple - the field type can hold several values per node (FieldInstanceDef.Multiple): taxonomy, list, reference, image, link, date and user fields.

type ContentTypeRepository

type ContentTypeRepository interface {
	// Content type CRUD
	// ContentTypes - the content types; the field sets (Embedded) are
	// FieldSets'.
	ContentTypes(ctx context.Context) (ContentTypeDefs, error)
	// FieldSets - the field sets (ContentTypeDef.Embedded), by label.
	FieldSets(ctx context.Context) (ContentTypeDefs, error)
	ContentTypeByID(ctx context.Context, id int) (*ContentTypeDef, error)
	ContentTypeByMachineName(ctx context.Context, machineName string) (*ContentTypeDef, error)
	CreateContentType(ctx context.Context, ct ContentTypeDef) (*ContentTypeDef, error)
	UpdateContentType(ctx context.Context, ct ContentTypeDef) (*ContentTypeDef, error)
	// DeleteContentType deletes the type with its fields (groups among
	// them), each as DeleteField does; the caller checks the type has no
	// nodes and runs it in a transaction.
	DeleteContentType(ctx context.Context, id int) error

	// Field CRUD (flat list ordered by SortOrder)
	FieldsByContentTypeID(ctx context.Context, contentTypeID int) (FieldInstanceDefs, error)
	FieldByID(ctx context.Context, id int) (*FieldInstanceDef, error)
	// CreateField atomically creates a new FieldStorageDef and an instance
	// referencing it. The machine name must be globally unused, otherwise
	// ErrFieldStorageMachineNameTaken.
	CreateField(ctx context.Context, f FieldInstanceDef) (*FieldInstanceDef, error)
	// UpdateField writes FieldStorageDef.Config (shared by all types using
	// the field) and the instance's Label/Required/HiddenInForm/FormGroupID.
	UpdateField(ctx context.Context, f FieldInstanceDef) (*FieldInstanceDef, error)
	// DeleteField deletes the instance and its values on that type's nodes;
	// when it was the storage's last instance and nothing else references
	// the storage (FieldStorageUsage), the storage leaves the catalog too
	// (a storage goes with its last field).
	DeleteField(ctx context.Context, id int) error
	// FieldStorageUsage - what still holds a catalog field.
	FieldStorageUsage(ctx context.Context, storageID int) (FieldStorageUsage, error)
	// NodesWithSeveralFieldValues - the nodes holding more than one value
	// of a multi-value field, sorted by ID.
	NodesWithSeveralFieldValues(ctx context.Context, storage FieldStorageDef) ([]int, error)
	// SetFieldMultiple switches a field between one and several values per
	// node: moves its values to the other value table, sets the storage's
	// "multiple" (and drops "symmetric" when single) and replaces the
	// instances' widgets the new cardinality doesn't allow.
	SetFieldMultiple(ctx context.Context, storageID int, multiple bool) error

	// FieldStorages - the whole catalog of reusable fields, for the
	// "add existing field" picker.
	FieldStorages(ctx context.Context) (FieldStorageDefs, error)
	// FieldStorageByID - a single catalog entry (used by the Views query
	// layer).
	FieldStorageByID(ctx context.Context, id int) (*FieldStorageDef, error)
	// FieldInstanceLabelsByFieldStorageIDs returns a human-readable label
	// per field_storage_id, taken from its first (by id) instance, since
	// FieldStorageDef has no label. Takes explicit IDs so public View
	// rendering loads only the fields it shows.
	FieldInstanceLabelsByFieldStorageIDs(ctx context.Context, fieldStorageIDs []int) (map[int]string, error)
	// RichTextFieldStorageIDs - which of fieldStorageIDs hold HTML: every
	// instance of the storage is RichText (a View shows values of all of
	// them, and one plain instance stores unsanitized text).
	RichTextFieldStorageIDs(ctx context.Context, fieldStorageIDs []int) (map[int]bool, error)
	// AttachExistingField attaches an existing FieldStorageDef to a content
	// type. Returns ErrFieldAlreadyAttached if it is already attached.
	AttachExistingField(ctx context.Context, contentTypeID, fieldStorageID int, label string, required bool, sortOrder int) (*FieldInstanceDef, error)

	// UpdateFieldSortOrder/UpdateFieldDetailDisplay update only the
	// settings of their own admin tab, so one tab never overwrites
	// another's values. formGroupID/parentGroupID move the field into a
	// group; nil clears membership.
	UpdateFieldSortOrder(ctx context.Context, fieldID int, sortOrder int, formGroupID *int) error
	UpdateFieldDetailDisplay(ctx context.Context, fieldID int, d FieldDetailDisplay) error

	// CountFieldValues counts values stored for this field on this content
	// type (for confirming detachment). Scoped by contentTypeID because
	// value rows are shared by every type using the field.
	CountFieldValues(ctx context.Context, contentTypeID, fieldID int, fieldType ContentTypeFieldType, multiple bool) (int, error)

	// Generic value storage - fans out over the typed value tables inside
	// the adapter.
	FieldValues(ctx context.Context, nodeID int, fields FieldInstanceDefs) (map[int]any, error)
	// FieldValuesForNodes - batch FieldValues (nodeID→fieldID→value): one
	// query per field for all nodes instead of one per (node × field).
	// Supports text/number/date/bool and image (the file ID) fields.
	FieldValuesForNodes(ctx context.Context, nodeIDs []int, fields FieldInstanceDefs) (map[int]map[int]any, error)
	// SetFieldValues's textFormats is keyed like values (FieldInstanceDef.ID),
	// see DynamicContent.TextFormats. nil is fine when text formats aren't
	// used.
	SetFieldValues(ctx context.Context, nodeID int, fields FieldInstanceDefs, values map[int]any, textFormats map[int]int) error
	// TextFormatIDsByNode - for the edit form: the TextFormatDef.ID each
	// existing value was saved with, keyed by FieldInstanceDef.ID. Callers
	// should pass only fields with non-empty AllowedTextFormatIDs() to
	// skip the query when text formats aren't used.
	TextFormatIDsByNode(ctx context.Context, nodeID int, fields FieldInstanceDefs) (map[int]int, error)

	// FieldTextValuesForNodes/FieldNumberValuesForNodes/FieldDateValuesForNodes
	// batch-resolve one field (fieldStorageID is FieldStorageDef.ID) for
	// many nodes in one query: node_id → value, only for nodes that have
	// one. For listings that read one field across many nodes.
	FieldTextValuesForNodes(ctx context.Context, fieldStorageID int, nodeIDs []int) (map[int]string, error)
	FieldNumberValuesForNodes(ctx context.Context, fieldStorageID int, nodeIDs []int) (map[int]float64, error)
	FieldDateValuesForNodes(ctx context.Context, fieldStorageID int, nodeIDs []int) (map[int]time.Time, error)
	// FieldTaxonomyValuesForNodes - same batch shape, for a
	// FieldTypeTaxonomy field: node_id -> term_id. Used by catalog
	// listings to filter by a term (e.g. ?category=<term id>).
	FieldTaxonomyValuesForNodes(ctx context.Context, fieldStorageID int, nodeIDs []int) (map[int]int, error)
	// FieldTaxonomyMultiValuesForNodes is FieldTaxonomyValuesForNodes for
	// a Multiple() taxonomy field: node_id -> all its term IDs (from
	// field_value_taxonomy_multi). Used for OR-match filtering and
	// displaying multi-value fields outside the generic field loop.
	FieldTaxonomyMultiValuesForNodes(ctx context.Context, fieldStorageID int, nodeIDs []int) (map[int][]int, error)
}

ContentTypeRepository - persistence port for content types, fields and generic field value storage.

type ContentVisitor

type ContentVisitor struct {
	// HiddenTypes - the content types they may not view, sorted.
	HiddenTypes []string
	// ItemRoles - some content item has view roles of its own
	// (Node.ViewRoles): the fields below decide which of them they view.
	ItemRoles bool
	// Roles - their roles (UserRoleNames), sorted: an item with view
	// roles is for them with one of these.
	Roles []string
	// UserID - the signed-in visitor (0 - a guest): their own items they
	// view whatever the items' view roles.
	UserID int
	// AllItems - they view every item of the types they may view,
	// whatever its view roles.
	AllItems bool
	// ItemTypes - the types whose every item they view (they may edit any
	// of them), sorted.
	ItemTypes []string
}

ContentVisitor - whose eyes a ctx's content queries are for (WithContentVisitor): what of the content they may not view.

func VisitorOf

func VisitorOf(ctx context.Context) (ContentVisitor, bool)

VisitorOf - ctx's visitor (WithContentVisitor), false for a ctx without one (a background job's: it sees everything, and gets what is shared); under WithAllNodeTypes one who is hidden nothing.

func (ContentVisitor) Key

func (v ContentVisitor) Key() string

Key - what they view, as a string: visitors with the same key view the same content, their own items aside (Shared).

func (ContentVisitor) Restricts

func (v ContentVisitor) Restricts() bool

Restricts - whether anything is hidden from them.

func (ContentVisitor) RestrictsItems

func (v ContentVisitor) RestrictsItems() bool

RestrictsItems - whether an item's own view roles may hide it from them.

func (ContentVisitor) Shared

func (v ContentVisitor) Shared() ContentVisitor

Shared - v without their own items: what is kept for every visitor with their Key.

type Counter

type Counter struct {
	NID        int
	TotalCount int
	DayCount   int
	LastViewed time.Time
}

Counter - a node's views (node_counter): all time, on the site's day of the last view, and the last view's time.

type CreatableMaterialLink struct {
	URL   string `json:"url"`
	Label string `json:"label"`
}

CreatableMaterialLink is a menu entry for "create material" UI (JSON in USER_DATA).

type DashboardRepository

type DashboardRepository interface {
	// Stats - the figures; since - the start of the recent period,
	// today - of the site's day (a view counts today from it).
	Stats(ctx context.Context, since, today time.Time) (DashboardStats, error)
	// OnModeration - how many content items wait on moderation (the
	// "Pending moderation" menu item's count).
	OnModeration(ctx context.Context) (int, error)
	// Popular - the published content viewed most in q's period, most
	// first, a page of it; and how many items there are in all.
	Popular(ctx context.Context, q PopularQuery) ([]PopularNode, int, error)
}

DashboardRepository - what the admin's Overview counts.

type DashboardStats

type DashboardStats struct {
	Published, PublishedSince int
	Comments, CommentsSince   int
	Users, UsersSince         int
	ViewsToday, ViewsTotal    int
}

DashboardStats - the figures of the admin's Overview: the published content, the comments and the users, all and since the start of the recent period; the content's views, today and all.

type DateFormat

type DateFormat struct {
	ID          int
	MachineName string
	Label       string
	Pattern     string
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

DateFormat - a named date format of the date formats catalog (/admin/config/date-formats): a pattern (internal/lib/dateformat) that date fields and Views fields pick by MachineName.

type DateFormatRepository

type DateFormatRepository interface {
	DateFormats(ctx context.Context) ([]DateFormat, error)
	DateFormatByID(ctx context.Context, id int) (*DateFormat, error)
	CreateDateFormat(ctx context.Context, f DateFormat) (int, error)
	UpdateDateFormat(ctx context.Context, f DateFormat) error
	DeleteDateFormat(ctx context.Context, id int) error
	// DateFormatUsage - the fields and Views fields that chose the
	// format, as readable labels.
	DateFormatUsage(ctx context.Context, machineName string) ([]string, error)
	// InstanceDateFormats - the formats chosen on date field instances:
	// "<content type>:<field storage id>" → format machine name.
	InstanceDateFormats(ctx context.Context) (map[string]string, error)
}

DateFormatRepository - the date_formats table.

type DatePart

type DatePart string

DatePart - whether a date field asks for a part of its value: the time or the end.

const (
	// DatePartNone - it doesn't: no time (a date), no end (one day).
	DatePartNone DatePart = ""
	// DatePartOptional - a value may have it.
	DatePartOptional DatePart = "optional"
	// DatePartRequired - every value has it.
	DatePartRequired DatePart = "required"
)

func ParseDatePart

func ParseDatePart(s string) DatePart

ParseDatePart - s as a DatePart; unknown - none.

type DateValue

type DateValue struct {
	Start    time.Time
	End      time.Time
	WithTime bool
}

DateValue - the value of a date field with a time or an end (FieldInstanceDef.DateRich): its start, its end (zero - none) and whether they have a time (WithTime: instants in UTC, shown in the page's zone; without one, dates at UTC midnight, shown as they are). A plain date field's value is a time.Time, a field with several dates' - a []DateValue in the editor's order (DateStart, AsDateValue, DateValues read them all).

func AsDateValue

func AsDateValue(v any) (DateValue, bool)

AsDateValue - a date field's value as a DateValue (a plain date - its start; several - the first); false - none.

func DateValues

func DateValues(v any) []DateValue

DateValues - a date field's value as its dates (one or several, in the editor's order); none for anything else.

func (DateValue) Ended

func (v DateValue) Ended(now time.Time, zone *time.Location) bool

Ended - the value is over at now (the date in zone for a value without a time): its end (else its start) has passed - a date without a time at the end of that day, one with a time at that moment.

func (DateValue) HasEnd

func (v DateValue) HasEnd() bool

HasEnd - the value has an end.

func (DateValue) MarshalJSON

func (v DateValue) MarshalJSON() ([]byte, error)

MarshalJSON - a date without a time and an end as a plain date field's (the instant as a string: the snapshots of a field that gained the settings stay comparable), else an object.

func (DateValue) Ongoing

func (v DateValue) Ongoing(now time.Time, zone *time.Location) bool

Ongoing - the value has started and not ended at now.

func (*DateValue) UnmarshalJSON

func (v *DateValue) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads both forms of MarshalJSON.

type DisplaySection

type DisplaySection struct {
	Group     *FieldInstanceDef
	Body      *FieldInstanceDef
	Image     *FieldInstanceDef
	Formatted *FieldInstanceDef
	Blocks    *FieldInstanceDef
	Fields    FieldInstanceDefs
}

DisplaySection is one rendered block of a node's detail page (dynamic/page.html), in DisplayOrder; every field renders at its own position (see DynamicContentController.buildDisplaySections). At most one of Group/Body/Image/Formatted/Blocks is set:

  • Group: a FieldTypeGroup's boxed ".item-fieldgroup" card, Fields its members.
  • Body: a single RendersInBody FieldTypeText field as a full-width body section.
  • Image: a single FieldTypeImage field as a full-width picture block.
  • Formatted: a single field a module's formatter shows (DetailFormatter, its module on) as a full-width block - a link field's videos, say.
  • Blocks: a blocks field (FieldTypeBlocks) with blocks, each shown by its field set's display - whatever its page group.
  • none: a contiguous run of compact fields (text/number/date/bool/ taxonomy/list/file/link) in Fields, rendered together in one ".item-characteristic" card.

type DisplaySections

type DisplaySections []DisplaySection

DisplaySections - a node page's field blocks in display order.

func (DisplaySections) Without

func (s DisplaySections) Without(machineNames ...string) DisplaySections

Without - the sections without the given fields (by machine_name), for a theme template that places those fields by hand; a section left empty is dropped.

type DynamicContent

type DynamicContent struct {
	Node        Node
	ContentType ContentTypeDef
	Fields      FieldInstanceDefs
	Values      map[int]any
	// TextFormats - keyed like Values: the TextFormatDef.ID chosen for each
	// FieldTypeText value that uses text formats. Absent for other fields
	// (text_format_id stays NULL).
	TextFormats map[int]int
	Tags        TaxonomyTerms
}

DynamicContent is the entity for a node of an admin-created content type. It has no static fields: Values holds one entry per field, keyed by FieldInstanceDef.ID and typed per FieldType (string for text, float64 for number, time.Time for date, bool for bool, int for taxonomy/reference/image - a term, node or file ID).

func (DynamicContent) FieldValueByMachineName

func (d DynamicContent) FieldValueByMachineName(machineName string) any

FieldValueByMachineName returns the stored value of the field with the given machine name (typed per FieldType), or nil if the field is not attached or not set.

func (DynamicContent) GetAltTitle

func (d DynamicContent) GetAltTitle() string

GetAltTitle - the alternative title: the value of the type's AltTitleField ("" when the type has none or it is empty).

func (DynamicContent) GetContent

func (d DynamicContent) GetContent() string

GetContent returns the value of the first text field that renders in the body, is shown on the detail page and is not in a group - the closest thing to a body field, used as a meta description fallback. The group check matters because grouped fields may also be ShowOnDetail and Fields is sorted by SortOrder, so a grouped field could otherwise win.

func (DynamicContent) GetNode

func (d DynamicContent) GetNode() Node

GetNode (with GetContent and GetAltTitle) implements interfaces.SEOProvider, so DynamicContent works with the generic PageSEO() helper.

type DynamicContentRepository

type DynamicContentRepository interface {
	Create(ctx context.Context, e *DynamicContent) (*DynamicContent, error)
	Update(ctx context.Context, e *DynamicContent) (*DynamicContent, error)
	ByNodeID(ctx context.Context, nodeID int) (*DynamicContent, error)
}

DynamicContentRepository - port for a content-type-scoped instance of the generic repository (see database.NewDynamicContentRepository). Built per request via a factory, since the content type is known only after the node/path is resolved.

type FeedImage

type FeedImage struct {
	Field string
	Style string
}

FeedImage - which image field (and style) a feed's items show.

type FeedNodeFilter

type FeedNodeFilter struct {
	Types   []string
	TermIDs []int
	Since   time.Time
	Limit   int
}

FeedNodeFilter - the materials a feed takes: published, not on moderation, of Types, tagged with any of TermIDs (none - any), created at or after Since (zero - any time), newest first, at most Limit.

type FieldAllowedValue

type FieldAllowedValue struct {
	Value string
	Label string
}

FieldAllowedValue - a stored value and its display label for FieldTypeList.

type FieldDetailDisplay

type FieldDetailDisplay struct {
	DisplayOrder  int
	ShowOnDetail  bool
	ShowLabel     bool
	RendersInBody bool
	ImageStyle    string
	// ListImageStyle - FieldInstanceDef.ListImageStyle.
	ListImageStyle string
	Formatter      string
	Layout         FieldLayout
	// ParentGroupID - the group on the page; nil - none.
	ParentGroupID *int
}

FieldDetailDisplay - a field's settings of the "Detail page" tab (ContentTypeRepository.UpdateFieldDetailDisplay): its place, whether it and its label show, and how - the image style (image fields), the formatter and the layout of several values (link fields).

type FieldInstanceDef

type FieldInstanceDef struct {
	ID             int
	ContentTypeID  int
	FieldStorageID int
	MachineName    string
	Label          string
	FieldType      ContentTypeFieldType
	Required       bool
	// HiddenInForm hides the field on the create/edit form while keeping
	// its stored value: the save path carries the existing value forward
	// instead of treating it as cleared (see
	// the hidden hooks of formFieldTypes).
	HiddenInForm bool
	// DefaultImageID - FieldTypeImage only: fallback entity.File shown when
	// the field is empty; nil - not configured. Rendered through the same
	// image styles as a real value (see
	// DynamicContentController.imageFieldURLs).
	DefaultImageID *int
	// ShowOnDetail/ShowLabel - whether the field and its label show on
	// the detail page (dynamic/page.html). Set via the detail-display tab
	// (ContentTypeService.UpdateFieldDetailDisplay), never the field form.
	ShowOnDetail bool
	ShowLabel    bool
	// RendersInBody - for an ungrouped FieldTypeText field: renders as a
	// full-width body section instead of in the fact-box (see
	// buildDisplaySections) and serves as the node body for the
	// meta-description fallback (DynamicContent.GetContent). A layout
	// choice, independent of Widget() and text formats. Set via
	// ContentTypeService.UpdateFieldDetailDisplay.
	RendersInBody bool
	// ShowLabelInList, ExcludeFromDisplay, FallbackFieldKey and TrimLength
	// are only populated on the synthetic FieldInstanceDefs Views builds
	// for dynamic/list.html (see
	// views.BuildContentFieldInstances), mirroring
	// the same-named ViewFieldDef settings. Never set on DB-backed fields.
	ShowLabelInList bool
	// ExcludeFromDisplay - the value is resolved but gets no slot of its
	// own; usable only as a {{field:<key>}} RewriteHTML token.
	ExcludeFromDisplay bool
	// FallbackFieldKey - see ApplyFieldFallbacks.
	FallbackFieldKey string
	// TrimLength - >0 strips HTML and truncates the value to that many
	// characters at render time.
	TrimLength int
	// DetailImageStyle - FieldTypeImage only: ImageStyleDef.Name used on
	// the detail page; "" - not configured. ListImageStyle - in lists:
	// the type's cards (entity.TeaserItem), a blocks field's items; "" -
	// the original. A View's field has its own (ViewFieldDef.ImageStyle).
	DetailImageStyle string
	ListImageStyle   string
	// DetailFormatter - FieldTypeLink only: the FieldFormatter showing the
	// field on the detail page ("" - links); DetailLayout - how its several
	// values show there. A Views field has its own (ViewFieldDef.Formatter,
	// on the synthetic instance's Config "formatter"/"layout").
	DetailFormatter string
	DetailLayout    FieldLayout
	// DateFormat - FieldTypeDate only: entity.DateFormat machine name;
	// "" - the default format. Views may override it
	// (ViewFieldDef.DateFormat).
	DateFormat string
	// SortOrder orders the create/edit form; DisplayOrder orders the
	// detail page. Each is set by its own admin tab's drag-and-drop.
	SortOrder    int
	DisplayOrder int
	// Config - FieldStorageDef.Config (denormalized), shared by every
	// content type the field is attached to. Holds only storage/validation
	// constraints: vocabulary_id, multiple, allowed_values,
	// target_content_type, max_len, pattern.
	Config map[string]any
	// WidgetConfig - per-content-type settings for editing the field
	// ("widget", text formats, upload settings), so the same storage can
	// be WYSIWYG on one type and a plain textarea on another.
	WidgetConfig map[string]any
	// ParentGroupID - the FieldTypeGroup field (on the same content type)
	// this field belongs to on the detail page; nil - none. Groups can't
	// nest. Set via ContentTypeService.UpdateFieldDetailDisplay.
	ParentGroupID *int
	// FormGroupID - like ParentGroupID but for the create/edit form
	// (node/edit_dynamic.html renders one collapsible section per group).
	// Independent of ParentGroupID: form and detail page may group fields
	// differently. nil - the default form section.
	FormGroupID *int
	// UsableInForm/UsableInDetail - FieldTypeGroup only: whether the group
	// can be targeted by FormGroupID and/or ParentGroupID, so a form-only
	// group doesn't appear in the detail-page group picker and vice versa.
	// Always false for other field types.
	UsableInForm   bool
	UsableInDetail bool
	CreatedAt      time.Time
	UpdatedAt      time.Time
}

FieldInstanceDef - a field attached to a ContentTypeDef with its per-type settings (label, required, order, display, widget). The definition itself (machine_name, field type, storage config) lives on the shared FieldStorageDef (field_storage.go), so one field can be attached to several content types sharing stored values (field_value_*.field_id references FieldStorageDef.ID).

MachineName/FieldType/Config are denormalized from the joined FieldStorageDef (see dao.ToFieldInstanceDefEntity).

func (FieldInstanceDef) AllowedFileExtensions

func (f FieldInstanceDef) AllowedFileExtensions() []string

AllowedFileExtensions - FieldTypeImage/FieldTypeFile: extensions without the dot (e.g. "jpg") accepted for this field. Per content type (WidgetConfig). Empty - FileUploadService.FieldUploadPolicy falls back to the site-wide UploadSettings for this setting.

func (FieldInstanceDef) AllowedFileExtensionsString

func (f FieldInstanceDef) AllowedFileExtensionsString() string

AllowedFileExtensionsString - space-separated, the format of the "Allowed file extensions" input (see fieldWidgetConfigFromForm).

func (FieldInstanceDef) AllowedHosts

func (f FieldInstanceDef) AllowedHosts() []string

AllowedHosts - FieldTypeLink: the sites its links may lead to (storage config "allowed_hosts"), lower case, without "www."; none - any site.

func (FieldInstanceDef) AllowedHostsString

func (f FieldInstanceDef) AllowedHostsString() string

AllowedHostsString - AllowedHosts space-separated, the format of the field's "Allowed sites" input (ParseHosts).

func (FieldInstanceDef) AllowedTextFormatIDs

func (f FieldInstanceDef) AllowedTextFormatIDs() []int

AllowedTextFormatIDs - FieldTypeText: TextFormatDef IDs the editor may pick per value. A non-empty list overrides Widget() for choosing the editor (see node/edit_dynamic.html's textFormatPicker). Empty - the field doesn't use text formats and Widget() decides as usual (WidgetSafeHTML and WidgetWYSIWYG sanitized with fixed policies). Per content type (WidgetConfig).

func (FieldInstanceDef) AllowedValueLabel

func (f FieldInstanceDef) AllowedValueLabel(value string) string

AllowedValueLabel returns the label for a stored value, or the value itself if it is no longer among AllowedValues() (option removed after being saved).

func (FieldInstanceDef) AllowedValues

func (f FieldInstanceDef) AllowedValues() []FieldAllowedValue

AllowedValues - FieldTypeList options in the order entered. Stored as a JSON array (not a map) so the order survives encoding.

func (FieldInstanceDef) AllowedValuesText

func (f FieldInstanceDef) AllowedValuesText() string

AllowedValuesText serializes AllowedValues() as "value|Label" lines to prefill the field edit form's textarea.

func (FieldInstanceDef) AllowsLibrary

func (f FieldInstanceDef) AllowsLibrary() bool

AllowsLibrary - the form picks a file from the media library (MediaSource).

func (FieldInstanceDef) AllowsUpload

func (f FieldInstanceDef) AllowsUpload() bool

AllowsUpload and AllowsLibrary - MediaSource: the form uploads, picks from the media library.

func (FieldInstanceDef) BlockTypes

func (f FieldInstanceDef) BlockTypes() []string

BlockTypes - FieldTypeBlocks: the field sets its items may be of (their machine names, storage config "block_types").

func (FieldInstanceDef) DateEnd

func (f FieldInstanceDef) DateEnd() DatePart

DateEnd - FieldTypeDate: whether its values have an end (storage config "date_end").

func (FieldInstanceDef) DateList

func (f FieldInstanceDef) DateList() bool

DateList - a date field with several dates: its value is a []DateValue.

func (FieldInstanceDef) DateRangeFull

func (f FieldInstanceDef) DateRangeFull() bool

DateRangeFull - FieldTypeDate: a range shows both dates whole, never shortened to the common month and year once (instance config "date_range_full").

func (FieldInstanceDef) DateRich

func (f FieldInstanceDef) DateRich() bool

DateRich - a date field whose values may have a time or an end: its value is a DateValue (several - a []DateValue, whatever the parts), a plain one's a time.Time.

func (FieldInstanceDef) DateTime

func (f FieldInstanceDef) DateTime() DatePart

DateTime - FieldTypeDate: whether its values have a time (storage config "date_time").

func (FieldInstanceDef) EmailPlain

func (f FieldInstanceDef) EmailPlain() bool

EmailPlain - FieldTypeEmail: the address is shown as is, not hidden from harvesters (storage config "email_plain").

func (FieldInstanceDef) FileDirectory

func (f FieldInstanceDef) FileDirectory() string

FileDirectory - Image/File field's upload directory pattern ("File directory"): storage-relative, may contain tokens such as [date:custom:Y]; resolved by files.ResolveFileDirectory. Empty - the default content directory. Field INSTANCE setting (WidgetConfig), like the other upload settings above.

func (FieldInstanceDef) FormGroupIDValue

func (f FieldInstanceDef) FormGroupIDValue() int

FormGroupIDValue - FormGroupID as a plain int (0 = no group), see ParentGroupIDValue.

func (FieldInstanceDef) HasExplicitMaxLen

func (f FieldInstanceDef) HasExplicitMaxLen() bool

HasExplicitMaxLen reports whether config sets max_len explicitly. The 255 default of MaxLen applies only to WidgetInput; long-form widgets get a length check only when max_len is set.

func (FieldInstanceDef) HasMaxUploadSize

func (f FieldInstanceDef) HasMaxUploadSize() bool

HasMaxUploadSize reports whether this field sets its own max upload size (otherwise the site-wide limit applies).

func (FieldInstanceDef) HostAllowed

func (f FieldInstanceDef) HostAllowed(host string) bool

HostAllowed reports whether a link to host may be saved in the field: any host when it names none, else one of them or a subdomain of one.

func (FieldInstanceDef) LinkTitle

func (f FieldInstanceDef) LinkTitle() LinkTitleMode

LinkTitle - FieldTypeLink: whether the links have titles (storage config "link_title"); an unknown value - none.

func (FieldInstanceDef) ListItems

func (f FieldInstanceDef) ListItems(v any) ListItems

ListItems - the chosen options of a FieldTypeList value v (one option's value, or several).

func (FieldInstanceDef) MaxLen

func (f FieldInstanceDef) MaxLen() int

MaxLen - FieldTypeText max length, 255 by default. For widgets other than WidgetInput it applies only if HasExplicitMaxLen().

func (FieldInstanceDef) MaxResolution

func (f FieldInstanceDef) MaxResolution() (width, height int)

MaxResolution and MinResolution - FieldTypeImage resolution limits. (0, 0) means unset: max falls back to the site-wide UploadSettings.MaxImageDimension (as a square bound), min - no minimum.

func (FieldInstanceDef) MaxResolutionString

func (f FieldInstanceDef) MaxResolutionString() string

MaxResolutionString and MinResolutionString - "WIDTHxHEIGHT" (the resolution input format), or "" when unset.

func (FieldInstanceDef) MaxUploadSizeBytes

func (f FieldInstanceDef) MaxUploadSizeBytes() int

MaxUploadSizeBytes - FieldTypeImage/FieldTypeFile max upload size; meaningful only if HasMaxUploadSize().

func (FieldInstanceDef) MaxUploadSizeMB

func (f FieldInstanceDef) MaxUploadSizeMB() float64

MaxUploadSizeMB - MaxUploadSizeBytes() in MB for the admin form; 0 when unset.

func (FieldInstanceDef) MaxValues

func (f FieldInstanceDef) MaxValues() int

MaxValues - how many images or links a FieldTypeImage/FieldTypeLink field with several values holds at most (widget config "max_values"); 0 - no limit.

func (FieldInstanceDef) MediaSource

func (f FieldInstanceDef) MediaSource() MediaSource

MediaSource - FieldTypeFile, FieldTypeImage: whether the form uploads a file, picks one from the media library, or both (the default). Field INSTANCE setting (WidgetConfig "media_source").

func (FieldInstanceDef) MinResolution

func (f FieldInstanceDef) MinResolution() (width, height int)

MinResolution - the FieldTypeImage minimum resolution; (0, 0) - none.

func (FieldInstanceDef) MinResolutionString

func (f FieldInstanceDef) MinResolutionString() string

MinResolutionString - MinResolution as "WIDTHxHEIGHT", or "" when unset.

func (FieldInstanceDef) Multiple

func (f FieldInstanceDef) Multiple() bool

Multiple - for the types that allow it (AllowsMultiple): several values per (node, field), stored in the *_multi value table (a link field's in its one table). Set at creation (ContentTypeService.CreateField); changed only by ContentTypeService.SetFieldMultiple, which moves the values between the tables.

func (FieldInstanceDef) NumberDecimals

func (f FieldInstanceDef) NumberDecimals() int

NumberDecimals - FieldTypeNumber with NumberDecimal: the decimals kept and shown (storage config "decimals", 0-6; unset - 2); 0 for the others.

func (FieldInstanceDef) NumberKind

func (f FieldInstanceDef) NumberKind() NumberKind

NumberKind - FieldTypeNumber: storage config "number_kind"; unknown - any.

func (FieldInstanceDef) NumberMax

func (f FieldInstanceDef) NumberMax() (float64, bool)

NumberMax - see NumberMin.

func (FieldInstanceDef) NumberMaxAttr

func (f FieldInstanceDef) NumberMaxAttr() string

NumberMaxAttr - see NumberMinAttr.

func (FieldInstanceDef) NumberMin

func (f FieldInstanceDef) NumberMin() (float64, bool)

NumberMin and NumberMax - FieldTypeNumber: the least and the greatest value allowed (storage config "min", "max"); false - no limit.

func (FieldInstanceDef) NumberMinAttr

func (f FieldInstanceDef) NumberMinAttr() string

NumberMinAttr and NumberMaxAttr - NumberMin, NumberMax for the number input's min and max ("" - none).

func (FieldInstanceDef) NumberPrefix

func (f FieldInstanceDef) NumberPrefix() string

NumberPrefix and NumberSuffix - FieldTypeNumber: what is shown before and after the value ("$", " ₽", " min"; storage config "prefix", "suffix").

func (FieldInstanceDef) NumberStep

func (f FieldInstanceDef) NumberStep() string

NumberStep - the step of the number input: 1 for whole numbers, one unit of the last decimal for decimals, "any" otherwise.

func (FieldInstanceDef) NumberSuffix

func (f FieldInstanceDef) NumberSuffix() string

NumberSuffix - see NumberPrefix.

func (FieldInstanceDef) ParentGroupIDValue

func (f FieldInstanceDef) ParentGroupIDValue() int

ParentGroupIDValue - ParentGroupID as a plain int (0 = no group), for templates: html/template can't dereference a *int in comparisons.

func (FieldInstanceDef) Pattern

func (f FieldInstanceDef) Pattern() string

Pattern - FieldTypeText: optional RE2 regexp a non-empty value must match (e.g. a URL or code format); "" - no format check.

func (FieldInstanceDef) PatternMessage

func (f FieldInstanceDef) PatternMessage() string

PatternMessage - error message when Pattern() doesn't match; "" - a generic default is used.

func (FieldInstanceDef) PrivateFiles

func (f FieldInstanceDef) PrivateFiles() bool

PrivateFiles - FieldTypeFile, FieldTypeImage: new uploads go to the private files (entity.PrivateScheme), served - an image's style derivatives too - only to those who may see a content item they are attached to ("Private files"). Field INSTANCE setting (WidgetConfig); files already uploaded keep where they are.

func (FieldInstanceDef) RichText

func (f FieldInstanceDef) RichText() bool

RichText - a FieldTypeText field whose values are HTML: it uses text formats (sanitized per format on save) or the legacy WidgetSafeHTML / WidgetWYSIWYG widget. Templates output only such values unescaped; other text values are plain text and are escaped.

func (FieldInstanceDef) RoundNumber

func (f FieldInstanceDef) RoundNumber(v float64) float64

RoundNumber - v as the field keeps it: whole, or with its decimals; as is for any number.

func (FieldInstanceDef) Symmetric

func (f FieldInstanceDef) Symmetric() bool

Symmetric - for a Multiple() FieldTypeReference: the relation is mutual (A references B ⇔ B references A through the same field). On save, back-references on added/removed targets are synced (the database's syncSymmetricReferences), so the relation can be edited from either side.

func (FieldInstanceDef) TargetContentType

func (f FieldInstanceDef) TargetContentType() string

TargetContentType - FieldTypeReference: optional comma-separated machine names of allowed target types; "" - no filter.

func (FieldInstanceDef) TimeFormat

func (f FieldInstanceDef) TimeFormat() string

TimeFormat - FieldTypeDate: the date format machine name its times are shown in (instance config "time_format"); "" - hours and minutes.

func (FieldInstanceDef) UserRoles

func (f FieldInstanceDef) UserRoles() []int

UserRoles - FieldTypeUser: the roles (IDs) whose users may be chosen (storage config "user_roles"); none - any active user.

func (FieldInstanceDef) VocabularyID

func (f FieldInstanceDef) VocabularyID() int

VocabularyID - FieldTypeTaxonomy: the vocabulary terms are chosen from. Required for this field type.

func (FieldInstanceDef) Widget

func (f FieldInstanceDef) Widget() FieldWidget

Widget returns the configured widget from WidgetConfig (per content type, unlike Config), or WidgetInput when unset. Valid values depend on the field type - see the FieldWidget constants. Changing it doesn't affect stored values.

type FieldInstanceDefs

type FieldInstanceDefs []FieldInstanceDef

FieldInstanceDefs - a list of fields of a content type.

func LocalizeFieldLabels

func LocalizeFieldLabels(lang string, fields FieldInstanceDefs) FieldInstanceDefs

LocalizeFieldLabels - fields with their labels in lang (a copy).

func (FieldInstanceDefs) SortByDisplayOrder

func (fs FieldInstanceDefs) SortByDisplayOrder() FieldInstanceDefs

SortByDisplayOrder returns a copy sorted by DisplayOrder, then ID.

func (FieldInstanceDefs) SortBySortOrder

func (fs FieldInstanceDefs) SortBySortOrder() FieldInstanceDefs

SortBySortOrder returns a copy sorted by SortOrder, then ID (stable).

type FieldLayout

type FieldLayout string

FieldLayout - how a field with several values shows them, whatever shows each (the field's formatter, FieldFormatter).

const (
	// FieldLayoutAll - all of them, one after another.
	FieldLayoutAll FieldLayout = ""
	// FieldLayoutFirst - only the first.
	FieldLayoutFirst FieldLayout = "first"
	// FieldLayoutFeatured - the first one large, the others small after
	// it (a formatter without a small form shows them as it shows the
	// first).
	FieldLayoutFeatured FieldLayout = "featured"
)
const (
	FieldLayoutUpcoming FieldLayout = "upcoming"
	FieldLayoutNearest  FieldLayout = "nearest"
)

The layouts of a date field's several dates (the others' too where they fit): only those not ended yet (all ended - the last), or the nearest of them and how many more.

const FieldLayoutGrid FieldLayout = "grid"

FieldLayoutGrid - a blocks field's items as cards in a grid (the others' - one after another).

func ParseFieldLayout

func ParseFieldLayout(s string) FieldLayout

ParseFieldLayout - s as a FieldLayout; unknown - FieldLayoutAll.

type FieldStorageDef

type FieldStorageDef struct {
	ID          int
	MachineName string
	FieldType   ContentTypeFieldType
	Config      map[string]any
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

FieldStorageDef - a reusable field definition (machine name, type, config) shared by every FieldInstanceDef that attaches it to a content type. field_value_* rows reference this ID, so a shared field's values live in one place across content types.

func (FieldStorageDef) BlockTypes

func (f FieldStorageDef) BlockTypes() []string

BlockTypes - the storage's BlockTypes (FieldInstanceDef.BlockTypes).

func (FieldStorageDef) HasExplicitMaxLen

func (f FieldStorageDef) HasExplicitMaxLen() bool

HasExplicitMaxLen reports whether config sets max_len. Textarea/WYSIWYG fields get a length check only when it is set explicitly.

func (FieldStorageDef) MaxLen

func (f FieldStorageDef) MaxLen() int

MaxLen - for FieldTypeText; defaults to 255 (the WidgetInput limit). For other widgets it applies only when HasExplicitMaxLen is true.

func (FieldStorageDef) Multiple

func (f FieldStorageDef) Multiple() bool

Multiple - the "multiple" config flag, same as FieldInstanceDef.Multiple, for callers that only have the storage definition.

func (FieldStorageDef) TargetContentType

func (f FieldStorageDef) TargetContentType() string

TargetContentType - for FieldTypeReference: optional target type machine name filter; empty means no filter.

func (FieldStorageDef) VocabularyID

func (f FieldStorageDef) VocabularyID() int

VocabularyID - for FieldTypeTaxonomy: the vocabulary the select is built from (required). Shared by every content type using the field.

type FieldStorageDefs

type FieldStorageDefs []FieldStorageDef

FieldStorageDefs - a list of field storages.

type FieldStorageUsage

type FieldStorageUsage struct {
	Instances int
	// Views - fields, filters and sorts of Views plus displays that use it
	// for carousel links or a glossary.
	Views           int
	BreadcrumbRules int
	SEORules        int
}

FieldStorageUsage - what still holds a field storage: its instances and the configuration that references it. The storage leaves the catalog only when nothing holds it.

func (FieldStorageUsage) References

func (u FieldStorageUsage) References() int

References - references other than instances.

func (FieldStorageUsage) Removable

func (u FieldStorageUsage) Removable() bool

Removable - nothing holds the storage.

type FieldUploadPolicy

type FieldUploadPolicy struct {
	// AllowedExtensions - lowercase, no leading dot ("jpg", "pdf"). nil for
	// an Image field means "use the sitewide MIME allow-list"; File fields
	// always resolve to a non-nil list.
	AllowedExtensions []string
	MaxFileSizeBytes  int
	// MaxWidth/MaxHeight - 0,0 means the sitewide MaxImageDimension as a
	// square cap. Unused for File fields.
	MaxWidth, MaxHeight int
	// MinWidth/MinHeight - 0,0 means no minimum. Unused for File fields.
	MinWidth, MinHeight int
}

FieldUploadPolicy is the effective upload-validation policy for one image/file field. A field's own settings are NOT clamped to the sitewide UploadSettings: a value set on the field wins even if wider; sitewide values only fill axes the field leaves unset (see ResolveFieldUploadPolicy).

func ResolveAvatarUploadPolicy

func ResolveAvatarUploadPolicy(account AccountSettings, sitewide UploadSettings) FieldUploadPolicy

ResolveAvatarUploadPolicy builds the upload policy for user avatars. With no AvatarAllowedExtensions, AllowedExtensions stays nil and the caller uses the sitewide MIME check; an explicit list replaces that check. MaxFileSizeBytes falls back to sitewide. The resize target is the MaxAvatarDimension constant, not part of this policy.

func ResolveFieldUploadPolicy

func ResolveFieldUploadPolicy(field FieldInstanceDef, sitewide UploadSettings) FieldUploadPolicy

ResolveFieldUploadPolicy builds the effective policy for one field, axis by axis: the field's own setting, else the sitewide default. File fields fall back to defaultFileExtensions and get no resolution limits.

func ResolveTextFormatUploadPolicy

func ResolveTextFormatUploadPolicy(format TextFormatDef, sitewide UploadSettings) FieldUploadPolicy

ResolveTextFormatUploadPolicy builds the upload policy for editor (TinyMCE file manager) image uploads of a text format: nil extensions fall through to the sitewide MIME check, an explicit list replaces it; MaxFileSizeBytes falls back to sitewide; an image larger than the sitewide MaxImageDimension is scaled down.

type FieldWidget

type FieldWidget string

FieldWidget - how a field is edited/displayed, independent of its storage type. Read via FieldInstanceDef.Widget().

const (
	// WidgetInput - single-line plain text, escaped on render. The
	// default when unset.
	WidgetInput FieldWidget = "input"
	// WidgetTextarea - multi-line plain text, escaped on render.
	WidgetTextarea FieldWidget = "textarea"
	// WidgetSafeHTML - textarea with HTML sanitized by pkg/htmlsanitize on
	// save and rendered unescaped.
	WidgetSafeHTML FieldWidget = "safe_html"
	// WidgetWYSIWYG - TinyMCE-backed textarea, its HTML sanitized on save
	// (htmlsanitize.SanitizeEditor) and rendered unescaped.
	WidgetWYSIWYG FieldWidget = "wysiwyg"
)

Widgets for FieldTypeText.

const (
	// WidgetSelect - <select>, or <select multiple> when Multiple().
	// Taxonomy terms are indented by hierarchy.
	WidgetSelect FieldWidget = "select"
	// WidgetRadio - radio-button group; valid only when !Multiple().
	WidgetRadio FieldWidget = "radio"
	// WidgetCheckboxes - checkbox group; valid only when Multiple().
	WidgetCheckboxes FieldWidget = "checkboxes"
)

Widgets for FieldTypeList (options from AllowedValues) and FieldTypeTaxonomy (options from the vocabulary's terms). They share the Config "widget" key with the text widgets but have their own allow-list (see admin/content_type_field_form.go's listWidgets/taxonomyWidgets).

const (
	// WidgetAutocomplete - Tagify free-tagging widget (comma-separated term
	// IDs and/or "new:<name>" tokens, see resolveTags);
	// valid only when Multiple(). The only widget that can create terms
	// on the fly; the default for multi-value taxonomy fields.
	WidgetAutocomplete FieldWidget = "autocomplete"
)

Taxonomy-only widget. Cardinality is validated on field update (ContentTypeFieldUpdate).

type File

type File struct {
	ID        int
	URI       string
	MimeType  string
	Width     int
	Height    int
	SizeBytes int
	Alt       string
	// OriginalFilename - the client-supplied file name. Set only for File
	// field uploads and used as the download-link text; other uploads leave
	// it empty (they store a generated name).
	OriginalFilename string
	// Focal - the image's focal point (nil - none): a style cropping at it
	// (ImageStyleAnchorFocal) keeps it in the picture.
	Focal     *FocalPoint
	CreatedBy *User
	CreatedAt time.Time
	UpdatedAt time.Time
}

File - an uploaded file (a files row): its URI (PublicScheme, PrivateScheme), type, size, an image's dimensions, alt text and focal point.

type FileRepository

type FileRepository interface {
	Create(ctx context.Context, uri, mimeType string, width, height, sizeBytes int, createdBy int) (*File, error)
	// ByID returns a file by id; ErrEntityNotFound if missing.
	ByID(ctx context.Context, id int) (*File, error)
	// ByIDs batch-loads files keyed by id; missing ids are absent from the
	// result rather than an error.
	ByIDs(ctx context.Context, ids []int) (map[int]File, error)
	// UpdateAlt sets a file's alt text. Alt is stored per file, not per
	// usage - fine while every upload creates its own file row.
	UpdateAlt(ctx context.Context, id int, alt string) error
	// SetFocal sets a file's focal point (nil - none).
	SetFocal(ctx context.Context, id int, focal *FocalPoint) error
	// SetOriginalFilename sets OriginalFilename right after Create (File
	// field uploads only); kept separate so Create's signature stays shared.
	SetOriginalFilename(ctx context.Context, id int, name string) error
	// ByURI returns the file stored under uri; ErrEntityNotFound if none.
	ByURI(ctx context.Context, uri string) (*File, error)
}

FileRepository defines the interface for file operations

type FocalPoint

type FocalPoint struct {
	X, Y int
}

FocalPoint - a point of an image, in percent of its width (X) and height (Y) from the top left, 0-100.

func (FocalPoint) Valid

func (p FocalPoint) Valid() bool

Valid - whether both are 0-100.

type GlossaryData

type GlossaryData []GlossaryItem

GlossaryData - a View's glossary bar: its letters with their counts.

type GlossaryItem

type GlossaryItem struct {
	Letter string `json:"letter"`
	Count  int    `json:"count"`
}

GlossaryItem - one letter of a View's glossary bar and how many results start with it.

type ImageStyleDef

type ImageStyleDef struct {
	ID          int
	Name        string
	Label       string
	Description string
	Width       int
	Height      int // 0 = keep aspect ratio
	Mode        string
	Anchor      string
	Quality     int
	// Format - encoding of the derivatives: "webp" (default) or "jpeg"
	// (pkg/imagestyle.Format), for consumers that don't take WebP.
	Format string
	// HiDPI - its derivatives are made at double size too, for
	// high-density screens (srcset 2x, imagestyle.ImageStyle.HiDPI).
	HiDPI     bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

ImageStyleDef - an admin-editable image resize preset. The domain-layer counterpart of pkg/imagestyle.ImageStyle, used for admin CRUD; the resize pipeline (pkg/imagestyle.StyleService) resolves styles by Name through internal/infrastructure/image_style_adapter.go, which wraps ImageStyleRepository.

type ImageStyleDefs

type ImageStyleDefs []ImageStyleDef

ImageStyleDefs - a list of image styles.

type ImageStyleRepository

type ImageStyleRepository interface {
	ImageStyles(ctx context.Context) (ImageStyleDefs, error)
	ImageStyleByID(ctx context.Context, id int) (*ImageStyleDef, error)
	ImageStyleByName(ctx context.Context, name string) (*ImageStyleDef, error)
	CreateImageStyle(ctx context.Context, s ImageStyleDef) (*ImageStyleDef, error)
	UpdateImageStyle(ctx context.Context, s ImageStyleDef) (*ImageStyleDef, error)
	DeleteImageStyle(ctx context.Context, id int) error
}

ImageStyleRepository - CRUD for image styles.

type IntegrationSettings

type IntegrationSettings struct {
	// VerificationTags - one "name=content" per line, each a
	// <meta name="…" content="…"> in <head> (yandex-verification,
	// google-site-verification, msvalidate.01…).
	VerificationTags string
	// MetrikaID - the Yandex Metrika counter number ("" - none) and its
	// options.
	MetrikaID             string
	MetrikaClickmap       bool
	MetrikaTrackLinks     bool
	MetrikaAccurateBounce bool
	MetrikaWebvisor       bool
	// GAID - the Google Analytics measurement ID, "G-…" ("" - none).
	GAID string
	// HeadCode / BodyEndCode - raw HTML/JS put as is at the end of <head>
	// and right before </body>; editable by full-access roles only.
	HeadCode    string
	BodyEndCode string
	// BodyEndSkipServicePages - leave BodyEndCode off service pages
	// (admin pages, 404), e.g. for fullscreen ads.
	BodyEndSkipServicePages bool
	// Consent - the visitors' consent to the codes: the banner and each
	// code's group.
	Consent Consent
}

IntegrationSettings - external services wired into every page (/admin/config/integrations): site verification meta tags, Yandex Metrika, Google Analytics, and raw code for the rest (ad loaders etc.), on one page. One row.

func (IntegrationSettings) AskedGroups

func (s IntegrationSettings) AskedGroups() []ConsentGroup

AskedGroups - the groups the banner offers: those of the site's codes (on, in s) that wait for consent, in ConsentGroups' order.

func (IntegrationSettings) MetrikaCounter

func (s IntegrationSettings) MetrikaCounter() int

MetrikaCounter - MetrikaID as a number (0 - none or not a number).

func (IntegrationSettings) VerificationMetas

func (s IntegrationSettings) VerificationMetas() []MetaTag

VerificationMetas - VerificationTags parsed ("name=content" lines; blank and malformed lines skipped).

type IntegrationSettingsRepository

type IntegrationSettingsRepository interface {
	Get(ctx context.Context) (*IntegrationSettings, error)
	Update(ctx context.Context, s IntegrationSettings) error
}

IntegrationSettingsRepository stores the integration settings row.

type InterfacePack

type InterfacePack struct {
	Lang, Version, SHA256 string
	Strings               int
	Draft                 bool
	InstalledAt           time.Time
}

InterfacePack - a language's interface translation downloaded from the translations catalog: its language, the catalog's version and the file's checksum, how many of its strings were kept, whether the catalog marks it a draft (machine translated), when it was installed.

type InterfacePackRepository

type InterfacePackRepository interface {
	// Packs - the installed ones, by language.
	Packs(ctx context.Context) ([]InterfacePack, error)
	// Strings - the strings of every installed one.
	Strings(ctx context.Context) ([]InterfaceString, error)
	// Install writes a language's pack and its strings in place of what
	// the language had.
	Install(ctx context.Context, p InterfacePack, strings []InterfaceString) error
	// Delete removes a language's pack and its strings.
	Delete(ctx context.Context, lang string) error
}

InterfacePackRepository - the downloaded interface translations.

type InterfaceString

type InterfaceString struct {
	Lang, Context, Source string
	Text                  string
	Forms                 []string
	UpdatedAt             time.Time
}

InterfaceString - an interface string's translation the site keeps itself, over the catalogs (pkg/i18n.Entry): changed in the admin. Lang - its language (the source language too: the site rewords English), Context and Source - the string (a plural string's singular), Text or the plural Forms.

type InterfaceStringRepository

type InterfaceStringRepository interface {
	// All - every one, of every language.
	All(ctx context.Context) ([]InterfaceString, error)
	// Save writes one (or rewrites it).
	Save(ctx context.Context, s InterfaceString) error
	// Delete removes one: the catalogs' translation is back.
	Delete(ctx context.Context, lang, msgctx, source string) error
}

InterfaceStringRepository - the site's own interface translations.

type Link struct {
	URL   string `json:"url"`
	Title string `json:"title,omitempty"`
}

Link - one value of a FieldTypeLink field: an absolute http(s) address and the text it shows with (Title; "" - the address itself).

func Links(v any) []Link

Links - a link field's value: its links in the editor's order (a field with one value holds at most one); none for anything else.

func (Link) Host

func (l Link) Host() string

Host - the link's host in lower case, without "www."; "" - not an absolute http(s) address.

func (Link) Text

func (l Link) Text() string

Text - what the link shows: its title, else its address.

type LinkTitleMode

type LinkTitleMode string

LinkTitleMode - whether a link field asks for the links' titles.

const (
	// LinkTitleNone - no title: the link shows its address (or what a
	// formatter makes of it, a video, say).
	LinkTitleNone LinkTitleMode = ""
	// LinkTitleOptional - a title may be given.
	LinkTitleOptional LinkTitleMode = "optional"
	// LinkTitleRequired - every link needs one.
	LinkTitleRequired LinkTitleMode = "required"
)

type ListItem

type ListItem struct {
	Value string
	Label string
	Index int
}

ListItem - an option chosen in a FieldTypeList field: its value, its label and its place among the field's options (1 - the first; 0 - an option removed since), so a theme can style the options in their order.

type ListItems

type ListItems []ListItem

ListItems - the options chosen in a list field; printed, their labels joined with ", ".

func (ListItems) String

func (l ListItems) String() string

type MailDef

type MailDef struct {
	// Key - the email's id: "account.password_reset", "<module>.<name>".
	Key string
	// Module - the module sending it ("" - the core): listed while the
	// module is on.
	Module string
	// Label, Description (when it is sent) and Recipient (who gets it) -
	// translation sources (i18n.N).
	Label       string
	Description string
	Recipient   string
	// Optional - it can be switched off on the Mail page; the others are
	// always sent.
	Optional bool
	// Placeholders - those its text may use (MailSitePlaceholders, the
	// user's, its own).
	Placeholders []string
	// Sample - values of its own placeholders for the page's preview and
	// a test email ("[pm:sender]" → "anna").
	Sample map[string]string
	// Default - its built-in text, translation sources (i18n.N): kept by
	// the mail_templates table when changed. An email keeping its text
	// elsewhere gives Load and Save instead.
	Default MailTemplate
	// Load - its template, a blank subject or body the default's; Save
	// stores one (blank - back to the default). Both nil - Default and
	// the mail_templates table.
	Load func(ctx context.Context) (MailTemplate, error)
	Save func(ctx context.Context, t MailTemplate) error
	// Weight orders it among its group's emails.
	Weight int
}

MailDef - one of the emails the site sends, on the Mail page's "Emails" tab: the core's (the accounts') and the modules' (modulekit.AddMail). It is sent by its Key (MailService.Send): its template with the placeholders filled in, unless it is switched off.

type MailLogEntry

type MailLogEntry struct {
	ID      int
	SentAt  time.Time
	Key     string
	To      string
	Subject string
	Status  string
	Error   string
}

MailLogEntry - an email the site sent or tried to (the Mail page's log): when, which of the site's emails (Key; "" - a message of no template, such as a form's notice), to whom, its subject, what came of it. Never its text.

type MailLogFilter

type MailLogFilter struct {
	To     string
	Key    string
	Status string
	Limit  int
	Offset int
}

MailLogFilter - the log's entries asked for: To - a part of the address, Key and Status - exactly ("" - any), newest first.

type MailLogRepository

type MailLogRepository interface {
	Add(ctx context.Context, e MailLogEntry) error
	// List - the entries f asks for, a page of them, and how many there are.
	List(ctx context.Context, f MailLogFilter) ([]MailLogEntry, int, error)
	// LastSent - when each email (by key) was last sent.
	LastSent(ctx context.Context) (map[string]time.Time, error)
	// DeleteBefore removes the entries older than t.
	DeleteBefore(ctx context.Context, t time.Time) error
}

MailLogRepository keeps the mail log.

type MailSettings

type MailSettings struct {
	// Enabled - the master switch: off means no email is sent.
	Enabled      bool
	Transport    string
	FromAddress  string
	SMTPHost     string
	SMTPPort     int
	SMTPUser     string
	SMTPPassword string
	// TransportSettings - the settings of the modules' ways of sending:
	// by transport, by setting.
	TransportSettings map[string]map[string]string
	// LogKeepDays - how many days the mail log keeps an email (0 - no
	// log).
	LogKeepDays int
}

MailSettings - how the site sends email (one row). An empty Transport means nothing is saved and the server config's settings apply.

func (MailSettings) TransportSetting

func (s MailSettings) TransportSetting(transport, name string) string

TransportSetting - the setting name of the transport ("" - unset).

type MailSettingsRepository

type MailSettingsRepository interface {
	Get(ctx context.Context) (*MailSettings, error)
	Update(ctx context.Context, s *MailSettings) error
}

MailSettingsRepository stores the mail settings row.

type MailTemplate

type MailTemplate struct {
	Subject string
	Body    string
}

MailTemplate - an email's subject and body with placeholders ([site:name], [user:name], an email's own).

type MailTemplateRepository

type MailTemplateRepository interface {
	// All - the emails changed, by key.
	All(ctx context.Context) (map[string]StoredMail, error)
	// SaveText stores an email's text (blank - the default's).
	SaveText(ctx context.Context, key string, t MailTemplate) error
	// SetEnabled switches an email on or off.
	SetEnabled(ctx context.Context, key string, on bool) error
}

MailTemplateRepository keeps what the Mail page changed of the emails.

type MaintenanceRepository

type MaintenanceRepository interface {
	Get(ctx context.Context) (*MaintenanceSettings, error)
	Update(ctx context.Context, s *MaintenanceSettings) error
}

MaintenanceRepository defines the interface for maintenance settings data access

type MaintenanceSettings

type MaintenanceSettings struct {
	Enabled bool
	Message string
}

MaintenanceSettings represents maintenance mode configuration

type MediaFilter

type MediaFilter struct {
	Search     string
	Kind       MediaKind
	CreatedBy  int
	Unused     bool
	Scheme     string
	Extensions []string
	MinWidth   int
	MinHeight  int
	MaxBytes   int
	IDs        []int
	Offset     int
	Limit      int
}

MediaFilter - the media library's search: text in the file's path, name or alt text; its kind; who uploaded it (0 - anyone); only the files nothing uses; the page. A field's picker narrows it further: the store (Scheme, public:// or private://; "" - any), the extensions (none - any), the least width and height, the largest size (0 - any), the files themselves (IDs; none - any).

type MediaKind

type MediaKind string

MediaKind - which of the files the media library lists: all, the images, the others.

const (
	MediaAll       MediaKind = ""
	MediaImages    MediaKind = "images"
	MediaDocuments MediaKind = "documents"
)

The media library's kinds (MediaKind).

type MediaRepository

type MediaRepository interface {
	// MediaFiles - the files the filter finds, the newest first, and
	// how many it finds in all.
	MediaFiles(ctx context.Context, f MediaFilter) ([]File, int, error)
	// MediaUseCounts - in how many places each of the files is used.
	MediaUseCounts(ctx context.Context, fileIDs []int) (map[int]int, error)
	// MediaUses - the places the file is used.
	MediaUses(ctx context.Context, fileID int) ([]MediaUse, error)
	// MediaUploaders - the users who uploaded files, by name.
	MediaUploaders(ctx context.Context) ([]User, error)
	MediaTotals(ctx context.Context) (MediaTotals, error)
}

MediaRepository - the media library's queries over the files.

type MediaSource

type MediaSource string

MediaSource - where an Image/File field's files come from (FieldInstanceDef.MediaSource): uploads, the media library, or both.

const (
	MediaSourceBoth    MediaSource = ""
	MediaSourceUpload  MediaSource = "upload"
	MediaSourceLibrary MediaSource = "library"
)

The media sources: both (the default), uploads only, the library only.

type MediaTotals

type MediaTotals struct {
	Count int
	Bytes int
}

MediaTotals - how many files there are and their size.

type MediaUse

type MediaUse struct {
	NodeID    int
	Title     string
	Type      string
	Slug      string
	InTrash   bool
	Field     string
	TypeLabel string
	Module    string
}

MediaUse - one place a file is used: a content item's field (NodeID, its Title, Type and Slug, InTrash; Field - the field's label), a content type's default image (Field, TypeLabel), or a module's table (Module - its name; NodeID when the module attaches it to a node).

func (MediaUse) URL

func (u MediaUse) URL() string

URL - the content item's address (Node.URL).

type MenuDef struct {
	ID          int
	MachineName string
	Label       string
	Description string
	// InSitemap - the menu's links go into the sitemap.
	InSitemap bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

MenuDef - a named menu container (e.g. main menu, footer), each with its own tree of MenuLinkDef. Any menu can be placed as a block in any region (BlockPlacementMenu).

type MenuDefs []MenuDef

MenuDefs - a list of menus.

type MenuLinkDef struct {
	ID       int
	MenuID   int
	ParentID *int
	Title    string
	LinkType MenuLinkType
	// LinkURL - used only for MenuLinkURL: an internal path (starting with "/")
	// or a full external URL, used as is.
	LinkURL string
	// LinkNodeID/LinkTermID/LinkViewID - the target ID for the matching LinkType.
	// The URL is resolved from the target's current state on each request
	// (service.DefaultMenuService.ResolveMenuLinkURL), so renaming the target
	// doesn't break the link; a deleted target resolves to ok=false, not an error.
	LinkNodeID *int
	LinkTermID *int
	LinkViewID *int
	// Weight - order among siblings, set by drag-and-drop.
	Weight int
	// Enabled - false hides the item and its subtree from public rendering
	// without deleting it.
	Enabled   bool
	CreatedAt time.Time
	UpdatedAt time.Time
}

MenuLinkDef - a menu item. ParentID forms a tree of arbitrary depth; nil means a top-level item.

func (l MenuLinkDef) LinkNodeIDValue() int

LinkNodeIDValue (and LinkTermIDValue, LinkViewIDValue) return the matching *int dereferenced (0 = unset), since templates can't compare an int with a *int (used by admin/menus/link_target_fields.html).

func (l MenuLinkDef) LinkTermIDValue() int

LinkTermIDValue - LinkTermID or 0 (see LinkNodeIDValue).

func (l MenuLinkDef) LinkViewIDValue() int

LinkViewIDValue - LinkViewID or 0 (see LinkNodeIDValue).

type MenuLinkDefs []MenuLinkDef

MenuLinkDefs - a list of menu links.

type MenuLinkOrderUpdate struct {
	ID       int
	ParentID *int
	Weight   int
}

MenuLinkOrderUpdate - one row of a bulk reorder (see MenuRepository.ReorderMenuLinks).

type MenuLinkType string

MenuLinkType - which of LinkURL/LinkNodeID/LinkTermID/LinkViewID the link uses.

const (
	MenuLinkURL  MenuLinkType = "url"
	MenuLinkNode MenuLinkType = "node"
	MenuLinkTerm MenuLinkType = "term"
	MenuLinkView MenuLinkType = "view"
)

The menu links' targets (MenuLinkType): a URL, a node, a term, a View.

type MenuRepository interface {
	Menus(ctx context.Context) (MenuDefs, error)
	MenuByID(ctx context.Context, id int) (*MenuDef, error)
	MenuByMachineName(ctx context.Context, machineName string) (*MenuDef, error)
	CreateMenu(ctx context.Context, m MenuDef) (*MenuDef, error)
	UpdateMenu(ctx context.Context, m MenuDef) (*MenuDef, error)
	// DeleteMenu deletes a menu with all its links (cascaded in application
	// code, not by FK).
	DeleteMenu(ctx context.Context, id int) error

	MenuLinksByMenuID(ctx context.Context, menuID int) (MenuLinkDefs, error)
	MenuLinkByID(ctx context.Context, id int) (*MenuLinkDef, error)
	CreateMenuLink(ctx context.Context, l MenuLinkDef) (*MenuLinkDef, error)
	UpdateMenuLink(ctx context.Context, l MenuLinkDef) (*MenuLinkDef, error)
	// DeleteMenuLink moves the deleted item's children up to its own level;
	// the subtree is not deleted.
	DeleteMenuLink(ctx context.Context, id int) error
	// ReorderMenuLinks bulk-updates Weight/ParentID after drag-and-drop; all
	// updates in one call belong to the same menu.
	ReorderMenuLinks(ctx context.Context, updates []MenuLinkOrderUpdate) error
}

MenuRepository - storage port for menus and their links.

type MetaTag

type MetaTag struct {
	Name    string
	Content string
}

MetaTag - a <meta name content> pair.

type Module

type Module struct {
	Name        string
	Label       string
	Description string
	// Category - its group on the Modules page, one of ModuleCategories
	// ("" or another - ModuleCategoryOther).
	Category string
	// External - the module comes from its own repository (registered
	// with modulekit.Register), not with the engine; set at registration.
	External bool
	// Requires - modules this one needs: it can't be enabled while one of
	// them is off, and they can't be switched off while it is on.
	Requires []string
	// NodeTypes - content types the module provides (no content_types
	// row of their own); they don't open, get created or edited, or show
	// in the sitemap and search while it is off.
	NodeTypes []ModuleNodeType
	// PluginBlocks - plugin blocks it provides (PluginBlocks()).
	PluginBlocks []ModulePluginBlock
	// Permissions - permissions it adds to the matrix.
	Permissions []ModulePermission
	// AdminMenu - its pages in the admin toolbar (AdminMenu()).
	AdminMenu []ModuleMenuItem
	// CaptchaForms - its forms that can show the CAPTCHA
	// (CaptchaFormNames()).
	CaptchaForms []ModuleCaptchaForm
	// FileSources - its texts that can link to users' files (the files
	// manager's "used in").
	FileSources []ModuleFileSource
	// NodeFiles - its tables of files attached to nodes (e.g. gallery
	// images): deleting a node deletes those files nothing else uses.
	NodeFiles []ModuleNodeFiles
	// MaintenancePaths - path prefixes of its pages that stay open while
	// the site is in maintenance mode (e.g. a fragment the public page
	// shell loads).
	MaintenancePaths []string
	// Paths - the addresses of its own pages ("/quotes": that path and the
	// ones under it): uninstalling removes the menu links to them.
	Paths []string
	// RobotsDisallow - paths of its pages crawlers should skip (forms,
	// actions), added to robots.txt while it is enabled (service.RobotsTxt);
	// "*" matches any part of a path.
	RobotsDisallow []string
	// LabelColumns - its tables' columns of labels its install step writes
	// in English (marked with i18n.N): app install puts them in the site's
	// language.
	LabelColumns []ModuleLabelColumn
	// Tables - every table the module owns: its schema migrations are its
	// own set (created when the module is installed); every other table is
	// the core's. A module's table may reference core tables, never the
	// other way round.
	Tables []string
	// Data - those of Tables the Modules page counts (a disabled module
	// keeps them).
	Data []ModuleData
	// OffByDefault - the module is off until enabled on the Modules page
	// (no state row - off): a module added to the engine after sites were
	// set up doesn't switch itself on there; enabling it installs it.
	OffByDefault bool
	// InstallByDefault - a new site has the module: app install installs
	// and enables it unless its -modules says otherwise. The others a new
	// site gets
	// not installed and off; enabling one on the Modules page installs it.
	InstallByDefault bool
	// CoreData - what the module keeps in core tables besides what the
	// fields above describe (a core column, a vocabulary), as the uninstall
	// page names it. A module with CoreData is uninstalled only with its
	// own uninstall step that removes them; everything else - its
	// NodeTypes' content and settings, files only its tables use -
	// an uninstall derives from this struct and the schema.
	CoreData []string
	// CSS/JS - the module's own assets, internal/modules/<Name>/static/
	// <file>.css and .js (served minified at /static/modules/<Name>/). A
	// page includes them while the module is enabled and only if it shows
	// something of the module: the module's templates call
	// {{attach "<Name>"}}, its plugin blocks attach it themselves (see
	// service.resolveModuleAssets). A theme styles the module's blocks in
	// its own CSS, loaded after these.
	CSS []string
	JS  []string
}

Module describes a module - everything it owns, in one place, declared by the module's manifest package: what a disabled module hides is derived from here (ModuleOfNodeType, ModuleOfPluginBlock, ModuleOfPermission). Its code wires its routes (router.ModuleMux in internal/app/routes.go).

func ModuleByName

func ModuleByName(name string) (Module, bool)

ModuleByName - the built-in module with the name, false if unknown.

func (Module) CategoryName

func (m Module) CategoryName() string

CategoryName - the module's group: its Category when the engine knows it, else ModuleCategoryOther.

func (Module) PermissionKeys

func (m Module) PermissionKeys() []string

PermissionKeys - the keys of the module's permissions.

type ModuleCaptchaForm

type ModuleCaptchaForm struct {
	Key     string
	Label   string
	Default bool
}

ModuleCaptchaForm - a module's form that can show the CAPTCHA: its key (CaptchaSettings.Forms), its label on the settings page (translation source) and whether it shows it until the settings say otherwise.

func CaptchaForms

func CaptchaForms() []ModuleCaptchaForm

CaptchaForms - every CAPTCHA form, in the order of the settings page: the core's, then the registered modules'.

type ModuleCategory

type ModuleCategory struct {
	Name  string
	Label string
}

ModuleCategory - a group of the Modules page: its name and label.

func ModuleCategories

func ModuleCategories() []ModuleCategory

ModuleCategories - the groups of the Modules page, in its order.

type ModuleData

type ModuleData struct {
	Label string
	Table string
}

ModuleData - a table of a module's data, as the Modules page names it.

type ModuleFileSource

type ModuleFileSource struct {
	Source      string
	Table       string
	IDColumn    string
	Columns     []string
	Label       string
	NodeBacked  bool
	TitleColumn string
	EditPath    string
}

ModuleFileSource - a module's texts that can link to users' files: the HTML Columns of Table, recorded against IDColumn. Label names a place of use ("Quote "@title"", a translation source). NodeBacked - IDColumn is a node's ID: the title and link are the node's; otherwise the title is the start of TitleColumn and the link EditPath + the ID - without TitleColumn neither (a private text, such as a private message: Label alone).

func ModuleFileSourceByKey

func ModuleFileSourceByKey(source string) (ModuleFileSource, bool)

ModuleFileSourceByKey - a registered module's file source by its key.

type ModuleLabelColumn

type ModuleLabelColumn struct {
	Table  string
	Column string
}

ModuleLabelColumn - a column of labels in a module's table (rows keyed by an id column).

type ModuleMenuItem

type ModuleMenuItem struct {
	Section string
	Item    AdminMenuItem
}

ModuleMenuItem - a module's page in the admin toolbar: Section - the label (translation source) of the section it joins (AdminSection*). Item.Module is set to the module by AdminMenu().

type ModuleNodeFiles

type ModuleNodeFiles struct {
	Table      string
	FileColumn string
	NodeColumn string
	Via        string
	ViaColumn  string
}

ModuleNodeFiles - a module's table of files attached to nodes: Table.FileColumn, whose node is Table.NodeColumn, or with Via set Via.NodeColumn of the Via row Table.ViaColumn points to (Via.id).

type ModuleNodeType

type ModuleNodeType struct {
	Name  string
	Label string
	// CreatePath - its standalone create page; empty when it is created
	// elsewhere (a forum topic inside a forum section).
	CreatePath string
	// PathPrefix - prepended to a node's slug that doesn't carry it yet
	// (NodeRelPath): a forum topic's bare slug lives under "forum/".
	PathPrefix string
	// OwnDiscussion - its comments are a discussion of their own (a forum
	// topic's replies), kept out of the site's latest comments.
	OwnDiscussion bool
	// EditPath / DeletePath - its own edit and delete pages, "{id}" the
	// node's ID ("" - the core's /node/{id}/edit and /delete).
	EditPath   string
	DeletePath string
}

ModuleNodeType - a node type a module provides.

type ModulePermission

type ModulePermission struct {
	Key   string
	Label string
}

ModulePermission - a permission a module adds: its key and its label (a translation source).

type ModulePluginBlock

type ModulePluginBlock struct {
	ID     PluginBlockID
	Label  string
	Region Region
}

ModulePluginBlock - a plugin block a module provides and its label in the block picker (a translation source). Region - where installing the module places it: that region of the site's active theme, if the theme has it (migrations.PlaceModuleBlocks); "" - the site places it on the Blocks page.

type ModuleRepository

type ModuleRepository interface {
	States(ctx context.Context) (map[string]bool, error)
	SetEnabled(ctx context.Context, name string, enabled bool) error
	// CountRows - rows in a module's data table (Module.Data).
	CountRows(ctx context.Context, table string) (int, error)
	// PluginPlacements - where the plugin blocks are placed, every theme.
	PluginPlacements(ctx context.Context, ids []PluginBlockID) ([]PluginPlacementRef, error)
	// DeletePluginPlacements removes the plugin blocks' placements, every
	// theme (a module's uninstall).
	DeletePluginPlacements(ctx context.Context, ids []PluginBlockID) error
	// DeleteMenuLinks removes the menu links to paths (Module.Paths: each
	// path and the ones under it), every menu; a removed link's children
	// take its place (a module's uninstall).
	DeleteMenuLinks(ctx context.Context, paths []string) error
}

ModuleRepository stores which modules and features are switched off; a name with no row is enabled.

type Node

type Node struct {
	ID           int
	Type         ContentType
	Title        string
	Slug         string
	PageSEO      PageSEO
	Status       int
	OnModeration int
	Counter      Counter
	CreatedBy    User
	CreatedAt    time.Time
	UpdatedAt    time.Time
	// CommentMode - this node's comment visibility. Copied from the type's
	// ContentTypeDef.DefaultCommentMode at creation, then edited per node.
	// The DB default is CommentModeOpen.
	CommentMode CommentMode
	// PathAuto - the slug follows the type's path pattern
	// (ContentTypeDef.PathPattern) on every save; off - set by hand.
	PathAuto bool
	// Promote - "on the front page", Sticky - "at the top of lists":
	// Views filter (ViewFilterBuiltinPromote/Sticky) and sort
	// (ViewSortBuiltinSticky) by them. A new node takes its type's
	// DefaultPromote/DefaultSticky; who may administer content sets them.
	Promote bool
	Sticky  bool
	// PublishOn / UnpublishOn - when the scheduled publishing publishes
	// or unpublishes the node (ScheduledPublishing); zero - not scheduled.
	PublishOn   time.Time
	UnpublishOn time.Time
	// ParentID - an item of a blocks field (FieldTypeBlocks): the node
	// holding it; 0 - content of its own.
	ParentID int
	// ViewRoles - the roles who may view the item, of those its type is
	// for (ContentTypeDef.ViewRoles); none - whoever may view its type.
	// Its author, who may edit it and who may view every content see it
	// anyway (AuthService.CanViewNode).
	ViewRoles []string
	// DeletedAt / DeletedBy - in the trash since then, put there by that
	// user (0 - unknown); zero - not in the trash. A node in the trash is
	// left out of every query (WithTrashed - kept) and shown to nobody.
	DeletedAt time.Time
	DeletedBy int
	// Langcode - the content's language (i18n code); its addresses carry
	// the language's prefix (LanguagePrefix), the default one's none.
	Langcode string
}

Node - a content item (a nodes row): its type, title, address (Slug), status (1 - published), author and dates; its content type's fields are DynamicContent's.

func (Node) InTrash

func (n Node) InTrash() bool

InTrash - whether the node is in the trash (DeletedAt).

func (Node) IsPublic

func (n Node) IsPublic() bool

IsPublic - published and not on moderation: everyone sees it (an unpublished node only who may view unpublished content, one on moderation its author too).

func (Node) URL

func (n Node) URL() string

URL - the node's public path: "/" + NodeRelPath, after its language's prefix (LocalPath: /en/… - none for the site's default language). Templates and code link to a node only through it, never "/" + Slug.

func (Node) ViewableBy

func (n Node) ViewableBy(roles []string) bool

ViewableBy - whether a visitor with roles (UserRoleNames) is one of those the item is for (ViewRoles), whatever its type.

type NodeCounterRepository

type NodeCounterRepository interface {
	// IncrementView counts a view of the node: its totals and its views
	// of the site's day.
	IncrementView(ctx context.Context, nid int) error
	// DeleteViewDaysBefore drops the views by day older than day
	// (ViewDay).
	DeleteViewDaysBefore(ctx context.Context, day int) error
}

NodeCounterRepository updates node_counter view aggregates.

type NodeDeleteRepository

type NodeDeleteRepository interface {
	DeleteNode(ctx context.Context, nodeID int) error
}

NodeDeleteRepository - the single node-delete path for every content type (see database.NodeDeleteRepository): rows without an ON DELETE CASCADE foreign key are removed explicitly, everything else goes with the nodes row, all in one transaction.

type NodePublishing

type NodePublishing string

NodePublishing - a content type's publishing of new nodes (ContentTypeDef.DefaultPublishing).

const (
	// NodePublished - published at once, everyone sees it.
	NodePublished NodePublishing = "published"
	// NodeToModeration - published and on moderation: its author sees
	// it, the moderation queue lists it, the others don't until a
	// moderator approves it.
	NodeToModeration NodePublishing = "moderation"
	// NodeUnpublished - unpublished: only who may view unpublished
	// content sees it.
	NodeUnpublished NodePublishing = "unpublished"
)

func (NodePublishing) Flags

func (p NodePublishing) Flags() (status, onModeration int)

Flags - a new node's Node.Status and Node.OnModeration; an unknown publishing goes to moderation.

func (NodePublishing) Valid

func (p NodePublishing) Valid() bool

Valid - one of the publishings.

type NodeRevision

type NodeRevision struct {
	ID        int
	NodeID    int
	User      *User
	CreatedAt time.Time
	Kind      RevisionKind
	// RevertedFromAt - when the revision a RevisionRevert brought back was
	// saved.
	RevertedFromAt time.Time
	// Changed - the snapshot's keys that differ from the revision before
	// (NodeSnapshot.Diff); empty for the first one.
	Changed  []string
	Snapshot NodeSnapshot
}

NodeRevision - one saved state of a node (NodeSnapshot), who saved it (nil - RevisionBaseline or a deleted account) and when.

type NodeRevisionRepository

type NodeRevisionRepository interface {
	Create(ctx context.Context, rev NodeRevision) (int, error)
	// Latest - the node's newest revision; nil without one.
	Latest(ctx context.Context, nodeID int) (*NodeRevision, error)
	// ByID - the revision id of the node nodeID (ErrEntityNotFound for
	// another node's).
	ByID(ctx context.Context, nodeID, id int) (*NodeRevision, error)
	// List - a page of the node's revisions, newest first, and how many
	// it has.
	List(ctx context.Context, nodeID, offset, limit int) ([]NodeRevision, int, error)
	// Prune deletes the node's oldest revisions beyond keep.
	Prune(ctx context.Context, nodeID, keep int) error
	// Recent - a page of the revisions of every node the filter shows,
	// newest first, and how many there are.
	Recent(ctx context.Context, f RecentRevisionsFilter) ([]RecentRevision, int, error)
}

NodeRevisionRepository - the nodes' revisions, newest last by ID.

type NodeSchedule

type NodeSchedule struct {
	Publish   int
	Unpublish int
	Next      time.Time
}

NodeSchedule - the scheduled publishing as a whole: how many nodes wait to be published and unpublished, and when the nearest one is due (zero - none).

type NodeScheduleRepository

type NodeScheduleRepository interface {
	// DueToPublish / DueToUnpublish - the nodes whose time has come by now.
	DueToPublish(ctx context.Context, now time.Time) ([]int, error)
	DueToUnpublish(ctx context.Context, now time.Time) ([]int, error)
	// Schedule - what waits.
	Schedule(ctx context.Context) (NodeSchedule, error)
}

NodeScheduleRepository - the nodes' scheduled publishing (Node.PublishOn, UnpublishOn).

type NodeSearchHit

type NodeSearchHit struct {
	Node  Node
	Match string
}

NodeSearchHit - one NodesRepository.SearchByTitle result.

type NodeSnapshot

type NodeSnapshot struct {
	Title           string                     `json:"title"`
	Status          int                        `json:"status"`
	OnModeration    int                        `json:"on_moderation"`
	Promote         bool                       `json:"promote"`
	Sticky          bool                       `json:"sticky"`
	CommentMode     string                     `json:"comment_mode"`
	Slug            string                     `json:"slug"`
	AuthorID        int                        `json:"author_id"`
	MetaTitle       string                     `json:"meta_title,omitempty"`
	MetaDescription string                     `json:"meta_description,omitempty"`
	Fields          map[string]json.RawMessage `json:"fields,omitempty"`
	TextFormats     map[string]int             `json:"text_formats,omitempty"`
}

NodeSnapshot - a node of an admin-created type as a revision keeps it: its own fields, SEO and field values. Values are JSON, keyed by the field's machine name (a field added or removed later doesn't shift them), so two snapshots compare by their bytes.

func DecodeNodeSnapshot

func DecodeNodeSnapshot(s string) (NodeSnapshot, error)

DecodeNodeSnapshot - a stored snapshot.

func SnapshotOf

func SnapshotOf(dc DynamicContent) NodeSnapshot

SnapshotOf - the snapshot of dc (its values by dc.Fields); a value of a type it can't encode is left out.

func (NodeSnapshot) Diff

func (s NodeSnapshot) Diff(next NodeSnapshot) []string

Diff - the keys of what differs between s and next: their own parts (SnapshotTitle…) in that order, then the fields (SnapshotFieldKey) by machine name; a field's value (a text's white space aside) or its text format.

func (NodeSnapshot) Encode

func (s NodeSnapshot) Encode() (string, error)

Encode - the snapshot as stored (NodeRevision's snapshot column).

func (NodeSnapshot) Values

func (s NodeSnapshot) Values(fields FieldInstanceDefs) (map[int]any, map[int]int)

Values - the snapshot's values of fields, typed as DynamicContentRepository reads them, and their text formats, keyed by field instance ID. A field the snapshot hasn't, or whose value doesn't decode as the field's type (its type changed since), is left out.

type NodeTrashRepository

type NodeTrashRepository interface {
	// TrashNode puts nodeID in the trash at at, by user by (0 - unknown).
	TrashNode(ctx context.Context, nodeID, by int, at time.Time) error
	// RestoreNode takes nodeID out of the trash.
	RestoreNode(ctx context.Context, nodeID int) error
	// TrashedNodes - the nodes in the trash, the latest put there first, a
	// page of limit from offset, and how many there are.
	TrashedNodes(ctx context.Context, limit, offset int) (Nodes, int, error)
	// TrashedBefore - the nodes put in the trash before before.
	TrashedBefore(ctx context.Context, before time.Time) ([]int, error)
}

NodeTrashRepository - the trash (Node.DeletedAt): a node put there is left out of every query until restored or deleted for good.

type Nodes

type Nodes []Node

Nodes - a list of nodes.

type NodesRepository

type NodesRepository interface {
	ByID(ctx context.Context, nodeID int) (*Node, error)
	// URLsByIDs - the public addresses (Node.URL) of the nodes among ids
	// that exist, in one query (a menu's links).
	URLsByIDs(ctx context.Context, ids []int) (map[int]string, error)
	BySlug(ctx context.Context, slug string) (*Node, error)
	// SearchByTitle - generic node search for pickers (menu link
	// target, reference fields' edit widget): published nodes whose
	// nodes.title - or any short (≤ 255 chars) text field value, e.g. a
	// localized title field - contains query; types (machine names)
	// narrows the result, empty = every type. Match is the short field
	// value that matched when the title itself didn't.
	SearchByTitle(ctx context.Context, query string, types []string, limit int) ([]NodeSearchHit, error)
	ListForAdmin(ctx context.Context, filter AdminNodesFilter) (*Nodes, int, error)
	// SlugExists/SlugExistsExcludingNode - whether a node has the slug.
	// Slugs share one URL space (nodes.slug is unique across all types).
	SlugExists(ctx context.Context, slug string) (bool, error)
	SlugExistsExcludingNode(ctx context.Context, slug string, excludeNodeID int) (bool, error)
	// ProfileMaterialDisplayTitle - the title for lists: the type's alternative
	// title field (ContentTypeDef.AltTitleField) if set, otherwise n.Title.
	ProfileMaterialDisplayTitle(ctx context.Context, n Node) string
	// AltTitles - ProfileMaterialDisplayTitle's alternative titles for a
	// list of nodes, by node ID (those without one left out).
	AltTitles(ctx context.Context, nodes Nodes) (map[int]string, error)
	UpdateStatus(ctx context.Context, nodeID int, status int) error
	UpdateOnModeration(ctx context.Context, nodeID int, onModeration int) error
	// SetLangcode sets the node's language (Node.Langcode); its words in
	// the search index are stemmed in it again.
	SetLangcode(ctx context.Context, nodeID int, code string) error
	// UpsertPageSEO creates or updates page_seo for the node. Empty metaTitle and metaDescription removes the row (fallback to PageSEO() defaults).
	UpsertPageSEO(ctx context.Context, nodeID int, metaTitle, metaDescription string) error
	// PageSEO - the node's own title and description (page_seo), empty
	// without them.
	PageSEO(ctx context.Context, nodeID int) (PageSEO, error)
	// CreateRow and UpdateRow - a node's own row: its type, title, slug,
	// status, moderation, comment mode, author and dates (UpdateRow keeps
	// the author and the creation time it isn't given) - for a module's
	// content type with pages of its own, whose rows go with it (in the
	// context's transaction). CreateRow returns the new node's ID.
	CreateRow(ctx context.Context, n Node) (int, error)
	UpdateRow(ctx context.Context, n Node) error
	// ByType - the nodes of a type (ID and title), the newest first.
	ByType(ctx context.Context, nodeType string) (Nodes, error)
	// ByIDs - the nodes among ids that exist, by ID: their own columns
	// (ID, type, title, slug, status, the author's ID in CreatedBy.ID), no
	// edges - in one query (a module's rows that reference nodes).
	ByIDs(ctx context.Context, ids []int) (map[int]Node, error)

	// CountPublicSitemapNodes counts published nodes visible to anonymous users (status=1, on_moderation=0, non-empty slug), except types whose page redirects (ContentTypeDef.RedirectField) and excludeTypes.
	CountPublicSitemapNodes(ctx context.Context, excludeTypes []string) (int, error)
	// ListPublicSitemapNodes returns rows ordered by updated_at desc, id desc.
	ListPublicSitemapNodes(ctx context.Context, excludeTypes []string, limit, offset int) ([]SitemapNodeRow, error)
	// ListForFeed - the materials a feed takes (see FeedNodeFilter).
	ListForFeed(ctx context.Context, filter FeedNodeFilter) (Nodes, error)

	// CountByType counts all nodes of the given type (any status); guards
	// deleting/renaming a content type that still has nodes.
	CountByType(ctx context.Context, nodeType string) (int, error)
	// PathBatch - up to limit nodes of nodeType after afterID (by ID),
	// for rebuilding their addresses: ID, type, title, slug, created,
	// PathAuto; onlyAuto - those following their type's pattern.
	// CountPathNodes counts them.
	PathBatch(ctx context.Context, nodeType string, afterID, limit int, onlyAuto bool) (Nodes, error)
	CountPathNodes(ctx context.Context, nodeType string, onlyAuto bool) (int, error)
	// SetPath - a node's slug and PathAuto; its updated time stays (the
	// content didn't change).
	SetPath(ctx context.Context, nodeID int, slug string, auto bool) error
}

NodesRepository - storage port for the nodes.

type NumberKind

type NumberKind string

NumberKind - what a number field holds: any number as typed (a field made before the setting), whole numbers, or numbers with a fixed count of decimals (NumberDecimals).

const (
	NumberAny     NumberKind = ""
	NumberInteger NumberKind = "integer"
	NumberDecimal NumberKind = "decimal"
)

The number kinds: any number, whole numbers, decimals.

type OAuthCredentials

type OAuthCredentials struct {
	ClientID     string
	ClientSecret string
}

OAuthCredentials - a provider app's keys, from the server config or the admin settings.

func (OAuthCredentials) Enabled

func (c OAuthCredentials) Enabled() bool

Enabled - both keys are set.

type OAuthProviderSettings

type OAuthProviderSettings struct {
	Provider string
	// Enabled - off hides the provider even with the config's keys.
	Enabled      bool
	ClientID     string
	ClientSecret string
}

OAuthProviderSettings - a social login provider's settings saved in the admin. Empty keys mean the server config's keys apply.

type OAuthSettingsRepository

type OAuthSettingsRepository interface {
	// List - the saved rows by provider name.
	List(ctx context.Context) (map[string]OAuthProviderSettings, error)
	Upsert(ctx context.Context, s OAuthProviderSettings) error
	// LinkedAccounts - the number of accounts linked to each provider.
	LinkedAccounts(ctx context.Context) (map[string]int, error)
}

OAuthSettingsRepository stores the providers' settings, a row each.

type PageSEO

type PageSEO struct {
	Title        string
	Description  string
	Canonical    string
	OGImage      string
	OGURL        string
	PreloadImage string // LCP image
	// PreloadImageSrcset - PreloadImage's srcset, as its <img> has it.
	PreloadImageSrcset string
	NoIndex            bool // pages without content of their own (login and the like): <meta name="robots" content="noindex, follow">
}

PageSEO - a page's head metadata: the title, the meta description, the canonical URL, the Open Graph image and URL, the image to preload and noindex.

type PluginBlockID

type PluginBlockID string

PluginBlockID - a built-in block type whose content is rendered by Go and templates rather than edited as text (unlike BlockDef.Body). Region, weight and visibility work the same as for custom blocks.

const (
	// PluginBlockLogo - the site logo (SiteInformation.Logo); none uploaded -
	// nothing.
	PluginBlockSearchForm   PluginBlockID = "search_form"
	PluginBlockUserMenu     PluginBlockID = "user_menu"
	PluginBlockLastComments PluginBlockID = "last_comments"
	// PluginBlockTagCloud - the most used terms (TagCloudTerm), the
	// more materials a term is on, the bigger (its settings:
	// TagCloudVocabularyKey, TagCloudCountKey, TagCloudLevelsKey).
	PluginBlockTagCloud PluginBlockID = "tag_cloud"
	// PluginBlockCopyright - the copyright line: "© <year> <holder>", the
	// current year, from a first year when set (CopyrightSinceKey), the
	// holder the site's name unless set (CopyrightHolderKey).
	PluginBlockCopyright PluginBlockID = "copyright"
)

The core's plugin blocks (corePluginBlocks).

func PluginBlocks

func PluginBlocks() []PluginBlockID

PluginBlocks - plugin blocks offered by the admin "Add system block" picker: the core's, then the registered modules'.

type PluginBlockSetting

type PluginBlockSetting struct {
	Key     string
	Label   string
	Type    PluginBlockSettingType
	Default string
	Min     int
	Max     int
	Options []PluginBlockTarget
}

PluginBlockSetting - one setting of a plugin block on its placement page, stored in its PluginConfig under Key (service.SetPluginBlockSettings). Label - the English label, translated by the page; Default - the value while unset.

func (PluginBlockSetting) Check

func (s PluginBlockSetting) Check(value string) bool

Check reports whether value is one the setting accepts.

type PluginBlockSettingType

type PluginBlockSettingType string

PluginBlockSettingType - how a plugin block's setting is entered.

const (
	// PluginBlockSettingNumber - a whole number from Min to Max.
	PluginBlockSettingNumber PluginBlockSettingType = "number"
	// PluginBlockSettingSelect - one of Options.
	PluginBlockSettingSelect PluginBlockSettingType = "select"
	// PluginBlockSettingText - a line of text of at most Max characters
	// (empty allowed), no line breaks or control characters.
	PluginBlockSettingText PluginBlockSettingType = "text"
)

type PluginBlockTarget

type PluginBlockTarget struct {
	Value string
	Label string
}

PluginBlockTarget - one thing a block can show (its PluginConfig "target"), as the placement page offers it.

type PluginPlacementRef

type PluginPlacementRef struct {
	PluginID PluginBlockID
	Theme    string
	Region   Region
}

PluginPlacementRef - where a plugin block is placed.

type PopularNode

type PopularNode struct {
	Node  Node
	Views int
	Total int
}

PopularNode - a published content item with its views in a period (Views) and all its views (Total).

type PopularPeriod

type PopularPeriod string

PopularPeriod - the period the popular content is counted over.

const (
	// PopularPeriodToday - the site's day (node_counter.daycount).
	PopularPeriodToday PopularPeriod = "today"
	// PopularPeriodWeek - the last 7 days, today's included (the views
	// by day).
	PopularPeriodWeek PopularPeriod = "week"
	// PopularPeriodMonth - the last 30 days, today's included.
	PopularPeriodMonth PopularPeriod = "month"
	// PopularPeriodAll - for ever (node_counter.totalcount).
	PopularPeriodAll PopularPeriod = "all"
)

func ParsePopularPeriod

func ParsePopularPeriod(p string) PopularPeriod

ParsePopularPeriod - p if it's a period, else PopularPeriodToday.

func (PopularPeriod) Days

func (p PopularPeriod) Days() int

Days - how many days of the views by day the period sums, today's included; 0 - it isn't counted from them (today, for ever).

type PopularQuery

type PopularQuery struct {
	Period        PopularPeriod
	Today         time.Time
	Type          string
	Limit, Offset int
}

PopularQuery - which popular content: of Period, counted from Today (the start of the site's day), of the content type Type ("" - of any), a page of it (Limit, Offset).

type PreviewLink struct {
	NodeID    int
	ExpiresAt time.Time
	CreatedBy int
	CreatedAt time.Time
}

PreviewLink - a link showing a content item to whoever has it, even unpublished, until ExpiresAt (service.PreviewLinks): a draft shown to a reviewer without an account.

type PreviewLinkRepository

type PreviewLinkRepository interface {
	// ReplacePreviewLink makes nodeID's link (an earlier one gone).
	ReplacePreviewLink(ctx context.Context, link PreviewLink, tokenHash string) error
	// PreviewLinkOf - nodeID's link; ErrEntityNotFound - none.
	PreviewLinkOf(ctx context.Context, nodeID int) (*PreviewLink, error)
	// PreviewLinkByHash - the link of a token's hash; ErrEntityNotFound -
	// none.
	PreviewLinkByHash(ctx context.Context, tokenHash string) (*PreviewLink, error)
	// DeletePreviewLinks removes nodeID's link.
	DeletePreviewLinks(ctx context.Context, nodeID int) error
}

PreviewLinkRepository - the preview links, by the SHA-256 of their tokens (the token itself is shown once); a node has one at most.

type RecentRevision

type RecentRevision struct {
	NodeRevision
	NodeTitle  string
	NodeType   string
	NodeURL    string
	PreviousID int
}

RecentRevision - a revision as the recent changes list it: its node's title, type and address (as they are now) and the node's revision before it (PreviousID, 0 - none kept). Snapshot holds only Status and OnModeration, and only when they alone changed.

type RecentRevisionsFilter

type RecentRevisionsFilter struct {
	Title, Type, Actor string
	From, To           time.Time
	AnyTypes, OwnTypes []string
	OwnerID            int
	Offset, Limit      int
}

RecentRevisionsFilter - the revisions the recent changes show: Title - a part of the node's title, Type - its type, Actor - a part of the saver's name, From/To - the days (To - the day after the last; zero - none). AnyTypes, OwnTypes - what the viewer may see: every node of AnyTypes, the published nodes of OwnTypes that OwnerID created.

type Redirect

type Redirect struct {
	ID       int
	FromPath string // path without leading slash
	ToPath   string // destination path with leading slash
}

Redirect represents a 301 redirect rule

type RedirectRepository

type RedirectRepository interface {
	List(ctx context.Context) ([]Redirect, error)
	// Search - a page of the redirects whose from or to path contains q
	// (letter case aside; "" - all), by from path, and how many there are.
	Search(ctx context.Context, q string, offset, limit int) ([]Redirect, int, error)
	Create(ctx context.Context, r Redirect) (*Redirect, error)
	Delete(ctx context.Context, id int) error
	DeleteByFromPath(ctx context.Context, fromPath string) error
}

RedirectRepository defines the interface for redirect data access

type Region

type Region string

Region - a region machine name. Regions are declared by the theme in theme.yaml (ThemeInfo, themes.LoadInfo) and rendered by theme templates; Go has no list of them.

const RegionDisabled Region = "disabled"

RegionDisabled - the built-in "Hidden" region: the placement is kept but rendered nowhere. Exists in every theme and is not declared in theme.yaml.

type Requirement

type Requirement struct {
	Title       string
	Value       string
	Description string
	Severity    RequirementSeverity
	// Module - the module whose check it is; "" - the core's.
	Module string
}

Requirement - one line of the status report: what was checked, what was found and, when not OK, what to do. Title, Value and Description are already translated; Description is HTML (placeholders escaped by i18n), the others text.

func (Requirement) IsError

func (r Requirement) IsError() bool

IsError - whether the check found an error.

func (Requirement) IsWarning

func (r Requirement) IsWarning() bool

IsWarning - whether the check found something to warn about.

type RequirementSeverity

type RequirementSeverity int

RequirementSeverity - how a status check came out.

const (
	RequirementOK RequirementSeverity = iota
	RequirementWarning
	RequirementError
)

The status checks' severities: OK, a warning, an error.

type RevisionKind

type RevisionKind string

RevisionKind - how a revision came about.

const (
	// RevisionCreate - the node's first save.
	RevisionCreate RevisionKind = "create"
	// RevisionEdit - a later save: the form, publishing, moderation.
	RevisionEdit RevisionKind = "edit"
	// RevisionRevert - an earlier revision brought back
	// (NodeRevision.RevertedFromAt).
	RevisionRevert RevisionKind = "revert"
	// RevisionBaseline - the node as it was before its first save with the
	// history on: no author, the node's last update time.
	RevisionBaseline RevisionKind = "baseline"
)

type Role

type Role struct {
	ID          int
	Name        string
	Description string
	Permissions map[string]any
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Role represents a user role with permissions

func (Role) Label

func (r Role) Label() string

Label - the role's readable name (Description, set on the roles page), or its machine name when it has none: what the interface shows wherever roles are listed.

type RoleFilter

type RoleFilter struct {
	Name string
}

RoleFilter defines filters for role queries

type RoleRepository

type RoleRepository interface {
	Find(ctx context.Context, filter RoleFilter) (*Role, error)
	ByID(ctx context.Context, id int) (*Role, error)
	ByName(ctx context.Context, name string) (*Role, error)
	Create(ctx context.Context, role Role) (*Role, error)
	List(ctx context.Context) (*Roles, error)
	Delete(ctx context.Context, id int) error
	Update(ctx context.Context, role Role) (*Role, error)
	// CountUsers - how many users have the role.
	CountUsers(ctx context.Context, id int) (int, error)
}

RoleRepository defines the interface for role data access

type Roles

type Roles []Role

Roles is a slice of Role

type SEORuleDef

type SEORuleDef struct {
	ID          int
	ContentType string
	// FieldStorageID - the taxonomy field the condition reads; nil = the
	// rule matches every node of ContentType.
	FieldStorageID *int
	// TermIDs - comma-separated term IDs for the field condition.
	TermIDs             string
	TitleTemplate       string
	DescriptionTemplate string
	Weight              int
}

SEORuleDef - "content type + optional taxonomy field and its terms → own templates": like BreadcrumbRuleDef, with templates instead of a menu link. The lowest Weight wins.

func (SEORuleDef) FieldStorageIDValue

func (r SEORuleDef) FieldStorageIDValue() int

FieldStorageIDValue - FieldStorageID or 0.

func (SEORuleDef) HasTerm

func (r SEORuleDef) HasTerm(id int) bool

HasTerm reports whether id is one of the rule's terms.

func (SEORuleDef) TermIDList

func (r SEORuleDef) TermIDList() []int

TermIDList - TermIDs parsed (invalid entries skipped).

type SEORuleDefs

type SEORuleDefs []SEORuleDef

SEORuleDefs - a list of SEO rules.

type SEORuleRepository

type SEORuleRepository interface {
	// SEORules - all rules ordered by weight, then id.
	SEORules(ctx context.Context) (SEORuleDefs, error)
	SEORuleByID(ctx context.Context, id int) (*SEORuleDef, error)
	CreateSEORule(ctx context.Context, r SEORuleDef) (*SEORuleDef, error)
	UpdateSEORule(ctx context.Context, r SEORuleDef) error
	UpdateSEORuleWeight(ctx context.Context, id, weight int) error
	DeleteSEORule(ctx context.Context, id int) error
}

SEORuleRepository - storage port for the SEO rules.

type SEOTemplate

type SEOTemplate struct {
	Scope               string
	TitleTemplate       string
	DescriptionTemplate string
	// ImageTemplate - node scopes only: the og:image, e.g.
	// [node:field:<image field>].
	ImageTemplate string
	// SchemaType - node scopes only: the schema.org type of the pages'
	// JSON-LD (SchemaTypes); "" - the default scope's, SchemaNone - none.
	SchemaType string
	// SchemaProps - its properties' templates by name (SchemaPropDef).
	SchemaProps map[string]string
}

SEOTemplate - token templates of one scope; an empty template defers to the next level.

type SEOTemplateRepository

type SEOTemplateRepository interface {
	SEOTemplates(ctx context.Context) (SEOTemplates, error)
	SaveSEOTemplate(ctx context.Context, t SEOTemplate) error
}

SEOTemplateRepository - storage port for the SEO templates.

type SEOTemplates

type SEOTemplates map[string]SEOTemplate

SEOTemplates - by scope.

type SchemaPropDef

type SchemaPropDef struct {
	Name  string
	Label string
	Hint  string
}

SchemaPropDef - a property a content type's template fills: Name - its schema.org name ("keywords"), or a dotted one of an object ("location.name"); Label and Hint - the admin's (i18n.N).

type SchemaTypeDef

type SchemaTypeDef struct {
	// Name - the schema.org type ("Article").
	Name string
	// Label - the admin's name of it (i18n.N).
	Label string
	// Creative - a creative work: datePublished, dateModified.
	Creative bool
	// Article - headline instead of name, the author, the publisher.
	Article bool
	// Props - the properties the type's templates fill, beside those.
	Props []SchemaPropDef
	// Objects - the type of the object a dotted property ("offers.price")
	// goes into, by its first part ("offers" → "Offer").
	Objects map[string]string
}

SchemaTypeDef - a schema.org type a content type's pages are marked up as (JSON-LD): the vocabulary's, not a site's. Every one gets the page's name, description, image and address; Creative - its dates; Article - its author and the site as the publisher too.

func SchemaTypeByName

func SchemaTypeByName(name string) (SchemaTypeDef, bool)

SchemaTypeByName - the schema.org type name, if offered.

type SearchCategory

type SearchCategory struct {
	Label string `json:"label"`
	URL   string `json:"url"`
}

SearchCategory represents a category link for empty search state

type SearchConfigRepository

type SearchConfigRepository interface {
	// SearchTypes - every type's row (switched on or off), by weight.
	SearchTypes(ctx context.Context) (SearchTypeDefs, error)
	SaveSearchType(ctx context.Context, t SearchTypeDef) error
	UpdateSearchTypeWeight(ctx context.Context, nodeType string, weight int) error
	SearchSettings(ctx context.Context) (*SearchSettings, error)
	SaveSearchSettings(ctx context.Context, s SearchSettings) error
}

SearchConfigRepository - storage port for the live search's settings: its types and the site-wide row.

type SearchResult

type SearchResult struct {
	ID        int    `json:"id"`
	Type      string `json:"type"`     // content type machine name, e.g. article
	URL       string `json:"url"`      // /articles/foo
	Title     string `json:"title"`    // the type's title field, else the node title
	Subtitle  string `json:"subtitle"` // the type's subtitle field (search settings)
	ImageURL  string `json:"image_url"`
	Badge     string `json:"badge"`      // terms of the badge vocabulary (search settings)
	TypeLabel string `json:"type_label"` // human label of the type
	// Snippet - the piece of the item's text with the query's words (the
	// results page's: SearchService.WithSnippets).
	Snippet SearchSnippet `json:"-"`
}

SearchResult represents a single search result for live search autocomplete

type SearchSettings

type SearchSettings struct {
	// PlaceholderImage - the picture of a result without one.
	PlaceholderImage string
	// CategoriesMenu - the menu whose links the empty search shows.
	CategoriesMenu string
}

SearchSettings - the live search's site-wide settings (single row).

type SearchSnippet

type SearchSnippet struct {
	Parts         []SearchSnippetPart
	Before, After bool
}

SearchSnippet - a piece of a search result's text around the query's words: its parts, the words marked (Match); Before, After - the text goes on there.

type SearchSnippetPart

type SearchSnippetPart struct {
	Text  string
	Match bool
}

SearchSnippetPart - a piece of a snippet's text.

type SearchTypeDef

type SearchTypeDef struct {
	NodeType string
	// Enabled - false: the type is left out of the search.
	Enabled bool
	Weight  int
	// Limit - results of this type from the field search.
	Limit int
	// Label - the result's type label.
	Label string
	// MatchFields - text field machine names searched besides the title.
	MatchFields []string
	// AllFields - all the type's text fields are searched besides the
	// title, new ones too (MatchFields is then only kept for the form).
	AllFields bool
	// TitleField - the result's title (empty value or field - the node
	// title); SubtitleField - its second line.
	TitleField    string
	SubtitleField string
	// ImageField - an image field for the picture (a node without a value
	// gets the field's default image; empty - none: the results get
	// SearchSettings.PlaceholderImage); ImageStyle - its image style.
	ImageField string
	ImageStyle string
	// BadgeVocabularyID - the vocabulary whose terms of the node form the
	// result's caption ("A / B / "); 0 - none.
	BadgeVocabularyID int
}

SearchTypeDef - how one node type takes part in the live search: which text fields are searched besides the title, how many results, and how a result is shown. A type with no row is searched with the defaults (DefaultSearchLimit, its title); one switched off (Enabled false) isn't.

type SearchTypeDefs

type SearchTypeDefs []SearchTypeDef

SearchTypeDefs - a list of the live search's types.

type Settings

type Settings struct {
	// Domain - the site's canonical origin (config public_base_url /
	// PUBLIC_BASE_URL, else the address saved in Site information), no
	// trailing slash; empty - URLs stay site-relative.
	Domain string
}

Settings - the process's site-wide settings (NewSystemSettings): the site's canonical origin.

func NewSystemSettings

func NewSystemSettings() Settings

NewSystemSettings - the settings as SetSiteDomain last set them.

type SiteInformation

type SiteInformation struct {
	SiteName  string
	Slogan    string
	SiteEmail string
	// Empty - the header logo block falls back to the theme's default logo.
	Logo File
	// Icon - the site's icon (favicon, the home screen's icon); only the
	// URI is stored. Empty - the theme's (theme.yaml "favicon",
	// service.SiteIconFor).
	Icon File
	// FrontFeedView - machine_name of the View that provides the front page
	// feed (and the RSS feed's items). Empty - no feed.
	FrontFeedView string
	// Timezone - the site's time zone (IANA name, e.g. "Europe/Berlin"):
	// dates are stored in UTC and shown in it (pkg/sitetime). Empty - UTC.
	Timezone string
	// DefaultLanguage - the site's interface language (a pkg/i18n catalog
	// language, e.g. "ru"; "en" - the source strings).
	DefaultLanguage string
	// Languages - the site's languages besides DefaultLanguage, each with
	// its addresses' prefix (SetSiteLanguages); none - one language.
	Languages []SiteLanguage
	// Page404, Page403 - paths of published nodes shown, with the error
	// status, for "not found" and "access denied", one per line (a random
	// one each time). Empty - the theme's or the engine's default page.
	Page404 string
	Page403 string
	// Theme - the active theme chosen on the Appearance page: a directory
	// under themes/, "" - the engine's own templates. Nil -
	// not chosen; the config's theme applies.
	Theme *string
	// BaseURL - the site's canonical origin (e.g. https://www.example.com,
	// no trailing slash) for absolute URLs: sitemap, RSS, canonical links,
	// OAuth callbacks. The config's public_base_url, when set, overrides
	// it (service.SiteURL). Empty - derived from the request.
	BaseURL string
	// RobotsExtra - the site's own robots.txt rules, added after the
	// engine's and the modules' (service.RobotsTxt).
	RobotsExtra string
	// SchemaOrg - who runs the site, for search engines (SetSchemaOrg).
	SchemaOrg SiteSchemaOrg
}

SiteInformation is the row from site_information (site name, slogan, admin contact email).

type SiteInformationRepository

type SiteInformationRepository interface {
	Get(ctx context.Context) (*SiteInformation, error)
	Update(ctx context.Context, s *SiteInformation) error
	SetTheme(ctx context.Context, theme string) error
	SetRobotsExtra(ctx context.Context, rules string) error
	SetLanguages(ctx context.Context, languages []SiteLanguage) error
	// SetSchemaOrg stores who runs the site (SiteInformation.SchemaOrg).
	SetSchemaOrg(ctx context.Context, o SiteSchemaOrg) error
}

SiteInformationRepository persists site-wide branding and contact.

type SiteLanguage

type SiteLanguage struct {
	Code   string `json:"code"`
	Prefix string `json:"prefix"`
}

SiteLanguage - a language of the site besides its default one: its code (i18n, "en") and the prefix of its addresses ("en" - /en/…).

func MoveDefaultLanguage

func MoveDefaultLanguage(others []SiteLanguage, oldDef, newDef string) []SiteLanguage

MoveDefaultLanguage - others once newDef becomes the default language instead of oldDef: newDef leaves them, oldDef joins them with its code as the prefix (its addresses move under /<code>/).

func SiteLanguages

func SiteLanguages() (string, []SiteLanguage)

SiteLanguages - the default language and the others in use (SetSiteLanguages, SetLanguagesSwitch).

type SiteSchemaOrg

type SiteSchemaOrg struct {
	// Kind - SchemaOrgOrganization (also ""), SchemaOrgLocalBusiness,
	// SchemaOrgPerson.
	Kind string `json:"kind,omitempty"`
	// Name - "" - the site's name.
	Name string `json:"name,omitempty"`
	// SameAs - its pages elsewhere (social networks, directories).
	SameAs []string `json:"same_as,omitempty"`
	Phone  string   `json:"phone,omitempty"`
	Email  string   `json:"email,omitempty"`
	// Address - a local business's.
	Address string `json:"address,omitempty"`
	// SearchBox - the site's search in the results (WebSite's
	// SearchAction).
	SearchBox bool `json:"search_box,omitempty"`
}

SiteSchemaOrg - who runs the site, for search engines: the publisher of its articles, its card in the results (the front page's JSON-LD).

func (SiteSchemaOrg) TypeName

func (o SiteSchemaOrg) TypeName() string

TypeName - the schema.org type of Kind.

type SitemapNodeRow

type SitemapNodeRow struct {
	ID        int
	Slug      string
	Type      string
	Langcode  string
	UpdatedAt time.Time
}

SitemapNodeRow holds minimal node fields for sitemap URL generation.

type StatisticsSettings

type StatisticsSettings struct {
	ViewCountingEnabled bool
	// DailyViewsKeepDays - how many days the views by day are kept (the
	// popular content of a period); 0 - for ever.
	DailyViewsKeepDays int
}

StatisticsSettings is the row from statistics_settings (view counting toggle, how long the views by day are kept).

type StatisticsSettingsRepository

type StatisticsSettingsRepository interface {
	Get(ctx context.Context) (*StatisticsSettings, error)
	Update(ctx context.Context, s *StatisticsSettings) error
}

StatisticsSettingsRepository persists site-wide statistics preferences.

type StatusModule

type StatusModule struct {
	Name      string
	Label     string
	Enabled   bool
	Installed bool
	// SchemaVersion, SchemaStep, SchemaUpdated - the module's database
	// step applied last: its version, its name and when it was applied.
	SchemaVersion string
	SchemaStep    string
	SchemaUpdated time.Time
}

StatusModule - a module on the status report: its state and the database step of its set applied last (SchemaVersion "" - none).

type StoredMail

type StoredMail struct {
	Enabled bool
	MailTemplate
}

StoredMail - what the Mail page changed of an email (mail_templates): whether it is sent, its own text (blank - the default).

type TagCloudTerm

type TagCloudTerm struct {
	Term   TaxonomyTerm
	Count  int
	Level  int
	Linked bool
}

TagCloudTerm - a term in the tag cloud (PluginBlockTagCloud): Count - the published materials it is on, Level - its size step, 1 (the fewest) to the block's levels (the most), Linked - its vocabulary has public term pages (PublicTermPages), so it links to its page.

type TagSpecification

type TagSpecification struct {
	Value string // ID or name
	IsNew bool   // true = create a new term, false = use an existing one
}

TagSpecification - a tag of a tags input: an existing term's ID, or a new tag's name (TaxonomyService.ProcessTagInputs finds or creates its term).

type TaxonomyRepository

type TaxonomyRepository interface {
	NodeTermsByID(ctx context.Context, nID int) (TaxonomyTerms, error)
	// NodeTermsByIDs is NodeTermsByID batched over many node IDs in one query.
	NodeTermsByIDs(ctx context.Context, nodeIDs []int) (map[int]TaxonomyTerms, error)
	TermBySlug(ctx context.Context, slug string) (*TaxonomyTerm, error)
	// CountNodesByTermID - the nodes the term is on, of any status: in the
	// index or in a taxonomy field's values (which keep the term from
	// being deleted).
	CountNodesByTermID(ctx context.Context, termID int) (int, error)
	// TermNodeCounts - how many published materials (not on moderation)
	// each term of the vocabulary is on (0 - every vocabulary), by term
	// ID; terms on none are left out.
	TermNodeCounts(ctx context.Context, vocabularyID int) (map[int]int, error)
	SearchTermsByName(ctx context.Context, vocabularyID int, query string, limit int) (TaxonomyTerms, error)
	TermsByVocabularyID(ctx context.Context, vocabularyID int) (TaxonomyTerms, error)
	CreateTerm(ctx context.Context, vocabularyID int, name, slug string, createdBy int) (*TaxonomyTerm, error)
	UpdateNodeTerms(ctx context.Context, nodeID int, termIDs []int) error
	// FieldTermIDsForNode - every term the node references through any
	// taxonomy field (field_value_taxonomy ∪ field_value_taxonomy_multi),
	// whatever the field or vocabulary - what taxonomy_index must cover.
	FieldTermIDsForNode(ctx context.Context, nodeID int) ([]int, error)

	// Admin CRUD for taxonomy vocabularies and terms (dictionary management screen).
	Vocabularies(ctx context.Context) (TaxonomyVocabularies, error)
	VocabularyByID(ctx context.Context, id int) (*TaxonomyVocabulary, error)
	CreateVocabulary(ctx context.Context, name, slug, termPathPrefix, desc string, publicTermPages bool, weight, createdBy int) (*TaxonomyVocabulary, error)
	UpdateVocabulary(ctx context.Context, id int, name, slug, termPathPrefix, desc string, publicTermPages bool, weight int) (*TaxonomyVocabulary, error)
	// UpdateVocabularySortOrder updates only Weight (drag-and-drop reorder).
	UpdateVocabularySortOrder(ctx context.Context, id int, weight int) error
	DeleteVocabulary(ctx context.Context, id int) error

	TermByID(ctx context.Context, id int) (*TaxonomyTerm, error)
	// TermsByIDs is TermByID batched over many term IDs in one query. Unknown
	// IDs are absent from the map, not an error.
	TermsByIDs(ctx context.Context, ids []int) (map[int]TaxonomyTerm, error)
	CreateTermFull(ctx context.Context, vocabularyID int, name, slug, desc string, weight, parentID, createdBy int) (*TaxonomyTerm, error)
	UpdateTerm(ctx context.Context, id int, name, slug, desc string, weight, parentID int) (*TaxonomyTerm, error)
	UpdateTermPageTitle(ctx context.Context, id int, pageTitle string) error
	// UpdateTermSortOrder updates only Weight/ParentID (drag-and-drop reorder).
	UpdateTermSortOrder(ctx context.Context, id int, weight, parentID int) error
	DeleteTerm(ctx context.Context, id int) error
}

TaxonomyRepository - storage port for the vocabularies, their terms and the nodes' terms.

type TaxonomyTerm

type TaxonomyTerm struct {
	ID         int
	Vocabulary TaxonomyVocabulary
	Name       string
	Desc       string
	// PageTitle - the term page's heading and [term:title] SEO token
	// (per-term meta title); empty - Name.
	PageTitle string
	Weight    int
	Slug      string
	ParentID  int
	CreatedBy User
	CreatedAt time.Time
	UpdatedAt time.Time
}

TaxonomyTerm - a term of a vocabulary, under another (ParentID; 0 - a root term).

func LocalizeTerm

func LocalizeTerm(lang string, term TaxonomyTerm) TaxonomyTerm

LocalizeTerm - term in lang: its name and description translated (TranslatedText); with its name translated, its page title - the translated name (the page title is one, in the default language).

func (TaxonomyTerm) HasPublicPage

func (t TaxonomyTerm) HasPublicPage() bool

HasPublicPage - the term has a public page at "/<Slug>": its vocabulary has PublicTermPages on. Templates link a term only then (else the link is a 404). Needs Vocabulary loaded with the term, as the repository's term queries do.

type TaxonomyTerms

type TaxonomyTerms []TaxonomyTerm

TaxonomyTerms - a list of terms.

func (TaxonomyTerms) BuildDepths

func (ts TaxonomyTerms) BuildDepths() map[int]int

BuildDepths returns each term's nesting depth (0 = root), e.g. for drag-and-drop indentation in the terms admin.

func (TaxonomyTerms) BuildHierarchy

func (ts TaxonomyTerms) BuildHierarchy() map[int]string

BuildHierarchy creates a map of terms with their display names including parent hierarchy

func (TaxonomyTerms) FilterByVID

func (ts TaxonomyTerms) FilterByVID(vID int) TaxonomyTerms

FilterByVID - the terms of vocabulary vID.

func (TaxonomyTerms) IDs

func (ts TaxonomyTerms) IDs() []int

IDs - the terms' IDs, in order.

func (TaxonomyTerms) SortByHierarchy

func (ts TaxonomyTerms) SortByHierarchy() TaxonomyTerms

SortByHierarchy sorts terms by parent-child relationship

type TaxonomyVocabularies

type TaxonomyVocabularies []TaxonomyVocabulary

TaxonomyVocabularies - a list of vocabularies.

type TaxonomyVocabulary

type TaxonomyVocabulary struct {
	ID     int
	Name   string
	Desc   string
	Weight int
	Slug   string
	// TermPathPrefix - first part of the URL of this vocabulary's new
	// terms ("tags" → /tags/<term>), the terms' path pattern;
	// empty = derived from the vocabulary name. See
	// TaxonomyService.GenerateTermSlug.
	TermPathPrefix string
	// PublicTermPages - this vocabulary's terms have public pages at
	// their URL (/<term slug>, TaxonomyController.TermPageFallback);
	// off - the URL is 404 (a vocabulary used only for classification).
	PublicTermPages bool
	CreatedBy       User
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

TaxonomyVocabulary - a vocabulary: a named set of terms (tags, rubrics) content is classified by.

type TeaserItem

type TeaserItem struct {
	Node Node
	// TypeLabel - the content type's label (content_types.label).
	TypeLabel string
	// Fields - text/number/date/bool field values by machine_name.
	Fields map[string]any
	// Labels - field instance labels by machine_name.
	Labels map[string]string
	// Terms - taxonomy field terms by machine_name.
	Terms        map[string]TaxonomyTerms
	CommentCount int
	// Images - image field files by machine_name.
	Images map[string]File
	// DefaultImages - the default image (FieldInstanceDef.DefaultImageID)
	// of each image field the node leaves empty, by machine_name.
	DefaultImages map[string]File
	// AltTitle - the alternative title: the value of the type's
	// AltTitleField ("" - none).
	AltTitle string
	// BodyField - machine_name of the type's body text field (the first one
	// shown in the detail page body), "" when none.
	BodyField string
	// ImageField/ImageStyle - the type's first image field (its
	// machine_name, "" when none) and that field's list image style
	// ("" - the original): the engine's default teaser picture.
	ImageField string
	ImageStyle string
	// DateFormats - the chosen date format machine name per date field, by
	// machine_name; a theme teaser passes it to fieldDate.
	DateFormats map[string]string
}

TeaserItem - one material rendered as a teaser card. The theme template teaser/<type>.html (fallback teaser/default.html) gets the node plus its field values keyed by machine_name, so card markup lives in the theme.

func (TeaserItem) Body

func (t TeaserItem) Body() string

Body - the body text field's value (the RSS description, the [node:summary] source).

func (TeaserItem) Image

func (t TeaserItem) Image(machineName string) File

Image - an image field's file, else the field's default image (zero value - neither).

func (TeaserItem) MainImage

func (t TeaserItem) MainImage() File

MainImage - Image of the ImageField.

func (TeaserItem) OwnImage

func (t TeaserItem) OwnImage(machineName string) File

OwnImage - the node's own file of an image field, never the default image (feeds: no placeholder pictures in enclosures).

func (TeaserItem) Text

func (t TeaserItem) Text(machineName string) string

Text - a text field's value ("" when absent).

type TextFormatDef

type TextFormatDef struct {
	ID          int
	MachineName string
	Label       string
	// Weight - order in the format dropdown (lower first) and fallback priority:
	// when a value has no selected format, or the selected one is no longer
	// allowed for the user, the lowest-weight format allowed for the field wins
	// (see resolveTextFormat). Give the richest format the lowest weight,
	// otherwise rich content falls back to a plain textarea.
	Weight int
	// AllowedTags - space-separated HTML tags SanitizeWithFormat (pkg/htmlsanitize)
	// keeps. Empty means plain text: all markup is stripped. "script"/"style" keep
	// their raw content unescaped (see AllowUnsafeContent). "iframe" allows embeds
	// with https src and player attributes only. The <!--break--> marker is kept
	// in every format except plain text.
	AllowedTags string
	// AllowClassAttribute - allow the class attribute on kept tags (a per-format
	// equivalent of htmlsanitize.SanitizeAdmin's AllowStyling()).
	AllowClassAttribute bool
	// HasRichEditor - whether the format has a visual editor (TinyMCE). Fields
	// using formats always render a plain textarea; JS attaches or detaches
	// TinyMCE based on the currently selected format (node/edit_scripts.html).
	HasRichEditor bool
	// TinyMCEPlugins/TinyMCEToolbar - editor config for this format, applied by JS
	// when the format is selected. Empty means the default toolbar is kept.
	TinyMCEPlugins string
	TinyMCEToolbar string
	// AllowedExtensions/MaxFileSizeBytes - TinyMCE file manager upload policy for
	// this format, independent of site-wide UploadSettings. Empty/0 means unset;
	// see ResolveTextFormatUploadPolicy for the fallback.
	AllowedExtensions string
	MaxFileSizeBytes  int
	// Status - 1 = selectable for new values, 0 = hidden. Existing values keep
	// rendering and editing with it.
	Status int
	// Filters - the modules' text filters on for the format (their names,
	// space-separated; service.RegisterTextFilter): they process a value of
	// the format when it's shown, the stored HTML stays as saved.
	Filters   string
	CreatedBy int
	CreatedAt time.Time
	UpdatedAt time.Time
}

TextFormatDef - an admin-editable text format: a named set of allowed HTML tags plus a TinyMCE toolbar config. The format is chosen per value on each save rather than fixed on the field definition, since the same field may be edited by both regular users and admins.

Deliberate simplification: the allowlist is a flat tag list (AllowedTags) plus one AllowClassAttribute toggle, not per-tag attribute allowlists. Access is granted via role permissions (see AuthService.CanUseTextFormat).

func (TextFormatDef) AllowUnsafeContent

func (f TextFormatDef) AllowUnsafeContent() bool

AllowUnsafeContent reports whether AllowedTags includes "script" or "style" (raw-content passthrough in SanitizeWithFormat). AuthService.CanUseTextFormat requires full_access for such formats regardless of role permissions: this is the security boundary, not optional hardening.

func (TextFormatDef) AllowedExtensionsList

func (f TextFormatDef) AllowedExtensionsList() []string

AllowedExtensionsList parses AllowedExtensions for ResolveTextFormatUploadPolicy.

func (TextFormatDef) FilterNames

func (f TextFormatDef) FilterNames() []string

FilterNames - Filters as a list.

func (TextFormatDef) MaxFileSizeMB

func (f TextFormatDef) MaxFileSizeMB() float64

MaxFileSizeMB - MaxFileSizeBytes in MB, for the admin form's megabyte-denominated input. 0 when unset.

type TextFormatDefs

type TextFormatDefs []TextFormatDef

TextFormatDefs - a list of text formats.

type TextFormatRepository

type TextFormatRepository interface {
	TextFormats(ctx context.Context) (TextFormatDefs, error)
	TextFormatByID(ctx context.Context, id int) (*TextFormatDef, error)
	TextFormatByMachineName(ctx context.Context, machineName string) (*TextFormatDef, error)
	CreateTextFormat(ctx context.Context, f TextFormatDef) (*TextFormatDef, error)
	UpdateTextFormat(ctx context.Context, f TextFormatDef) (*TextFormatDef, error)
	DeleteTextFormat(ctx context.Context, id int) error
}

TextFormatRepository - storage port for text formats.

type ThemeBlock

type ThemeBlock struct {
	Plugin    PluginBlockID     `yaml:"plugin"`
	Settings  map[string]string `yaml:"settings"`
	Title     string            `yaml:"title"`
	ShowTitle bool              `yaml:"show_title"`
	Body      string            `yaml:"body"`
	Region    Region            `yaml:"region"`
	Weight    int               `yaml:"weight"`
}

ThemeBlock - a block a theme comes with (theme.yaml "blocks"): placed when the theme gets its layout for the first time (a new site's theme on install, another theme when first chosen or opened on the Blocks page), after the placements copied from the current theme, unless that layout already has it. Either a plugin block (Plugin: its PluginBlockID, Settings: its PluginConfig) or a custom block (Title and Body, the HTML sanitized as a block saved in the admin); then the site edits or removes it as any other.

func (ThemeBlock) IsCustom

func (b ThemeBlock) IsCustom() bool

IsCustom - a custom block (its Body), not a plugin one.

type ThemeInfo

type ThemeInfo struct {
	Name          string         `yaml:"name"`
	Base          string         `yaml:"base"`
	DefaultRegion Region         `yaml:"default_region"`
	Regions       []ThemeRegion  `yaml:"regions"`
	Settings      []ThemeSetting `yaml:"settings"`
	Stylesheets   []string       `yaml:"stylesheets"`
	// Favicon - the theme's icon, a path on the site ("/static/…"): the
	// site's when Site information has none (service.SiteIconFor); a
	// subtheme without one takes its base's.
	Favicon string `yaml:"favicon"`
	// Blocks - the blocks the theme comes with (ThemeBlock, CheckBlocks);
	// a subtheme without its own takes its base's.
	Blocks []ThemeBlock `yaml:"blocks"`
	// The theme's description for the Appearance page: Description - English,
	// translated by the theme's catalog as Name; Version - its release
	// ("" - the engine's own, released with it); Author, Homepage (its
	// page or repository, http(s)), License (an SPDX identifier, e.g.
	// "MIT"); Tags - lowercase words (dark, two-columns, retro…), also
	// translated; Screenshot - a file in the theme's static directory
	// (themes/<theme>/static/, 3:2, e.g. 1500×1000); MinVersion - the
	// engine release it needs at least ("0.2.0"), the theme can't be
	// previewed or set active on an older one.
	Description string   `yaml:"description"`
	Version     string   `yaml:"version"`
	Author      string   `yaml:"author"`
	Homepage    string   `yaml:"homepage"`
	License     string   `yaml:"license"`
	Tags        []string `yaml:"tags"`
	Screenshot  string   `yaml:"screenshot"`
	MinVersion  string   `yaml:"min_version"`
}

ThemeInfo - the active theme's description (theme.yaml): regions in admin order, the default region for a new block, the theme's settings (ThemeSetting, CheckSettings), a subtheme's base theme (its templates, regions and settings are inherited, paths.ThemeChain) and the stylesheets the theme adds after its base's (css/<name>.css).

func (ThemeInfo) Allows

func (t ThemeInfo) Allows(r Region) bool

Allows reports whether a placement may use the region: a theme region or RegionDisabled.

func (ThemeInfo) CheckBlocks

func (t ThemeInfo) CheckBlocks() error

CheckBlocks validates the theme's blocks: a plugin block or a custom one with a title and a body, in one of the theme's regions.

func (*ThemeInfo) CheckSettings

func (t *ThemeInfo) CheckSettings() error

CheckSettings validates and normalizes the theme's settings: an ID (latin, digits, "_"; unique), a known type, a valid default, options of a select, a CSS variable only of a colour.

func (ThemeInfo) Has

func (t ThemeInfo) Has(r Region) bool

Has reports whether the region belongs to the theme (RegionDisabled does not).

func (ThemeInfo) Labels

func (t ThemeInfo) Labels() map[Region]string

Labels returns labels for the theme's regions and RegionDisabled.

func (ThemeInfo) RegionIDs

func (t ThemeInfo) RegionIDs() []Region

RegionIDs returns the theme's regions in order.

func (ThemeInfo) RegionIDsWithDisabled

func (t ThemeInfo) RegionIDsWithDisabled() []Region

RegionIDsWithDisabled returns the theme's regions followed by RegionDisabled.

func (ThemeInfo) Setting

func (t ThemeInfo) Setting(id string) (ThemeSetting, bool)

Setting - the theme's setting with id, if any.

type ThemeRegion

type ThemeRegion struct {
	ID    Region `yaml:"id"`
	Label string `yaml:"label"`
}

ThemeRegion - a theme region: machine name and admin label.

type ThemeSetting

type ThemeSetting struct {
	ID       string               `yaml:"id"`
	Label    string               `yaml:"label"`
	Type     ThemeSettingType     `yaml:"type"`
	Default  string               `yaml:"default"`
	Options  []ThemeSettingOption `yaml:"options"`
	CSSVar   string               `yaml:"css_var"`
	Selector string               `yaml:"selector"`
	// MaxLength - a text's limit in characters (defaultThemeTextLength
	// when unset).
	MaxLength int `yaml:"max_length"`
}

ThemeSetting - an option a theme offers in its manifest (theme.yaml "settings"), set on the Appearance page: ID - its name in the templates (themeSetting "<id>"), Label - English, translated like the region labels, Default - its value until set. A colour's CSSVar ("--name") is set to it on the theme's pages, in Selector (":root" when empty; e.g. `[data-bs-theme="dark"]` for a dark scheme's colour).

func (ThemeSetting) CSSSelector

func (s ThemeSetting) CSSSelector() string

CSSSelector - where the setting's CSS variable is set.

func (ThemeSetting) Valid

func (s ThemeSetting) Valid(v string) bool

Valid reports whether v is a value of the setting: a "#rrggbb" colour, one of the options, "1" or "0", a line of text within MaxLength.

type ThemeSettingOption

type ThemeSettingOption struct {
	Value string `yaml:"value"`
	Label string `yaml:"label"`
}

ThemeSettingOption - a select setting's choice: its value and English label.

type ThemeSettingType

type ThemeSettingType string

ThemeSettingType - the kind of a theme setting's value.

const (
	// ThemeSettingColor - a colour, "#rrggbb"; with CSSVar it becomes that
	// CSS variable of the theme's pages.
	ThemeSettingColor ThemeSettingType = "color"
	// ThemeSettingSelect - one of the setting's Options (their Value).
	ThemeSettingSelect ThemeSettingType = "select"
	// ThemeSettingBool - on ("1") or off ("0").
	ThemeSettingBool ThemeSettingType = "bool"
	// ThemeSettingText - a line of text of at most MaxLength characters
	// (empty allowed), no line breaks or control characters; for the
	// theme's templates (themeSetting), never a CSS variable.
	ThemeSettingText ThemeSettingType = "text"
)

type ThemeSettingsRepository

type ThemeSettingsRepository interface {
	All(ctx context.Context) (map[string]map[string]string, error)
	Save(ctx context.Context, theme string, values map[string]string) error
}

ThemeSettingsRepository - the themes' stored setting values (theme key, entity.ThemeKey → setting ID → value).

type TitleDisplay

type TitleDisplay string

TitleDisplay - see ContentTypeDef.TitleDisplay.

const (
	// TitleDisplayOriginalWithTranslation - "Title (Translated)".
	TitleDisplayOriginalWithTranslation TitleDisplay = "original_with_translation"
	// TitleDisplayTranslatedFirst - the heading is the translated title,
	// the original goes into a subtitle (the breadcrumb shows the
	// translated one).
	TitleDisplayTranslatedFirst TitleDisplay = "translated_first"
	// TitleDisplayOriginalOnly - just the title.
	TitleDisplayOriginalOnly TitleDisplay = "original_only"
)

type TwoFactor

type TwoFactor struct {
	UserID    int
	Secret    string
	LastStep  int64
	EnabledAt time.Time
	CodesLeft int
}

TwoFactor - a user's two-factor sign-in, while it is on: the authenticator's secret (base32), the last time step a code was accepted for, since when, how many recovery codes are left unused.

type TwoFactorRepository

type TwoFactorRepository interface {
	// ByUser - the user's, nil while it is off.
	ByUser(ctx context.Context, userID int) (*TwoFactor, error)
	// Enable turns it on with secret, the step its confirming code was
	// for and the recovery codes, in place of any earlier ones.
	Enable(ctx context.Context, userID int, secret string, step int64, codeHashes []string, at time.Time) error
	// AcceptStep records a code accepted for step: false - one for this
	// step or a later one was accepted already (a code isn't taken twice).
	AcceptStep(ctx context.Context, userID int, step int64) (bool, error)
	// UseRecoveryCode spends the unused recovery code: false - no such one.
	UseRecoveryCode(ctx context.Context, userID int, codeHash string) (bool, error)
	// ReplaceRecoveryCodes - new recovery codes; the old ones stop working.
	ReplaceRecoveryCodes(ctx context.Context, userID int, codeHashes []string) error
	// Disable turns it off: the secret and the codes are deleted.
	Disable(ctx context.Context, userID int) error
	// EnabledAmong - which of the users have it on.
	EnabledAmong(ctx context.Context, userIDs []int) (map[int]bool, error)
}

TwoFactorRepository - the users' two-factor sign-in and recovery codes (SHA-256 hex of each).

type UnitOfWork

type UnitOfWork interface {
	Do(ctx context.Context, fn func(ctx context.Context) error) error
}

UnitOfWork - a transaction: Do runs fn in one (the repositories called with fn's ctx write in it; in a transaction already - in that one), rolled back when fn fails.

type UploadSettings

type UploadSettings struct {
	MaxFileSizeBytes  int
	MaxImageDimension int
	// AllowedMimeTypes - e.g. []string{"image/jpeg", "image/png"}.
	AllowedMimeTypes []string
	// UserFileExtensions - document extensions (lower case, no dot) users
	// may upload to their own files besides images, e.g. "pdf", "docx".
	UserFileExtensions []string
}

UploadSettings - site-wide upload validation policy (single DB row), applied by FileUploadService.ValidateAndProcess to every upload path. The avatar output size (MaxAvatarDimension) is a fixed constant instead: it is a crop target tied to the layout, not a site policy.

type UploadSettingsRepository

type UploadSettingsRepository interface {
	Get(ctx context.Context) (*UploadSettings, error)
	Update(ctx context.Context, s *UploadSettings) error
}

UploadSettingsRepository persists the single upload-policy row.

type User

type User struct {
	ID       int
	UUID     uuid.UUID
	Username string
	Slug     string
	// Avatar - the uploaded picture as pages show it (its image style's
	// address); empty - none (the templates show avatarPlaceholder).
	Avatar File
	// AvatarStored - the uploaded picture's stored URI (public://…), for
	// removing its file; "" - none.
	AvatarStored string
	Email        string
	PasswordHash string
	// Timezone - the user's IANA time zone, used when per-user time zones
	// are enabled (see sitetime.ForUser); empty means the site's.
	Timezone      string
	Metadata      map[string]any
	Signature     string
	Role          *Role
	RoleID        int // role_id from DB, used when Role edge not loaded
	Status        int // 0=blocked, 1=active, 2=pending admin approval
	EmailVerified bool
	// SessionVersion - the account's sessions carry it; a session with
	// another is over (UserRepository.BumpSessionVersion).
	SessionVersion   int
	AvatarUpdateHint string // "keep" (default), "clear", "set" - for Update
	LastActivity     time.Time
	CreatedAt        time.Time
	UpdatedAt        time.Time
}

User - a site account (a users row): its name, e-mail, password hash, role, status (UserStatus…), picture and profile.

func MemoizedUser

func MemoizedUser(ctx context.Context, id int) (*User, bool)

MemoizedUser - a copy of the user id loaded earlier in ctx's request; false - none (or ctx keeps no users).

type UserAuthTokenRepository

type UserAuthTokenRepository interface {
	// InvalidateUserKind removes unused tokens of a kind for a user (e.g. before issuing a new reset).
	InvalidateUserKind(ctx context.Context, userID int, kind string) error
	Insert(ctx context.Context, userID int, tokenHash, kind string, expiresAt time.Time) error
	// Consume marks the newest matching unused token as used and returns user_id (single-use).
	Consume(ctx context.Context, tokenHash, kind string) (userID int, ok bool, err error)
	// Valid - the user of an unused, unexpired token, which stays unused
	// (a form shown before the token is taken).
	Valid(ctx context.Context, tokenHash, kind string) (userID int, ok bool, err error)
	// Pending - when the newest unused token of kind of each of userIDs
	// expires (an expired one too); a user without one - absent.
	Pending(ctx context.Context, kind string, userIDs []int) (map[int]time.Time, error)
}

UserAuthTokenRepository stores hashed one-time tokens: login links, password resets, e-mail confirmations.

type UserContentRepository

type UserContentRepository interface {
	Summary(ctx context.Context, userID int) (UserContentSummary, error)
	// NodeIDs - IDs of the user's nodes (any type/status), at most limit.
	NodeIDs(ctx context.Context, userID int, limit int) ([]int, error)
	// NodeFileIDs - files attached to these nodes (node files, the modules',
	// file fields). Must be called before the nodes are deleted, while the
	// links still exist.
	NodeFileIDs(ctx context.Context, nodeIDs []int) ([]int, error)
	// FileIDsByCreator - files uploaded by the user.
	FileIDsByCreator(ctx context.Context, userID int) ([]int, error)
	// DeleteUnreferencedFiles deletes the file rows among fileIDs that
	// nothing references any more and returns the URIs safe to remove from
	// disk (no remaining file row points to the same URI).
	DeleteUnreferencedFiles(ctx context.Context, fileIDs []int) ([]string, error)
	// ModuleInstalled - whether the module was installed: a module never
	// installed has no tables, so no content of the user.
	ModuleInstalled(ctx context.Context, module string) (bool, error)
}

UserContentRepository - queries and deletes for everything a user owns that per-entity repositories don't cover. Nodes themselves are deleted via AdminBulkService.DeleteNode so all its cascades apply.

type UserContentSummary

type UserContentSummary struct {
	NodesByType []UserContentTypeCount
	Nodes       int
	Comments    int
	// Modules - the modules' content (UserDeletionService.AddModuleContent).
	Modules []UserModuleContentCount
	Files   int
}

UserContentSummary - what will be deleted along with a user's content; shown on the confirmation page before the deletion.

type UserContentTypeCount

type UserContentTypeCount struct {
	Type  string
	Count int
}

UserContentTypeCount - number of nodes of one type created by a user.

type UserFieldDef

type UserFieldDef struct {
	ID          int
	MachineName string
	Label       string
	MaxLen      int
	Weight      int
	// Required - asked at sign-up (and by the administrator's "add
	// user", and after an OAuth sign-up) and never left empty.
	Required bool
}

UserFieldDef - an admin-defined profile field: a plain text value per user, shown on the profile and edited in the profile form, ordered by Weight.

type UserFieldDefs

type UserFieldDefs []UserFieldDef

UserFieldDefs - a list of profile fields.

func (UserFieldDefs) Sorted

func (fs UserFieldDefs) Sorted() UserFieldDefs

Sorted - by Weight, then ID.

type UserFieldRepository

type UserFieldRepository interface {
	Fields(ctx context.Context) (UserFieldDefs, error)
	CreateField(ctx context.Context, f UserFieldDef) (int, error)
	UpdateField(ctx context.Context, f UserFieldDef) error
	// DeleteField removes the field and every user's value of it.
	DeleteField(ctx context.Context, id int) error
	// Values - field ID → value for one user.
	Values(ctx context.Context, userID int) (map[int]string, error)
	// SetValues stores the user's values: an empty value removes it.
	SetValues(ctx context.Context, userID int, values map[int]string) error
	DeleteUserValues(ctx context.Context, userID int) error
}

UserFieldRepository - storage port for the profile fields and the users' values.

type UserFieldValue

type UserFieldValue struct {
	Field UserFieldDef
	Value string
}

UserFieldValue - a field with one user's value, as the profile and the profile form show it.

type UserFileRef

type UserFileRef struct {
	Source   string `json:"source"`
	EntityID int    `json:"entity_id"`
	Title    string `json:"title"`
	URL      string `json:"url,omitempty"`
}

UserFileRef - a place a file is used, for people: what it is and where to open it (URL empty when there is no page, e.g. a private message).

type UserFileUsage

type UserFileUsage struct {
	Path     string
	Source   string
	EntityID int
}

UserFileUsage - a text (Source + EntityID) that links to a user's file (Path, relative to the files directory: "u42/docs/a.pdf").

type UserFileUsageRepository

type UserFileUsageRepository interface {
	// ScanTextsFor calls fn for every text that mentions path.
	ScanTextsFor(ctx context.Context, path string, fn func(source string, entityID int, text string)) error
	// Describe gives each usage a title and a link.
	Describe(ctx context.Context, usages []UserFileUsage) ([]UserFileRef, error)
}

UserFileUsageRepository finds the texts that link to a user's file.

type UserFilter

type UserFilter struct {
	Email string
}

UserFilter - the user Find looks for: by e-mail address.

type UserModuleContentCount

type UserModuleContentCount struct {
	Label string
	Count int
}

UserModuleContentCount - how much of a module's content a user has: Label - its translation source with @count ("private messages: @count").

type UserOAuthIdentity

type UserOAuthIdentity struct {
	ID             int64
	UserID         int
	Provider       string
	ProviderUserID string
	Email          string
	CreatedAt      time.Time
}

UserOAuthIdentity - a provider's account (ProviderUserID) connected to a user's, with the e-mail the provider gave.

type UserOAuthIdentityRepository

type UserOAuthIdentityRepository interface {
	FindByProviderUser(ctx context.Context, provider, providerUserID string) (*UserOAuthIdentity, error)
	FindByUserAndProvider(ctx context.Context, userID int, provider string) (*UserOAuthIdentity, error)
	// ByUser - the provider accounts connected to the user's.
	ByUser(ctx context.Context, userID int) ([]UserOAuthIdentity, error)
	Create(ctx context.Context, identity UserOAuthIdentity) (*UserOAuthIdentity, error)
	// Delete disconnects the provider's account from the user's (none
	// connected - nothing to do).
	Delete(ctx context.Context, userID int, provider string) error
}

UserOAuthIdentityRepository - storage port for the provider accounts connected to the users'.

type UserRepository

type UserRepository interface {
	Find(ctx context.Context, filter UserFilter) (*User, error)
	// FindByEmailOrUsername loads a user where email or username matches identity (case-insensitive).
	FindByEmailOrUsername(ctx context.Context, identity string) (*User, error)
	ByID(ctx context.Context, id int) (*User, error)
	// ByIDs - the users with these ids, by id (a missing one is absent).
	ByIDs(ctx context.Context, ids []int) (map[int]User, error)
	Create(ctx context.Context, ct User) (*User, error)
	List(ctx context.Context) (*Users, error)
	// ListForAdmin returns users for the admin table, totalCount, effectivePage (after clamping), error.
	ListForAdmin(ctx context.Context, page int, perPage int, opts AdminPeopleListOpts) (*Users, int, int, error)
	Delete(ctx context.Context, id int) error
	Update(ctx context.Context, ct User) (*User, error)
	// Search - users whose username or e-mail contains query (the admin's
	// search).
	Search(ctx context.Context, query string, limit int) (*Users, error)
	// SearchActiveByName - active users whose username contains query
	// (with roles - of one of them): a member's search for another (an
	// e-mail address isn't matched, so it can't tell whether an address
	// has an account).
	SearchActiveByName(ctx context.Context, query string, roles []int, limit int) (*Users, error)
	BySlug(ctx context.Context, slug string) (*User, error)
	FindByUsername(ctx context.Context, username string) (*User, error)
	// ConfirmEmail marks the user's e-mail address confirmed.
	ConfirmEmail(ctx context.Context, userID int) error
	// CountWithStatus returns the number of users with the given status (e.g. UserStatusPending).
	CountWithStatus(ctx context.Context, status int) (int, error)
	// TouchAccessedAtIfStale sets accessed_at (LastActivity) to now only if it is nil or older than minInterval; does not change updated_at.
	TouchAccessedAtIfStale(ctx context.Context, userID int, minInterval time.Duration) error
	// SessionStateByID returns only users.status and session_version (the
	// per-request check of a session); ErrEntityNotFound if the user does
	// not exist.
	SessionStateByID(ctx context.Context, id int) (status, sessionVersion int, err error)
	// BumpSessionVersion raises the user's session version, ending every
	// session of the account; the new version.
	BumpSessionVersion(ctx context.Context, id int) (int, error)
}

UserRepository - storage port for the users.

type Users

type Users []User

Users - a list of users.

type View

type View struct {
	ID          int
	MachineName string
	Label       string
	CreatedBy   int
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

View - the container of ViewDisplayDefs: one "Default" display (never rendered, the shared baseline) plus any number of real displays, each inheriting or overriding Settings/Filters/Sort/Fields from Default per section. Label is admin-facing only. Created only by views.DefaultService.CloneDisplay.

type ViewBaseEntity

type ViewBaseEntity string

ViewBaseEntity - the base table a display's Filters/Sort/Fields/RunView target. Immutable once the display is created, like MachineName. "content" (nodes) is the zero value/default; "comment" lists comments via ViewQuery.RunCommentView - a configurable counterpart to the fixed PluginBlockLastComments block.

const (
	ViewBaseEntityContent ViewBaseEntity = "content"
	ViewBaseEntityComment ViewBaseEntity = "comment"
)

The base entities a display lists: content (nodes), comments.

type ViewDisplayDef

type ViewDisplayDef struct {
	ID int
	// BaseEntity - see ViewBaseEntity.
	BaseEntity ViewBaseEntity
	// ViewID - the owning View; nil for a display that has never been
	// cloned. Set by CloneDisplay.
	ViewID *int
	// IsDefault - true for the View's shared baseline display, which is
	// never rendered itself and is hidden from the admin views list.
	// Only views.DefaultService.CloneDisplay creates one.
	IsDefault bool
	// OverrideSettings/Filters/Sort/Fields - per-section "Override"/"Use
	// default" state. false = views.DefaultService's Effective* methods
	// resolve the section from the View's Default. Meaningless when
	// ViewID is nil or IsDefault is true.
	OverrideSettings bool
	OverrideFilters  bool
	OverrideSort     bool
	OverrideFields   bool
	MachineName      string
	Label            string
	// MetaTitle/MetaDescription - SEO fields for page displays. Empty
	// MetaTitle falls back to Label.
	MetaTitle       string
	MetaDescription string
	// URLPath - the page display's own path (no leading "/"), resolved
	// by a catch-all fallback. Unused for
	// non-page displays.
	URLPath string
	// DisplayType - see ViewDisplayType.
	DisplayType ViewDisplayType
	// AttachContentTypes/AttachWeight/AttachTitle/AttachShowTitle - for
	// attachment displays: comma-separated content types whose node page
	// shows this display between the article and its comments, ordered
	// by AttachWeight; AttachTitle is the public heading (empty = Label).
	// Structural placement: never inherited from Default nor snapshotted.
	AttachContentTypes string
	AttachWeight       int
	AttachTitle        string
	AttachShowTitle    bool
	// TermVocabularies - for term displays: comma-separated vocabulary
	// IDs whose term pages use this display (empty = every vocabulary).
	// Among several matches the lowest AttachWeight wins. Structural -
	// never inherited nor snapshotted.
	TermVocabularies string
	// ProfileTabPath/ProfileTabAccess - for user_tab displays: the tab's
	// path segment under a profile (/users/<alias>/<path>, /me/<path>)
	// and who sees it. The tab label is Label, its order AttachWeight.
	// Structural - never inherited nor snapshotted.
	ProfileTabPath   string
	ProfileTabAccess ViewProfileTabAccess
	// ThemeTemplate - a theme template (views/<ThemeTemplate>.html
	// defining "view_<ThemeTemplate>") that renders the list instead of
	// the generic display style. Empty = DisplayStyle. Structural -
	// never inherited nor snapshotted.
	ThemeTemplate string
	// DisplayStyle - grid (cards in N columns), list (one plain row per
	// item), table (columns from ViewFieldDefs) or carousel. Same values
	// for both base entities.
	DisplayStyle ViewDisplayStyle
	// GridColumns - column count for the grid style.
	GridColumns int
	// OverflowAfter - 0 renders every item in DisplayStyle. >0 renders
	// only the first OverflowAfter items that way and the rest as a
	// compact list below (title plus fields not excluded or marked
	// ViewFieldDef.HideInOverflow). Works with any style, so "N full
	// cards + a plain list of the rest" needs one display, not two.
	OverflowAfter int
	// CarouselSlidesPerView/Autoplay/Loop/ShowNavigation/ShowPagination -
	// carousel style settings, part of the Settings bundle.
	CarouselSlidesPerView  int
	CarouselAutoplay       bool
	CarouselLoop           bool
	CarouselShowNavigation bool
	CarouselShowPagination bool
	// CarouselLinkFieldStorageID - when set, each carousel slide is
	// wrapped in a link to this text field's value; nil = no wrapping
	// link. Restricted to FieldTypeText at the service layer.
	CarouselLinkFieldStorageID *int
	// CarouselEffect - Swiper transition: "slide" (default) or "fade".
	CarouselEffect string
	ShowPagination bool
	// PaginationAjax - with ShowPagination, pager links fetch the next
	// page and swap #view-list-container's content instead of navigating
	// (see initViewPagination in web/static/js/app.js). Default false:
	// plain ?page=N links that work without JS.
	PaginationAjax bool
	// ShowGlossary - renders a letter-index bar above the list. RunView
	// then synthesizes (never persists) a starts_with filter from
	// ?letter=X - see service.glossaryLetterFilter.
	ShowGlossary bool
	// GlossaryFieldStorageID - the text field the glossary groups by;
	// nil = the node title. Restricted to FieldTypeText at the service
	// layer (views.GlossaryFieldType).
	GlossaryFieldStorageID *int
	PageSize               int
	// HeaderText/FooterText - rich text rendered before/after the list.
	// Part of the Settings bundle. Sanitized on save, rendered unescaped
	// (trusted admin HTML).
	HeaderText string
	FooterText string
	// OverflowHeaderText - plain-text heading shown above the compact
	// overflow list (see OverflowAfter), only when that list is
	// non-empty. Empty = no heading.
	OverflowHeaderText string
	// CustomCSS - raw CSS rendered as an inline <style> on the display's
	// page. Not namespaced: #view-list-container is shared by every View
	// page, so admins must scope their own selectors.
	CustomCSS string
	// RowTemplate - row (card) markup for grid/list/carousel displays:
	// HTML with {{field:<machine_name>}} tokens (the field's rendered
	// output, empty when the item has no value) and {{url}} (the item's
	// path). Empty = fields rendered one after another. Settings bundle.
	RowTemplate string
	// GroupByField - machine name of one of the display's fields (field
	// storage or builtin like created_at); rows are grouped by its value,
	// one heading per group in order of first appearance
	// (service.groupViewRowsIn). Empty = no grouping.
	// GroupDateFormat - heading format for a date field: "" (the rendered
	// field) or ViewGroupDateYear/Month/Day. Settings bundle.
	GroupByField    string
	GroupDateFormat string
	// PublishedSnapshot/PublishedAt - nil PublishedAt = never published,
	// the page renders live data. Once set, PublishedSnapshot holds a
	// JSON ViewSnapshot (Settings bundle, Label/meta, Filters, Sorts,
	// Fields as of the last publish) that every visitor, admins included,
	// sees; the admin preview shows live state. URLPath/Status/
	// DisplayType/MachineName are not snapshotted and apply immediately
	// (ViewByURLPath resolves by the live column).
	PublishedSnapshot string
	PublishedAt       *time.Time
	Status            int // 1=enabled (resolves on the public side), 0=disabled
	CreatedBy         int
	CreatedAt         time.Time
	UpdatedAt         time.Time
}

ViewDisplayDef - an admin-configured listing display (page, block, attachment, term page or profile tab) inside a View. Content type scoping is just a filter (ViewFilterBuiltinContentType), so a display without one spans every type. A display with nil ViewID is a "lone" display; ViewID/IsDefault/Override* matter only once views.DefaultService.CloneDisplay has grouped it into a View.

func LocalizeView

func LocalizeView(lang string, view ViewDisplayDef) ViewDisplayDef

LocalizeView - view in lang: its title and meta description translated; with its title translated, its meta title - the translated title (the meta title is one, in the default language).

func (ViewDisplayDef) AttachContentTypeList

func (v ViewDisplayDef) AttachContentTypeList() []string

AttachContentTypeList - AttachContentTypes split into machine names.

func (ViewDisplayDef) CanEditFields

func (v ViewDisplayDef) CanEditFields() bool

CanEditFields - whether the fields are the display's own (see CanEditSettings).

func (ViewDisplayDef) CanEditFilters

func (v ViewDisplayDef) CanEditFilters() bool

CanEditFilters - whether the filters are the display's own (see CanEditSettings).

func (ViewDisplayDef) CanEditSettings

func (v ViewDisplayDef) CanEditSettings() bool

CanEditSettings (and CanEditFilters, CanEditSort, CanEditFields) - whether the section is the display's own (no group, the Default itself, or overridden) rather than inherited. Checked by the admin handlers as a defense-in-depth guard and by admin/views/page.html to choose controls vs. the "inherited" banner.

func (ViewDisplayDef) CanEditSort

func (v ViewDisplayDef) CanEditSort() bool

CanEditSort - whether the sort is the display's own (see CanEditSettings).

func (ViewDisplayDef) CarouselLinkFieldStorageIDValue

func (v ViewDisplayDef) CarouselLinkFieldStorageIDValue() int

CarouselLinkFieldStorageIDValue - CarouselLinkFieldStorageID, 0 when nil.

func (ViewDisplayDef) GlossaryFieldStorageIDValue

func (v ViewDisplayDef) GlossaryFieldStorageIDValue() int

GlossaryFieldStorageIDValue - GlossaryFieldStorageID, 0 when nil (for templates).

func (ViewDisplayDef) HasGroup

func (v ViewDisplayDef) HasGroup() bool

HasGroup - whether the display belongs to a View; templates use it to show the display tabs and override banners.

func (ViewDisplayDef) HasPublishedSnapshot

func (v ViewDisplayDef) HasPublishedSnapshot() bool

HasPublishedSnapshot - whether the display has been published at least once (enables the "discard changes" action).

func (ViewDisplayDef) IsComment

func (v ViewDisplayDef) IsComment() bool

IsComment reports whether the display lists comments (its ViewBaseEntity).

func (ViewDisplayDef) MatchesContentType

func (v ViewDisplayDef) MatchesContentType(contentType string) bool

MatchesContentType - whether an attachment display is attached to contentType (same comparison as BlockPlacementDef.MatchesContentType, so the shared visibility_content_types checkbox partial works for both).

func (ViewDisplayDef) MatchesVocabulary

func (v ViewDisplayDef) MatchesVocabulary(vid int) bool

MatchesVocabulary - whether a term display lists terms of vid (an empty TermVocabularies matches every vocabulary).

func (ViewDisplayDef) TermVocabularyIDs

func (v ViewDisplayDef) TermVocabularyIDs() []int

TermVocabularyIDs - TermVocabularies parsed into IDs (invalid entries skipped).

func (ViewDisplayDef) ViewIDValue

func (v ViewDisplayDef) ViewIDValue() int

ViewIDValue - ViewID, 0 for a lone display.

func (ViewDisplayDef) WithSettingsOf

func (display ViewDisplayDef) WithSettingsOf(from ViewDisplayDef) ViewDisplayDef

WithSettingsOf - display with from's Settings bundle (inherited from a View's Default, seeded into a copy): the snapshot's fields but Label/meta, which are the display's own.

type ViewDisplayDefs

type ViewDisplayDefs []ViewDisplayDef

ViewDisplayDefs - a list of View displays.

type ViewDisplayStyle

type ViewDisplayStyle string

ViewDisplayStyle - see ViewDisplayDef.DisplayStyle's doc comment.

const (
	ViewDisplayStyleGrid  ViewDisplayStyle = "grid"
	ViewDisplayStyleList  ViewDisplayStyle = "list"
	ViewDisplayStyleTable ViewDisplayStyle = "table"
	// ViewDisplayStyleCarousel - a Swiper carousel, one slide per item;
	// configured by ViewDisplayDef.Carousel*.
	ViewDisplayStyleCarousel ViewDisplayStyle = "carousel"
)

The display styles: a grid of cards, a list, a table, a carousel.

type ViewDisplayType

type ViewDisplayType string

ViewDisplayType - where a display renders: "page" has its own URL (URLPath); "block" and the others have no URL and render inside other pages.

const (
	ViewDisplayTypePage  ViewDisplayType = "page"
	ViewDisplayTypeBlock ViewDisplayType = "block"
	// ViewDisplayTypeAttachment - attached to node detail pages of
	// AttachContentTypes (see ViewDisplayDef.AttachContentTypes).
	ViewDisplayTypeAttachment ViewDisplayType = "attachment"
	// ViewDisplayTypeTerm - lists a taxonomy term's materials on the
	// term's own page (see ViewDisplayDef.TermVocabularies); the term
	// comes from the URL as the has_current_term contextual filter.
	ViewDisplayTypeTerm ViewDisplayType = "term"
	// ViewDisplayTypeUserTab - a tab of the user profile listing that
	// user's materials (see ViewDisplayDef.ProfileTabPath); the user
	// comes from the URL as the created_by contextual filter.
	ViewDisplayTypeUserTab ViewDisplayType = "user_tab"
)

The display types (ViewDisplayType).

func (ViewDisplayType) HasURL

func (t ViewDisplayType) HasURL() bool

HasURL - only a page display owns a URL path; block, attachment, term and user_tab displays are rendered inside other pages.

type ViewFieldBuiltinField

type ViewFieldBuiltinField string

ViewFieldBuiltinField - a ViewFieldDef target that isn't a generic field (node title and other node properties; pictures are ordinary image fields). views.BuildContentFieldInstances synthesizes them from the node itself, so they get label, CSS class and position like any other field.

const (
	ViewFieldBuiltinTitle ViewFieldBuiltinField = "title"
	// ViewFieldBuiltinContentType - the node's content type label
	// (ContentTypeDef.Label), resolved once per render, not per node.
	ViewFieldBuiltinContentType ViewFieldBuiltinField = "content_type"
	// ViewFieldBuiltinCreatedAt - the node's CreatedAt, rendered as a
	// date field.
	ViewFieldBuiltinCreatedAt ViewFieldBuiltinField = "created_at"
	// ViewFieldBuiltinViewCount - the node's total view counter, rendered
	// as a number.
	ViewFieldBuiltinViewCount ViewFieldBuiltinField = "view_count"
	// ViewFieldBuiltinCommentCount - the node's published comment count
	// (batched via CommentsService.CountByNodeIDs), rendered as a number.
	ViewFieldBuiltinCommentCount ViewFieldBuiltinField = "comment_count"
	// ViewFieldBuiltinAuthor - the node's author's name, linking their
	// profile.
	ViewFieldBuiltinAuthor ViewFieldBuiltinField = "author"
	// ViewFieldBuiltinLink - a link to the node, its text the field's
	// label ("Read more" when empty).
	ViewFieldBuiltinLink ViewFieldBuiltinField = "link"

	// Comment base entity builtins.
	ViewFieldBuiltinCommentSubject   ViewFieldBuiltinField = "comment_subject"
	ViewFieldBuiltinCommentContent   ViewFieldBuiltinField = "comment_content"
	ViewFieldBuiltinCommentAuthor    ViewFieldBuiltinField = "comment_author"
	ViewFieldBuiltinCommentCreatedAt ViewFieldBuiltinField = "comment_created_at"
	// ViewFieldBuiltinCommentNodeTitle - the parent node's title.
	ViewFieldBuiltinCommentNodeTitle ViewFieldBuiltinField = "comment_node_title"
)

The built-in View fields: the node's, then the comment base entity's.

func (ViewFieldBuiltinField) IsDate

func (b ViewFieldBuiltinField) IsDate() bool

IsDate - the builtin is a date (a date format applies to it).

type ViewFieldDef

type ViewFieldDef struct {
	ID            int
	ViewDisplayID int
	// FieldStorageID nil means this field reads BuiltinField.
	FieldStorageID *int
	// BuiltinField - see ViewFieldBuiltinField. Used only when
	// FieldStorageID is nil.
	BuiltinField ViewFieldBuiltinField
	// Label - the field's label in this View (field storages are global
	// and carry no label). Empty falls back at render time
	// (views.BuildContentFieldInstances) to the first attached content
	// type's instance label, then to the machine name; builtins fall back
	// to their fixed name. Never stored as a default.
	Label     string
	ShowLabel bool
	// ImageStyle - image fields only: the ImageStyleDef.Name to render
	// with, like FieldInstanceDef.ListImageStyle.
	ImageStyle string
	// DateFormat - date fields and date builtins only: the date format
	// machine name; empty = the field instance's DateFormat, else the
	// default format.
	DateFormat string
	// TagFormat - taxonomy fields only, see ViewTagFormat. Empty behaves
	// as ViewTagFormatPlain.
	TagFormat ViewTagFormat
	// ImageDisplay - image fields only, see ViewImageDisplay.
	ImageDisplay ViewImageDisplay
	// Formatter, Layout - link fields only: the FieldFormatter showing
	// the field ("" - links) and how its several values show, like
	// FieldInstanceDef.DetailFormatter/DetailLayout.
	Formatter string
	Layout    FieldLayout
	// LinkTo - see ViewFieldLinkTarget. List items have no automatic
	// link, so a field must opt in for the item to be clickable.
	LinkTo ViewFieldLinkTarget
	// CSSClass - extra class on the field's wrapper (card / table cell),
	// alongside the default item-field-{FieldType} class.
	CSSClass string
	// RewriteHTML - admin HTML wrapping the field's rendered value via a
	// literal "{{value}}" token, substituted by plain string replace -
	// never parsed as a Go template. Sanitized via
	// htmlsanitize.SanitizeAdmin on save.
	RewriteHTML string
	// TrimLength - a text field (a content or a comment View): when >0,
	// the value as plain text (tags stripped, blocks apart) cut to this
	// many characters at a word (service.PlainExcerpt; stripping avoids
	// broken, dangling markup). 0 = show as-is.
	TrimLength int
	// SortOrder - the field's column/card position.
	SortOrder int
	// ExcludeFromDisplay - the value is still resolved (usable as a
	// {{field:<key>}} token in another field's RewriteHTML, see
	// rewriteFieldValue) but the field renders no slot of its own, e.g.
	// a badge overlaid inside another field.
	ExcludeFromDisplay bool
	// HideInOverflow - with ViewDisplayDef.OverflowAfter > 0: rendered in
	// the full items but skipped in the compact overflow list (e.g. an
	// image). Unlike ExcludeFromDisplay, which hides it everywhere.
	HideInOverflow bool
	// FallbackFieldKey - when this field's value is empty for a row, the
	// value of another field in the same row is used instead
	// (ApplyFieldFallbacks). Same key namespace as RewriteHTML's
	// {{field:<key>}} tokens: a field storage machine name or a builtin
	// key.
	FallbackFieldKey string
	// Params - a module's field's settings in this View
	// (ViewModuleField.Params); nil for the others.
	Params    map[string]string `json:"Params,omitempty"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

ViewFieldDef - one field shown by a ViewDisplayDef (independent of filters). Either FieldStorageID (a generic field) or BuiltinField is set. The list template renders only these fields, so even the title must be added here to appear.

func (ViewFieldDef) FieldStorageIDValue

func (f ViewFieldDef) FieldStorageIDValue() int

FieldStorageIDValue - FieldStorageID, 0 when the field is a builtin.

type ViewFieldDefs

type ViewFieldDefs []ViewFieldDef

ViewFieldDefs - a list of a display's fields.

func (ViewFieldDefs) SortBySortOrder

func (fs ViewFieldDefs) SortBySortOrder() ViewFieldDefs

SortBySortOrder - see ViewFilterDefs.SortBySortOrder.

type ViewFieldLinkTarget

type ViewFieldLinkTarget string

ViewFieldLinkTarget - what a field's rendered value links to: nothing, the item ("content", any field type) or the original unstyled image ("file", image fields only - enforced in resolveViewFieldTarget).

const (
	ViewFieldLinkNone    ViewFieldLinkTarget = ""
	ViewFieldLinkContent ViewFieldLinkTarget = "content"
	ViewFieldLinkFile    ViewFieldLinkTarget = "file"
)

The fields' link targets (ViewFieldLinkTarget).

type ViewFilterBuiltinField

type ViewFilterBuiltinField string

ViewFilterBuiltinField - built-in columns (or pseudo-columns) a ViewFilterDef targets when FieldStorageID is nil.

const (
	ViewFilterBuiltinStatus       ViewFilterBuiltinField = "status"
	ViewFilterBuiltinOnModeration ViewFilterBuiltinField = "on_moderation"
	// ViewFilterBuiltinPromote / ViewFilterBuiltinSticky - Node.Promote
	// ("on the front page") and Node.Sticky; Value "1" or "0".
	ViewFilterBuiltinPromote   ViewFilterBuiltinField = "promote"
	ViewFilterBuiltinSticky    ViewFilterBuiltinField = "sticky"
	ViewFilterBuiltinCreatedBy ViewFilterBuiltinField = "created_by"
	ViewFilterBuiltinTitle     ViewFilterBuiltinField = "title"
	// ViewFilterBuiltinContentType - the node's type. Value is a content
	// type machine name (eq) or a comma-separated list (in). The only
	// way to scope a display to specific content types.
	ViewFilterBuiltinContentType ViewFilterBuiltinField = "content_type"
	// ViewFilterBuiltinSimilarToCurrentNode - Contextual builtin: the
	// published nodes sharing taxonomy terms with the current node, ranked
	// live (via taxonomy_index) by those terms weighted by rarity - the
	// fewer nodes have a term, the more it counts. Value - optional
	// vocabulary ID to compare only its terms; empty = every vocabulary.
	// Spans every type unless combined with a content_type filter; the
	// ranking replaces the View's order, its sort criteria break ties.
	ViewFilterBuiltinSimilarToCurrentNode ViewFilterBuiltinField = "similar_to_current_node"
	// ViewFilterBuiltinSharesTermsWithCurrentNode - Contextual builtin:
	// nodes sharing at least one taxonomy term with the current node (live,
	// via taxonomy_index). Value - optional vocabulary ID to restrict to;
	// empty = any vocabulary.
	ViewFilterBuiltinSharesTermsWithCurrentNode ViewFilterBuiltinField = "shares_terms_with_current"
	// ViewFilterBuiltinHasCurrentTerm - Contextual builtin for term
	// displays: nodes indexed under the term being rendered
	// (ViewRunParams.ContextTermID). No term in context = empty result.
	ViewFilterBuiltinHasCurrentTerm ViewFilterBuiltinField = "has_current_term"

	// Comment base entity builtins, mirroring the content ones where a
	// comment analog exists.
	ViewFilterBuiltinCommentStatus    ViewFilterBuiltinField = "comment_status"
	ViewFilterBuiltinCommentSubject   ViewFilterBuiltinField = "comment_subject"
	ViewFilterBuiltinCommentContent   ViewFilterBuiltinField = "comment_content"
	ViewFilterBuiltinCommentCreatedBy ViewFilterBuiltinField = "comment_created_by"
	// ViewFilterBuiltinCommentNodeType - the parent node's type; same
	// Value/operator convention as ViewFilterBuiltinContentType.
	ViewFilterBuiltinCommentNodeType ViewFilterBuiltinField = "comment_node_type"
	// ViewFilterBuiltinCommentIsReply - whether the comment is a reply
	// (ParentID set). Operator eq only, Value "0"/"1".
	ViewFilterBuiltinCommentIsReply ViewFilterBuiltinField = "comment_is_reply"
)

The built-in filter targets: the node's, then the comment base entity's.

type ViewFilterDef

type ViewFilterDef struct {
	ID int
	// ViewDisplayID - the owning ViewDisplayDef.ID.
	ViewDisplayID int
	// FieldStorageID nil means this filter reads BuiltinField instead
	// of a generic field.
	FieldStorageID *int
	// ViaFieldStorageID - a blocks field (FieldTypeBlocks): FieldStorageID
	// is a field of its blocks' sets, and the filter keeps the nodes with
	// a block that matches; nil - the node's own field.
	ViaFieldStorageID *int
	BuiltinField      ViewFilterBuiltinField
	Operator          ViewFilterOperator
	// Value - the fixed filter value, used only when Exposed==false.
	Value string
	// ValueIsRelative - date fields only: Value is a relative expression
	// ("now", "+7 days", "-1 month") resolved against today on every
	// query (see ParseRelativeDate) instead of a literal "2006-01-02"
	// date. Not used for exposed filters.
	ValueIsRelative bool
	Exposed         bool
	// ExposedParam - the query parameter read when Exposed==true (e.g.
	// "category" for ?category=foo).
	ExposedParam string
	// ExposedLabel - the filter's label on the public exposed-filters
	// form. Empty falls back at render time (buildExposedFilterFields) to
	// the target field's label; never stored as a default.
	ExposedLabel string
	// Contextual - the value comes from the current page instead of
	// Value/ExposedParam. Valid only for the created_by builtin, the
	// *_current builtins and reference fields with the *Current
	// operators (enforced in views.DefaultService.validateFilter); resolved
	// from ViewRunParams.Context*. Where no context exists (a page View, a
	// cache-time block render) the filter yields an empty result, not an
	// unfiltered one - see RunView.
	Contextual bool
	// SortOrder - position in the admin filter list and the public
	// exposed-filters form.
	SortOrder int
	CreatedAt time.Time
	UpdatedAt time.Time
}

ViewFilterDef - one filter criterion of a ViewDisplayDef. Its value comes from exactly one source: fixed (Value), exposed (ExposedParam, read from the query string) or contextual (the current page).

func (ViewFilterDef) FieldStorageIDValue

func (f ViewFilterDef) FieldStorageIDValue() int

FieldStorageIDValue - FieldStorageID, 0 when the filter targets a builtin.

func (ViewFilterDef) Target

func (f ViewFilterDef) Target() string

Target - the filter's target as the admin's picker names it: "field:<storage>", "block:<blocks field>:<storage>" (ViaFieldStorageID) or "builtin:<name>".

func (ViewFilterDef) ViaFieldStorageIDValue

func (f ViewFilterDef) ViaFieldStorageIDValue() int

ViaFieldStorageIDValue - ViaFieldStorageID, 0 for nil (templates).

type ViewFilterDefs

type ViewFilterDefs []ViewFilterDef

ViewFilterDefs - a list of a display's filters.

func (ViewFilterDefs) HasContextual

func (fs ViewFilterDefs) HasContextual() bool

HasContextual reports whether any filter is Contextual. Such View-blocks can't be pre-rendered by CacheService and need a live per-request render.

func (ViewFilterDefs) SortBySortOrder

func (fs ViewFilterDefs) SortBySortOrder() ViewFilterDefs

SortBySortOrder returns a copy sorted by SortOrder, ties broken by ID so equal SortOrders keep a deterministic order.

type ViewFilterOperator

type ViewFilterOperator string

ViewFilterOperator - the comparison a ViewFilterDef applies. The allowed subset depends on the target field's type (or builtin).

const (
	ViewFilterOperatorEq ViewFilterOperator = "eq"
	ViewFilterOperatorIn ViewFilterOperator = "in"
	// ViewFilterOperatorNotIn - "has none of these values" (same
	// comma-separated Value as In). Nodes with no value also match.
	ViewFilterOperatorNotIn    ViewFilterOperator = "not_in"
	ViewFilterOperatorContains ViewFilterOperator = "contains"
	ViewFilterOperatorGte      ViewFilterOperator = "gte"
	ViewFilterOperatorLte      ViewFilterOperator = "lte"
	// ViewFilterOperatorEmpty/NotEmpty - the generic field has no value /
	// has a value; no Value needed. Not offered for builtins, which
	// always have a value (see service.validOperatorsForBuiltin).
	ViewFilterOperatorEmpty    ViewFilterOperator = "empty"
	ViewFilterOperatorNotEmpty ViewFilterOperator = "not_empty"
	// ViewFilterOperatorOngoing/NotEnded/Ended - a date field's value is
	// going on now / hasn't ended (going on or to come) / has ended, by
	// DateValue.Ended and Ongoing (a date without a time - by the site's
	// today); a field with several dates - any of them going on or not
	// ended, all of them ended. No Value needed.
	ViewFilterOperatorOngoing  ViewFilterOperator = "ongoing"
	ViewFilterOperatorNotEnded ViewFilterOperator = "not_ended"
	ViewFilterOperatorEnded    ViewFilterOperator = "ended"
	// ViewFilterOperatorStartsWith - case-insensitive prefix match backing
	// the glossary letter filter (ViewDisplayDef.ShowGlossary). Not
	// selectable in the admin UI: only service.glossaryLetterFilter
	// builds it, bypassing validateFilter.
	ViewFilterOperatorStartsWith ViewFilterOperator = "starts_with"
	// ViewFilterOperatorReferencedByCurrent/RelatedToCurrent - only for a
	// Contextual filter on a FieldTypeReference field: nodes the current
	// node references via that field; RelatedToCurrent also includes
	// nodes referencing the current one via the same field (a symmetric
	// relation editable from either side).
	ViewFilterOperatorReferencedByCurrent ViewFilterOperator = "referenced_by_current"
	ViewFilterOperatorRelatedToCurrent    ViewFilterOperator = "related_to_current"
	// ViewFilterOperatorIsProfileUser - only for a Contextual filter on a
	// FieldTypeUser field: nodes naming the user of the page (a profile
	// tab's user, the user of a %-address View) in that field.
	ViewFilterOperatorIsProfileUser ViewFilterOperator = "is_profile_user"
)

The filter operators (ViewFilterOperator).

func (ViewFilterOperator) IsDateState

func (o ViewFilterOperator) IsDateState() bool

IsDateState - o is one of the date state operators (ongoing, not ended, ended): it takes no value.

type ViewImageDisplay

type ViewImageDisplay string

ViewImageDisplay - which images of an image field a View shows: the first (ViewImageFirst, "") or all of a field with several (ViewImageAll).

const (
	ViewImageFirst ViewImageDisplay = ""
	ViewImageAll   ViewImageDisplay = "all"
)

The image fields' displays (ViewImageDisplay).

type ViewModuleField

type ViewModuleField struct {
	Module string
	Key    string
	Label  string
	Params []ViewModuleParam
	// Render - each node's markup among ids by the View field's params; a
	// node left out shows nothing.
	Render func(ctx context.Context, ids []int, params map[string]string) (map[int]template.HTML, error)
}

ViewModuleField - a value a module shows in a content View's rows.

type ViewModuleFilter

type ViewModuleFilter struct {
	Module string
	Key    string
	Label  string
	// Values - the nodes' values among ids; a node left out has none
	// (the "empty" operator matches it, the others don't).
	Values func(ctx context.Context, ids []int) (map[int]float64, error)
	// Options - the values to choose from (a choice filter); Choices -
	// the nodes' values among ids, a node left out has none.
	Options func(ctx context.Context) ([]ViewModuleOption, error)
	Choices func(ctx context.Context, ids []int) (map[int]string, error)
}

ViewModuleFilter - a number a module lets content Views filter by (ViewModuleFilterOperators); with Options - one of a list instead (ViewModuleChoiceOperators: the value is one, or several comma-separated), the nodes' values from Choices.

func (ViewModuleFilter) Choice

func (f ViewModuleFilter) Choice() bool

Choice - the filter is one of a list (Options), not a number.

type ViewModuleOption

type ViewModuleOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

ViewModuleOption - a value of a choice filter and its label.

type ViewModuleParam

type ViewModuleParam = PluginBlockSetting

ViewModuleParam - one setting of a module's sort criterion or field in a View (the threshold of a weighted rating, how a rating is shown): the same kinds as a plugin block's setting. Its value is kept with the View's row (ViewSortDef.Params, ViewFieldDef.Params) under Key.

type ViewModuleSort

type ViewModuleSort struct {
	// Module - the module's name: the criterion is offered and applied
	// only while it is on.
	Module string
	// Key - "<module>.<name>", at most ViewModuleKeyMaxLen characters.
	Key string
	// Label - the English name, translated where shown.
	Label  string
	Params []ViewModuleParam
	// Values - each node's sort key among ids by the View's params (every
	// param set: its value, else its Default); a node left out sorts as
	// 0.
	Values func(ctx context.Context, ids []int, params map[string]string) (map[int]float64, error)
}

ViewModuleSort - a sort criterion a module adds to content Views.

type ViewProfileTabAccess

type ViewProfileTabAccess string

ViewProfileTabAccess - who sees a user_tab display's tab.

const (
	// ViewProfileTabAccessAll - every visitor.
	ViewProfileTabAccessAll ViewProfileTabAccess = "all"
	// ViewProfileTabAccessOwner - the profile's owner and admins.
	ViewProfileTabAccessOwner ViewProfileTabAccess = "owner"
)

type ViewQuery

type ViewQuery interface {
	// RunView executes a content view: each filter's value is
	// QueryParams[ExposedParam] for exposed filters (missing/empty = no
	// constraint) or Value otherwise; filters are AND-combined, sorted by
	// params.Sorts (empty = created_at desc) and paginated. Returns the
	// page's nodes and the total count. FieldStorages must contain every
	// field storage referenced by Filters/Sorts - RunView doesn't load
	// them itself.
	RunView(ctx context.Context, params ViewRunParams) (Nodes, int, error)

	// RunCommentView - RunView for a comment base entity display. Same
	// params; FieldStorages is always empty (comments have only builtin
	// filters/sorts).
	RunCommentView(ctx context.Context, params ViewRunParams) (Comments, int, error)

	// GlossaryForView computes per-letter counts for the glossary bar
	// using RunView's filter semantics (filters must exclude the
	// synthetic letter filter), grouped by the uppercased first rune of
	// the node title, or of the given text field when
	// glossaryFieldStorageID is set.
	GlossaryForView(ctx context.Context, filters ViewFilterDefs, moduleFilters []ViewRunModuleFilter, fieldStorages map[int]FieldStorageDef, glossaryFieldStorageID *int, queryParams map[string]string) (GlossaryData, error)
}

ViewQuery runs Views: the content and comment lists a display defines and its glossary bar. Separate from ViewRepository (the Views' definitions): the queries are an engine of their own.

type ViewRepository

type ViewRepository interface {
	// Views - the admin list rows: lone displays (ViewID nil) and View
	// Defaults, not every display (see PublicPageViews).
	Views(ctx context.Context) (ViewDisplayDefs, error)
	// PublicPageViews - every non-Default page display across all Views
	// (Views alone misses page displays inside a group), enabled or not:
	// the sitemap lists the enabled ones, a menu link may point to them.
	PublicPageViews(ctx context.Context) (ViewDisplayDefs, error)
	// AttachmentDisplays - every enabled, non-Default
	// DisplayType==attachment display, ordered by AttachWeight.
	AttachmentDisplays(ctx context.Context) (ViewDisplayDefs, error)
	// TermDisplays - every enabled, non-Default DisplayType==term
	// display, ordered by AttachWeight (then id).
	TermDisplays(ctx context.Context) (ViewDisplayDefs, error)
	// UserTabDisplays - every enabled, non-Default user_tab display,
	// ordered by AttachWeight (then id).
	UserTabDisplays(ctx context.Context) (ViewDisplayDefs, error)
	ViewByID(ctx context.Context, id int) (*ViewDisplayDef, error)
	ViewByMachineName(ctx context.Context, machineName string) (*ViewDisplayDef, error)
	// ViewByURLPath - public resolution of a page display by path.
	// Excludes IsDefault displays (defense-in-depth: they have no URL).
	ViewByURLPath(ctx context.Context, urlPath string) (*ViewDisplayDef, error)
	// PageDisplaysWithArgument - non-Default page displays whose URLPath
	// has an argument segment ("%"), e.g. "articles/%".
	PageDisplaysWithArgument(ctx context.Context) (ViewDisplayDefs, error)
	// ViewByURLPathAny - like ViewByURLPath but including Default
	// displays, for uniqueness checks: the DB UNIQUE constraint on
	// url_path covers every row regardless of is_default.
	ViewByURLPathAny(ctx context.Context, urlPath string) (*ViewDisplayDef, error)
	CreateView(ctx context.Context, v ViewDisplayDef) (*ViewDisplayDef, error)
	UpdateView(ctx context.Context, v ViewDisplayDef) (*ViewDisplayDef, error)
	DeleteView(ctx context.Context, id int) error
	// SetViewMachineName - renames a display's machine_name, bypassing
	// UpdateView's immutability. Only for createDisplay's
	// create-then-rename: the row is inserted with a placeholder (the
	// column is NOT NULL UNIQUE and the id is unknown before INSERT) and
	// renamed to "view_"+id in the same transaction.
	SetViewMachineName(ctx context.Context, id int, machineName string) (*ViewDisplayDef, error)
	// SetPublishedSnapshot - writes published_snapshot/published_at.
	// UpdateView never touches these columns, so its callers can't wipe
	// them. Called only by views.DefaultService.PublishDisplay.
	SetPublishedSnapshot(ctx context.Context, id int, snapshot string, publishedAt time.Time) (*ViewDisplayDef, error)

	// CreateViewContainer - creates a View (display group). Called only
	// by views.DefaultService.CloneDisplay.
	CreateViewContainer(ctx context.Context, v View) (*View, error)
	// SetViewContainerMachineName - the create-then-rename exception of
	// SetViewMachineName, for the container row.
	SetViewContainerMachineName(ctx context.Context, id int, machineName string) (*View, error)
	// ViewContainerByID - the View with the given id.
	ViewContainerByID(ctx context.Context, id int) (*View, error)
	// DeleteViewContainer - deletes a View by its own id. ON DELETE
	// CASCADE removes all its displays and their filters/sorts/fields,
	// so no orphaned Default is left behind.
	DeleteViewContainer(ctx context.Context, id int) error
	// DefaultDisplayOfView - the View's single IsDefault display (exists
	// once a View has been cloned). Used to resolve inherited sections.
	DefaultDisplayOfView(ctx context.Context, viewID int) (*ViewDisplayDef, error)
	// DisplaysOfView - every non-Default display of the View, for the
	// admin display tabs.
	DisplaysOfView(ctx context.Context, viewID int) (ViewDisplayDefs, error)

	FiltersByViewID(ctx context.Context, viewID int) (ViewFilterDefs, error)
	FilterByID(ctx context.Context, id int) (*ViewFilterDef, error)
	CreateFilter(ctx context.Context, f ViewFilterDef) (*ViewFilterDef, error)
	UpdateFilter(ctx context.Context, f ViewFilterDef) (*ViewFilterDef, error)
	DeleteFilter(ctx context.Context, id int) error

	SortsByViewID(ctx context.Context, viewID int) (ViewSortDefs, error)
	SortByID(ctx context.Context, id int) (*ViewSortDef, error)
	CreateSort(ctx context.Context, s ViewSortDef) (*ViewSortDef, error)
	// UpdateSort updates only Direction/SortOrder/Params; the target
	// (FieldStorageID/BuiltinField) is immutable - delete and re-add to
	// change it.
	UpdateSort(ctx context.Context, s ViewSortDef) (*ViewSortDef, error)
	DeleteSort(ctx context.Context, id int) error

	FieldsByViewID(ctx context.Context, viewID int) (ViewFieldDefs, error)
	ViewFieldByID(ctx context.Context, id int) (*ViewFieldDef, error)
	CreateViewField(ctx context.Context, f ViewFieldDef) (*ViewFieldDef, error)
	// UpdateViewField updates a field's display attributes; the target
	// (FieldStorageID/BuiltinField) is immutable - delete and re-add to
	// change it.
	UpdateViewField(ctx context.Context, f ViewFieldDef) (*ViewFieldDef, error)
	DeleteViewField(ctx context.Context, id int) error
}

ViewRepository - persistence for views, displays, filters, sorts and fields; running them is ViewQuery's.

type ViewRunModuleFilter

type ViewRunModuleFilter struct {
	Def    ViewFilterDef
	Filter ViewModuleFilter
}

ViewRunModuleFilter - a filter by a module's value with the module's lookup, as RunView consumes it.

type ViewRunParams

type ViewRunParams struct {
	Filters ViewFilterDefs
	// FieldStorages - by FieldStorageDef.ID, covering every filter and
	// sort that targets a generic field.
	FieldStorages map[int]FieldStorageDef
	// Sorts - in application order (Sorts[0] is the primary key). Empty
	// means "created_at desc".
	Sorts []ViewRunSort
	// QueryParams - the current request's query string, for exposed
	// filters. Never mutated.
	QueryParams map[string]string
	PageSize    int
	Page        int // 1-based
	// ContextCreatedByID/ContextNodeID - the node being viewed:
	// ContextCreatedByID feeds Contextual filters; ContextNodeID (when
	// >0) always excludes the current node from the results. 0 = no
	// context, in which case Contextual filters yield an empty result,
	// not an unfiltered one.
	ContextCreatedByID int
	ContextNodeID      int
	// ContextTermID - the taxonomy term whose page is being rendered,
	// for the has_current_term contextual filter (0 = no term context).
	ContextTermID int
	// ModuleFilters - the filters by modules' values (not in Filters),
	// AND-combined with them.
	ModuleFilters []ViewRunModuleFilter
}

ViewRunParams - input for ViewQuery.RunView, assembled by the service layer (which resolves FieldStorages), so RunView stays a pure query executor.

type ViewRunSort

type ViewRunSort struct {
	FieldStorage *FieldStorageDef // nil = sort by Builtin
	Builtin      ViewSortBuiltin
	Direction    string // "asc" | "desc"
	// Module - a module's criterion (Builtin is its key), with its
	// params resolved (ViewModuleParams).
	Module *ViewModuleSort
	Params map[string]string
}

ViewRunSort - a ViewSortDef with its field storage resolved, as RunView consumes it.

type ViewSnapshot

type ViewSnapshot struct {
	Settings ViewSnapshotSettings `json:"settings"`
	Filters  ViewFilterDefs       `json:"filters"`
	Sorts    ViewSortDefs         `json:"sorts"`
	Fields   ViewFieldDefs        `json:"fields"`
}

ViewSnapshot - the JSON stored in ViewDisplayDef.PublishedSnapshot by views.DefaultService.PublishDisplay: the effective settings and Filters/Sorts/Fields needed to render the public page. URLPath/Status/DisplayType/MachineName are not included - they always come from the live row (ViewByURLPath resolves by the live column; the rest are structural switches, not page content).

type ViewSnapshotSettings

type ViewSnapshotSettings struct {
	DisplayStyle               ViewDisplayStyle `json:"display_style"`
	GridColumns                int              `json:"grid_columns"`
	OverflowAfter              int              `json:"overflow_after"`
	CarouselSlidesPerView      int              `json:"carousel_slides_per_view"`
	CarouselAutoplay           bool             `json:"carousel_autoplay"`
	CarouselLoop               bool             `json:"carousel_loop"`
	CarouselShowNavigation     bool             `json:"carousel_show_navigation"`
	CarouselShowPagination     bool             `json:"carousel_show_pagination"`
	CarouselLinkFieldStorageID *int             `json:"carousel_link_field_storage_id"`
	CarouselEffect             string           `json:"carousel_effect"`
	ShowPagination             bool             `json:"show_pagination"`
	PaginationAjax             bool             `json:"pagination_ajax"`
	ShowGlossary               bool             `json:"show_glossary"`
	GlossaryFieldStorageID     *int             `json:"glossary_field_storage_id"`
	PageSize                   int              `json:"page_size"`
	HeaderText                 string           `json:"header_text"`
	FooterText                 string           `json:"footer_text"`
	OverflowHeaderText         string           `json:"overflow_header_text"`
	CustomCSS                  string           `json:"custom_css"`
	RowTemplate                string           `json:"row_template"`
	GroupByField               string           `json:"group_by_field"`
	GroupDateFormat            string           `json:"group_date_format"`
	Label                      string           `json:"label"`
	MetaTitle                  string           `json:"meta_title"`
	MetaDescription            string           `json:"meta_description"`
}

ViewSnapshotSettings - the Settings bundle EffectiveSettings resolves, plus Label/MetaTitle/MetaDescription: never inherited from Default, but still published page content. Stored as resolved values so a snapshot never depends on a live Default row that may change later.

func SnapshotSettingsOf

func SnapshotSettingsOf(display ViewDisplayDef) ViewSnapshotSettings

SnapshotSettingsOf - display's Settings bundle and Label/meta as a snapshot stores them (ApplyTo's counterpart).

func (ViewSnapshotSettings) ApplyTo

ApplyTo returns a copy of display with its Settings bundle (and Label/meta) replaced by s; all other fields pass through untouched. The snapshot counterpart of EffectiveSettings.

type ViewSortBuiltin

type ViewSortBuiltin string

ViewSortBuiltin - the built-in sort a ViewSortDef with a nil FieldStorageID applies. "views" sorts by node_counter.total_count, like AdminNodesSortViews.

const (
	ViewSortBuiltinCreatedAt ViewSortBuiltin = "created_at"
	ViewSortBuiltinViews     ViewSortBuiltin = "views"
	// ViewSortBuiltinTitle sorts by node title (alphabetical).
	ViewSortBuiltinTitle ViewSortBuiltin = "title"
	// ViewSortBuiltinUpdatedAt sorts by node updated_at (e.g. for a
	// moderation queue, like AdminNodesSortUpdated).
	ViewSortBuiltinUpdatedAt ViewSortBuiltin = "updated_at"
	// ViewSortBuiltinViewsToday sorts by node_counter.daycount (today's
	// views). RunView also excludes nodes not viewed today at all.
	ViewSortBuiltinViewsToday ViewSortBuiltin = "views_today"
	// ViewSortBuiltinViewsWeek and ViewSortBuiltinViewsMonth sort by the
	// views of the last 7 and 30 days, today included (node_view_days,
	// ViewDays). RunView also excludes nodes not viewed in them.
	ViewSortBuiltinViewsWeek  ViewSortBuiltin = "views_7d"
	ViewSortBuiltinViewsMonth ViewSortBuiltin = "views_30d"
	// ViewSortBuiltinCommentSubject - comment base entity only: sorts by
	// Comment.Subject. ViewSortBuiltinCreatedAt is reused for
	// Comment.CreatedAt (interpreted by BaseEntity at the query layer).
	ViewSortBuiltinCommentSubject ViewSortBuiltin = "comment_subject"
	// ViewSortBuiltinRandom - a shuffle, not a comparator; Direction is
	// ignored.
	ViewSortBuiltinRandom ViewSortBuiltin = "random"
	// ViewSortBuiltinSticky - Node.Sticky: descending puts the sticky
	// nodes first ("sticky at the top of lists"), the next criteria
	// order each group.
	ViewSortBuiltinSticky ViewSortBuiltin = "sticky"
)

The built-in sorts (ViewSortBuiltin).

func (ViewSortBuiltin) ViewDays

func (b ViewSortBuiltin) ViewDays() int

ViewDays - the days of views a sort counts (ViewSortBuiltinViewsWeek 7, ViewSortBuiltinViewsMonth 30), 0 for the other sorts.

type ViewSortDef

type ViewSortDef struct {
	ID            int
	ViewDisplayID int
	// FieldStorageID nil means this criterion sorts by BuiltinField.
	// Only text/number/date fields are sortable
	// (views.SortableFieldType).
	FieldStorageID *int
	BuiltinField   ViewSortBuiltin
	Direction      string // "asc" | "desc"
	// SortOrder - this criterion's position in the list; SortOrder==0
	// is the primary sort key.
	SortOrder int
	// Params - a module's criterion's settings in this View
	// (ViewModuleSort.Params); nil for the others.
	Params map[string]string `json:"Params,omitempty"`
	// ExposedKey - the criterion offered to visitors: its value of the
	// page's ViewSortParam; empty - not offered (see
	// ViewSortDefs.WithChoice).
	ExposedKey string `json:"ExposedKey,omitempty"`
	// ExposedLabel - the option's label in the visitors' choice.
	ExposedLabel string `json:"ExposedLabel,omitempty"`
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

ViewSortDef - one sort criterion of a ViewDisplayDef. Criteria apply in SortOrder: the first is the primary key, later ones break ties, like a multi-column ORDER BY.

func (ViewSortDef) Exposed

func (s ViewSortDef) Exposed() bool

Exposed - the criterion is offered to visitors.

func (ViewSortDef) FieldStorageIDValue

func (s ViewSortDef) FieldStorageIDValue() int

FieldStorageIDValue - FieldStorageID, 0 when the criterion targets a builtin.

type ViewSortDefs

type ViewSortDefs []ViewSortDef

ViewSortDefs - a list of a display's sort criteria.

func (ViewSortDefs) Exposed

func (ss ViewSortDefs) Exposed() ViewSortDefs

Exposed - the criteria offered to visitors, in order.

func (ViewSortDefs) SortBySortOrder

func (ss ViewSortDefs) SortBySortOrder() ViewSortDefs

SortBySortOrder - see ViewFilterDefs.SortBySortOrder.

func (ViewSortDefs) WithChoice

func (ss ViewSortDefs) WithChoice(key string) ViewSortDefs

WithChoice - the criteria a run applies (ss in order) when the visitor chose key: the exposed criteria are alternatives - one applies, the one with that ExposedKey (none such, or key empty - the first exposed), in the place of the first exposed; the others keep their places, so a "sticky first" criterion before them still leads.

type ViewTagFormat

type ViewTagFormat string

ViewTagFormat - how a taxonomy field renders: "plain" (comma-joined names), "linked" (comma-joined links) or "badges" (linked pills). See the dynamic_list_field_value block in dynamic/list.html.

const (
	ViewTagFormatPlain  ViewTagFormat = "plain"
	ViewTagFormatLinked ViewTagFormat = "linked"
	ViewTagFormatBadges ViewTagFormat = "badges"
)

The taxonomy fields' formats (ViewTagFormat).

Jump to

Keyboard shortcuts

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