repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

1495 lines · 111.7 KB · download this file

package BlowfishCMS;
# Blocks: every public page is an ordered list of blocks (text panels, the
# contact form, galleries, ...), stored in the pages and page_blocks tables.
# This file holds the block types, a new site's pages (from
# content/starter-pages.json), page lookup, public rendering and the admin
# page builder.
# Every BlowfishCMS/*.pm file adds subs to the one BlowfishCMS package; request state
# is shared through the package variables below and reset by BlowfishCMS::handle_request.
use v5.36;
use utf8;
use JSON::PP qw(encode_json decode_json);
use Digest::SHA qw(hmac_sha256_hex sha256_hex);
use Encode qw(decode encode FB_CROAK);
use Fcntl qw(:flock :DEFAULT);
use Unicode::Normalize qw(NFKC);
use POSIX qw(strftime);
use File::Basename qw(basename);
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf,%instance);

# ---- Block types ----------------------------------------------------------
# Each field: [name, label, kind, max length or options, hint]. Kinds: text,
# markdown, select, check, number. "once" types may appear once per page
# (their markup uses fixed element ids).
# Every block type BlowfishCMS has built in, keyed by its type name. Each
# type has:
#   label     its name in the editor
#   order     where it's listed among the "add a block" choices
#   group     which group of choices it's in (text, media, layout, content)
#   fields    its settings: [name, label, kind, limit or options, hint]
#             The kinds: text (one line; the number is its maximum length),
#             markdown (a text area), select (a menu; the list holds
#             [value => label] pairs), check (a tick box), number ([min, max]),
#             picture / pictures / folder (from the picture library),
#             item:music|video|file (one library item), collection:KIND (one
#             collection of a library), and items (a list of entries, each with
#             sub-fields of its own: questions, timeline entries, cards).
#   defaults  the values a new block starts with
#   once      may appear only once on a page
#   plain     draws its own markup instead of sitting in a panel (window)
#   manage    [library kind, link text]: the library screen for its content
#   note      a line of help shown in the block's settings
# `state` builds this once per worker and keeps it. After the list, every
# type with a panel gets the section settings (background, spacing...) and
# every type gets "leave out when printed".
sub core_block_types {
    state $types = do { my $types = {
        text => {label=>'Text panel', order=>1, group=>'text', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional; shown at the right of the title bar'],
            [heading=>'Large heading','text',200,'optional'],
            [body=>'Contents','markdown',30000,'Markdown: blank line between paragraphs, **bold**, [link](https://…), - lists, ### small headings'],
            [style=>'Style','select',[[panel=>'Panel'],[intro=>'Introduction (roomy, large heading)']]],
            [feed_link=>'Show the blog’s RSS feed link','check'],
        ], defaults=>{title=>'new panel',style=>'panel'}},
        about => {label=>'About me', order=>2, group=>'text', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [heading=>'Heading','text',200,'optional'],
            [body=>'Text','markdown',20000,'Markdown'],
            [picture=>'Picture','picture'],
            [position=>'Picture position','select',[[''=>'A portrait card (above, centred)'],[left=>'Left of the text'],[right=>'Right of the text'],[above=>'Above the text'],[below=>'Below the text']]],
            [picture_size=>'Picture size','select',[[medium=>'Medium'],[small=>'Small'],[large=>'Large'],[full=>'As wide as the panel']]],
            shape_fields(),
            button_fields(),
        ], defaults=>{title=>'about',heading=>'Hello!',body=>'A few words about me.',picture=>'',button_style=>'theme'},
           note=>'A few words about you, with a picture of you from the library if you like (choose none to leave it out).'},
        picture_text => {label=>'Text and picture', order=>3, group=>'text', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [heading=>'Heading','text',200,'optional'],
            [body=>'Text','markdown',20000,'Markdown'],
            [picture=>'Picture','picture'],
            [position=>'Picture position','select',[[left=>'Left of the text'],[right=>'Right of the text'],[above=>'Above the text'],[below=>'Below the text']]],
            [picture_size=>'Picture size','select',[[medium=>'Medium'],[small=>'Small'],[large=>'Large'],[full=>'As wide as the panel']]],
            [alt=>'Picture description','text',300,'optional; the picture’s own description is used otherwise'],
            [caption=>'Caption','text',300,'optional; shown under the picture'],
            link_fields('link','Picture links to'),
            shape_fields(),
            button_fields(),
        ], defaults=>{title=>'new panel',position=>'left',picture_size=>'medium',button_style=>'theme'},
           note=>'Text with a picture from the library beside, above or below it. Each block has its own picture.'},
        talk => {label=>'Comments and sharing', order=>42, group=>'content', once=>1, plain=>1, about=>'Likes, comments and sharing for the page it’s on (the Live page, say).', fields=>[]},
        contact_form => {label=>'Contact form', order=>40, group=>'content', once=>1, fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [label_name=>'Name label','text',60],
            [label_email=>'Email label','text',60],
            [label_subject=>'Subject label','text',60],
            [label_message=>'Message label','text',60],
            [subject=>'Ask for a subject','check'],
            [note=>'Note under the form','text',300,'optional'],
            [button=>'Button text','text',40],
            [button_style=>'Button colour','select',[button_colours()]],
            [sent_message=>'Message shown once it’s sent','text',300,'optional; “Your message was sent. Thank you for getting in touch.” otherwise'],
        ], defaults=>{title=>'get in touch',subtitle=>'send a message',label_name=>'Name',label_email=>'Email',label_subject=>'Subject',label_message=>'Message',button=>'send message',subject=>1,button_style=>'theme'},
           note=>'Messages are delivered to the address in the site settings.'},
        gallery => {label=>'Gallery', order=>12, group=>'media', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'leave blank to show the number of pictures'],
            [source=>'Show','select',[[folder=>'A folder of the picture library'],[picked=>'Pictures I choose']]],
            [folder=>'Folder','folder','when showing a folder'],
            [subfolders=>'Include the pictures in its subfolders','check'],
            [pictures=>'Pictures','pictures','when choosing pictures; in the order shown'],
            tag_field(),
            [layout=>'Layout','select',[[grid=>'Grid of thumbnails'],[rows=>'Rows (pictures keep their shape)'],[large=>'Large, one under another']]],
            [columns=>'Columns in the grid','select',[[auto=>'As many as fit'],[2=>'Two'],[3=>'Three'],[4=>'Four'],[5=>'Five']]],
            list_fields('pictures'),
            [captions=>'Show titles under the pictures','check'],
            tag_buttons_field(),
        ], defaults=>{title=>'gallery',source=>'folder',folder=>'',subfolders=>1,layout=>'grid',columns=>'auto',order=>'library',limit=>0,captions=>0}, manage=>['photography','manage pictures'],
           note=>'Pictures from the library. Visitors can open each one larger.'},
        music => {label=>'Music playlist', order=>15, group=>'media', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'leave blank to show the number of tracks'],
            [collection=>'Show','collection:music'],
            tag_field(),
            tag_buttons_field(),
            list_fields('tracks'),
        ], defaults=>{title=>'music',order=>'library',limit=>0}, manage=>['music','manage music']},
        videos => {label=>'Video gallery', order=>14, group=>'media', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'leave blank to show the number of videos'],
            [collection=>'Show','collection:video'],
            tag_field(),
            tag_buttons_field(),
            list_fields('videos'),
        ], defaults=>{title=>'videos',order=>'library',limit=>0}, manage=>['video','manage videos'],
           note=>'Plays each video in the page (no download link). Upload videos in the video library.'},
        download => {label=>'Download', order=>15, group=>'media', fields=>[
            [title=>'Panel title','text',120],
            [file=>'One file','item:file','or leave this empty for a list of files'],
            [collection=>'List','collection:file'],
            tag_field(),
            tag_buttons_field(),
            list_fields('files'),
        ], defaults=>{title=>'downloads',order=>'library',limit=>0}, manage=>['file','manage files'],
           note=>'Each file with a download button, its size, version and sha256. Upload files in the Files library.'},
        posts => {label=>'Article list', order=>41, group=>'content', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [limit=>'Number of posts','number',[0,100],'0 shows every published post'],
            tag_field(),
            [layout=>'Layout','select',[[list=>'A list'],[cards=>'Cards, with each article’s first picture']]],
            [show_date=>'Show the date','check'],
            [show_excerpt=>'Show the opening lines','check'],
        ], defaults=>{title=>'posts',limit=>0,layout=>'list',show_date=>1,show_excerpt=>0}, manage=>['blog','manage articles'],
           note=>'Newest first, with likes and comment counts. Each post opens on the Blog page.'},
        # ---- Media -------------------------------------------------------------
        picture => {label=>'Picture', order=>10, group=>'media', fields=>[
            [title=>'Panel title','text',120,'optional'],
            [picture=>'Picture','picture'],
            [size=>'Size','select',[[full=>'As wide as the panel'],[large=>'Large'],[medium=>'Medium'],[small=>'Small']]],
            [align=>'Alignment','select',[[center=>'Centred'],[left=>'Left'],[right=>'Right']]],
            [caption=>'Caption','text',300,'optional; shown under the picture'],
            [alt=>'Picture description','text',300,'optional; the picture’s own description is used otherwise'],
            link_fields('link','Links to'),
            [zoom=>'Open it larger when clicked (when it doesn’t link anywhere)','check'],
            shape_fields(),
        ], defaults=>{title=>'',size=>'full',align=>'center'}, note=>'One picture from the library, with a caption if you like.'},
        slideshow => {label=>'Slideshow', order=>11, group=>'media', fields=>[
            [title=>'Panel title','text',120,'optional'],
            [source=>'Show','select',[[folder=>'A folder of the picture library'],[picked=>'Pictures I choose']]],
            [folder=>'Folder','folder','when showing a folder'],
            [subfolders=>'Include the pictures in its subfolders','check'],
            [pictures=>'Pictures','pictures','when choosing pictures; in the order shown'],
            tag_field(),
            [interval=>'Moves on','select',[[0=>'Only when the visitor presses the arrows'],[3=>'Every 3 seconds'],[5=>'Every 5 seconds'],[8=>'Every 8 seconds'],[12=>'Every 12 seconds']]],
            [height=>'Height','select',[[natural=>'As the pictures are'],[wide=>'Fixed, 3:2'],[video=>'Fixed, 16:9']]],
            [picture_focus=>'Picture focus','select',[focus_choices()],'with a fixed height: the part of each picture that stays'],
            [controls=>'Controls','select',[[arrows=>'Arrows and a counter'],[dots=>'Arrows and dots'],[none=>'None (swipe, or let it move on)']]],
            [captions=>'Show titles over the pictures','check'],
        ], defaults=>{title=>'',source=>'folder',folder=>'',subfolders=>0,interval=>0,height=>'natural',picture_focus=>'center',controls=>'arrows',captions=>1}, manage=>['photography','manage pictures'],
           note=>'Pictures one at a time, with arrows (and swiping on phones). Pictures kept out of galleries stay out.'},
        video => {label=>'Video', order=>13, group=>'media', fields=>[
            [title=>'Panel title','text',120,'optional'],
            [video=>'Video','item:video'],
            [ambient=>'Play by itself, muted and looping (a moving picture rather than a film)','check'],
        ], defaults=>{title=>''}, manage=>['video','manage videos'], note=>'One video from the video library, played in the page.'},
        audio => {label=>'Audio player', order=>16, group=>'media', fields=>[
            [title=>'Panel title','text',120,'optional'],
            [track=>'Track','item:music'],
        ], defaults=>{title=>''}, manage=>['music','manage music'], note=>'One track from the music library. For several, use a music playlist.'},
        # ---- Layout ------------------------------------------------------------
        hero => {label=>'Hero header', order=>20, group=>'layout', plain=>1, fields=>[
            [heading=>'Heading','text',200],
            [body=>'Text','markdown',2000,'optional; a sentence or two'],
            [picture=>'Background picture','picture','optional'],
            [tint=>'Colours','select',[[dark=>'Light text on a dark tint'],[light=>'Dark text on a light tint'],[accent=>'Light text on the accent colour'],[plain=>'The page’s own colours']]],
            [height=>'Height','select',[[medium=>'Medium'],[small=>'Short'],[tall=>'Tall'],[screen=>'The height of the screen']]],
            [align=>'Alignment','select',[[center=>'Centred'],[left=>'Left'],[right=>'Right']]],
            [picture_focus=>'Picture focus','select',[focus_choices()],'the part of the picture that stays when the band crops it'],
            button_fields(),
            button_fields('button2','Second button'),
        ], defaults=>{heading=>'Welcome',tint=>'dark',height=>'medium',align=>'center',picture_focus=>'center',button_style=>'primary',button2_style=>'outline'},
           note=>'A wide band for the top of a page: a heading, a line of text and a button, over a picture or a colour.'},
        columns => {label=>'Columns', order=>21, group=>'layout', fields=>[
            [title=>'Panel title','text',120,'optional'],
            [count=>'Columns','select',[[2=>'Two'],[3=>'Three'],[4=>'Four']]],
            [widths=>'Widths','select',[[equal=>'Equal'],[wide=>'The first wider'],[narrow=>'The last wider']]],
            [valign=>'Line up','select',[[top=>'At the top'],[center=>'In the middle'],[bottom=>'At the bottom']]],
            [col1=>'First column','markdown',10000,'Markdown'],
            [col2=>'Second column','markdown',10000,'Markdown'],
            [col3=>'Third column','markdown',10000,'Markdown; shown with three or four columns'],
            [col4=>'Fourth column','markdown',10000,'Markdown; shown with four columns'],
        ], defaults=>{title=>'',count=>2,widths=>'equal',valign=>'top',col1=>"### First\n\nSome text.",col2=>"### Second\n\nSome text."},
           note=>'Text side by side; on phones the columns stack.'},
        divider => {label=>'Divider', order=>22, group=>'layout', plain=>1, fields=>[
            [style=>'Style','select',[[line=>'A line'],[space=>'Space only'],[dots=>'Three dots']]],
            [size=>'Space around it','select',[[medium=>'Medium'],[small=>'Small'],[large=>'Large']]],
            [colour=>'Colour','select',[[line=>'The theme’s lines'],[accent=>'The accent colour']]],
            [span=>'Width','select',[[full=>'Full width'],[short=>'Short, centred']]],
        ], defaults=>{style=>'line',size=>'medium',colour=>'line',span=>'full'}, note=>'A line or some space between blocks.'},
        button => {label=>'Button', order=>23, group=>'layout', plain=>1, fields=>[
            [label=>'Button text','text',60],
            link_fields('link','Links to','an address such as /contact/ or https://…'),
            [style=>'Colour','select',[button_colours()]],
            [size=>'Size','select',[[normal=>'Normal'],[small=>'Small'],[large=>'Large']]],
            [fill=>'Width','select',[[auto=>'Fits its text'],[full=>'The full width of the block']]],
            [align=>'Alignment','select',[[center=>'Centred'],[left=>'Left'],[right=>'Right']]],
            [note=>'Line under the button','text',200,'optional'],
        ], defaults=>{label=>'Get in touch',link=>'/contact/',style=>'theme',size=>'normal',fill=>'auto',align=>'center'}, note=>'A call to action.'},
        # ---- Content -----------------------------------------------------------
        quote => {label=>'Quote', order=>30, group=>'content', fields=>[
            [title=>'Panel title','text',120,'optional'],
            [text=>'Quote','markdown',3000],
            [who=>'Who said it','text',200,'optional'],
            [where=>'Where','text',300,'optional: a role, a publication, or a [link](https://…)'],
            [size=>'Size','select',[[large=>'Large'],[normal=>'Normal']]],
            [align=>'Alignment','select',[[left=>'Left'],[center=>'Centred']]],
            [picture=>'Picture of who said it','picture','optional; shown small and round'],
        ], defaults=>{title=>'',text=>'Something worth repeating.',size=>'large',align=>'left'}},
        faq => {label=>'Questions and answers', order=>31, group=>'content', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [items=>'Questions','items',[[q=>'Question','text',300],[a=>'Answer','markdown',5000]],'each answer folds out under its question'],
            [open=>'Start with the first one open','check'],
            [one=>'Only one open at a time','check'],
        ], defaults=>{title=>'questions',items=>[{q=>'A question visitors ask',a=>'The answer.'}]}, note=>'Fold-out questions (an FAQ).'},
        timeline => {label=>'Timeline', order=>32, group=>'content', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [items=>'Entries','items',[[when=>'When','text',80],[what=>'Title','text',200],[text=>'Text','markdown',5000]],'a year in “When” (2024, March 2024, 2024-03) lets them be put in order'],
            [order=>'Order','select',[[entered=>'As entered'],[newest=>'Newest first'],[oldest=>'Oldest first']]],
        ], defaults=>{title=>'timeline',order=>'entered',items=>[{when=>'2026',what=>'Something happened',text=>''}]}, note=>'Dated entries down a line: a history, a career, a project’s milestones.'},
        table => {label=>'Table', order=>33, group=>'content', fields=>[
            [title=>'Panel title','text',120],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [rows=>'Rows','markdown',20000,'one row per line, cells separated by | (a vertical bar); links as [text](https://…)'],
            [header=>'The first row is a header','check'],
            [striped=>'Striped rows','check'],
            [cell_align=>'Line up the cells','select',[[left=>'On the left'],[center=>'In the middle'],[numbers=>'On the left, the other columns on the right (for numbers)']]],
            [caption=>'Caption','text',300,'optional'],
        ], defaults=>{title=>'table',rows=>"Plan | Price | Includes\nBasic | 10 | One thing\nFull | 20 | Everything",header=>1}},
        cards => {label=>'Cards', order=>34, group=>'content', fields=>[
            [title=>'Panel title','text',120,'optional'],
            [subtitle=>'Panel subtitle','text',160,'optional'],
            [count=>'Cards per row','select',[[3=>'Three'],[2=>'Two'],[4=>'Four']]],
            [tone=>'Card colour','select',[[''=>'The theme’s panel'],tones()]],
            [text_align=>'Text','select',[[left=>'On the left'],[center=>'Centred']]],
            [link_as=>'Each card’s link','select',[[arrow=>'A link with an arrow'],[button=>'A button'],[card=>'The whole card']]],
            shape_fields('wide'),
            [items=>'Cards','items',[[picture=>'Picture','picture'],[heading=>'Title','text',200],[text=>'Text','markdown',3000],link_fields('link','Links to'),[link_label=>'Link text','text',60]],'each with a picture, a title, a little text and a link (all optional)'],
        ], defaults=>{title=>'',count=>3,text_align=>'left',link_as=>'arrow',picture_shape=>'wide',picture_focus=>'center',items=>[{heading=>'First',text=>'A few words.'},{heading=>'Second',text=>'A few words.'},{heading=>'Third',text=>'A few words.'}]},
           note=>'A grid of cards: services, projects, people, anything with a picture and a line or two.'},
    };
    # Options every block has.
    for my $t (values %$types) {
        push @{$t->{fields}},section_fields() unless $t->{plain};
        push @{$t->{fields}},anchor_field(),[print_hide=>'Leave out when the page is printed','check'];
    }
    $types };
    return $types;
}
# The look of a block's section, which every block with a panel has.
# The settings for the panel around a block: its background colour or none,
# a picture behind it, the space inside it, and hiding its title bar.
sub section_fields {
    return ([section_bg=>'Background','select',[[''=>'The theme’s panel'],tones(),[none=>'None: no panel, text on the page']]],
        [section_picture=>'Background picture','picture','optional; shown behind the block, dimmed'],
        [section_pad=>'Spacing','select',[[''=>'Normal'],[compact=>'Compact'],[roomy=>'Roomy']]],
        [section_bar=>'Hide the title bar','check']);
}
# Every block's anchor: a name for links straight to it, /services/#pricing.
# render_block puts it on the block's first tag as its id.
sub anchor_field { return [section_anchor=>'Anchor','text',40,'optional; a name such as pricing, for links that jump here: /page/#pricing'] }
# An anchor is 1–40 lowercase letters, digits and dashes, starting with a
# letter. The names the page uses for its own parts (the menu, the main
# column, comments, the contact form's fields) are kept for them.
sub anchor_ok ($name) {
    return 0 unless ($name//'') =~ /\A[a-z][a-z0-9-]{0,39}\z/;
    return 0 if $name =~ /\A(?:main|main-menu|theme-picker|photo-viewer|comments|comment-form|post-actions)\z/ || $name =~ /\A(?:contact|comment|block|tab|pe)-/;
    return 1;
}
# Gives a block's HTML its anchor as the id of its first tag, unless the
# anchor isn't usable or that tag already has an id.
sub anchor_html ($html,$anchor) {
    return $html unless anchor_ok($anchor);
    $html =~ s/\A(\s*<[a-zA-Z][\w-]*)(?![^>]*\sid=")/$1 id="$anchor"/;
    return $html;
}
# The colours blocks offer, all taken from the theme (its accent colour and
# its own buttons), so every theme and its dark variant draws them, and no
# colour code goes into the page (the security policy allows no inline styles).
sub tones { return ([soft=>'A soft tint of the accent colour'],[accent=>'The accent colour'],[dark=>'Dark'],[light=>'Light']) }
# The colours a button can be, all from the theme. "theme" is the theme's
# own form button; the others are cta--NAME classes in site.css.
sub button_colours {
    return ([theme=>'The theme’s own button'],[primary=>'Filled with the accent colour'],[outline=>'Outlined in the accent colour'],
        [soft=>'A soft tint of the accent colour'],[dark=>'Dark'],[light=>'Light']);
}
# ---- Settings blocks share ----------------------------------------------
# A link, and whether it opens in a new tab: every block with a link.
# The two settings every link in a block has: its address, and whether it
# opens in a new tab (NAME and NAME_newtab).
sub link_fields ($name,$label,$hint='optional: an address such as /contact/ or https://…') {
    return ([$name=>$label,'text',500,$hint],[$name.'_newtab'=>'Open it in a new tab','check']);
}
# href (and target) for a block's link, or '' when there's no usable one.
# The href (and target) attributes for a block's link, or '' when the
# address isn't one blocks may use (see link_ok). rel="noopener" stops the
# opened page from controlling this one.
sub link_attrs ($d,$name) {
    my $l=$d->{$name};
    return '' unless link_ok($l);
    return ' href="'.h($l).'"'.($d->{$name.'_newtab'} ? ' target="_blank" rel="noopener"' : '');
}
# A picture's shape and which part of it stays when the shape crops it.
sub focus_choices { return ([center=>'The middle'],[top=>'The top'],[bottom=>'The bottom']) }
sub shape_choices { return ([''=>'As it is'],[wide=>'3:2'],[square=>'Square'],[video=>'16:9'],[round=>'Round']) }
sub shape_fields {
    return ([picture_shape=>'Picture shape','select',[shape_choices()]],
        [picture_focus=>'Picture focus','select',[focus_choices()],'when the shape crops the picture: the part that stays']);
}
# The CSS classes for a picture's shape and focus (shape-square, focus-top),
# only from the allowed choices. Cards are 3:2 unless set otherwise
# ($fallback).
sub shape_class ($d,$fallback='') {
    my %shape=map {($_->[0]=>1)} shape_choices();my %focus=map {($_->[0]=>1)} focus_choices();
    my $shape=$shape{$d->{picture_shape}//$fallback} ? ($d->{picture_shape}//$fallback) : $fallback;
    my $focus=$focus{$d->{picture_focus}//''} ? $d->{picture_focus} : 'center';
    return (length $shape ? " shape-$shape" : '').($focus ne 'center' ? " focus-$focus" : '');
}
# A button under a block's text (About me, Text and picture, the Hero header's two).
# A button's settings under a given prefix: its text, link, new-tab choice
# and colour (button, button_link, button_link_newtab, button_style).
sub button_fields ($p='button',$label='Button') {
    return ([$p=>"$label text",'text',60,'optional'],link_fields($p.'_link',"$label links to"),[$p.'_style'=>"$label colour",'select',[button_colours()]]);
}
# The button for a block, drawn with cta_html, or '' if it has no text or
# no usable link.
sub button_html ($d,$p='button',$fallback='theme') {
    return '' unless length($d->{$p}//'') && link_ok($d->{$p.'_link'});
    return cta_html($d->{$p},$d->{$p.'_link'},style=>$d->{$p.'_style'}||$fallback,newtab=>$d->{$p.'_link_newtab'});
}
# How many of a library's items a block shows, and in which order.
# The settings blocks that list library items share: their order, how many
# to show (0 = all) and where a "See all" link goes.
sub list_fields ($what) {
    return ([order=>'Order','select',[[library=>'The library’s order'],[newest=>'Newest first']]],
        [limit=>"Number of $what",'number',[0,500],'0 shows them all'],
        link_fields('more_link','“See all” links to','optional, when the number is limited: a page showing them all'));
}
# Applies those settings to a list: sorts newest first if asked, keeps the
# first N, and returns (the shortened list, the "See all" link or '').
sub list_cut ($d,$list) {
    my @l=($d->{order}//'') eq 'newest' ? sort {($b->{created_at}//'') cmp ($a->{created_at}//'')} @$list : @$list;
    my $more=$d->{limit} && @l>$d->{limit};
    splice @l,$d->{limit} if $more;
    return (\@l,$more && link_ok($d->{more_link}) ? '<p class="block-more"><a'.link_attrs($d,'more_link').'>See all →</a></p>' : '');
}
# A button's link, in the chosen colour, size and width.
# A link drawn as a button ("call to action"): its colour, size and width are
# CSS classes, never inline colours (the security policy forbids inline
# styles).
sub cta_html ($label,$link,%o) {
    my %ok=map {($_->[0]=>1)} button_colours();
    my $style=$ok{$o{style}//''} ? $o{style} : 'primary';
    my $class='cta cta--'.$style.($style eq 'theme' ? ' form-submit' : '')
        .(($o{size}//'') =~ /\A(small|large)\z/ ? ' cta--'.$1 : '').(($o{fill}//'') eq 'full' ? ' cta--full' : '');
    return '<a class="'.$class.'" href="'.h($link).'"'.($o{newtab} ? ' target="_blank" rel="noopener"' : '').'>'.h($label).'</a>';
}
# The groups the "add a block" choices are shown in, in order.
sub block_groups { return ([text=>'Text'],[media=>'Pictures, music and video'],[layout=>'Layout'],[content=>'Content'],[addons=>'From add-ons']) }
# Core block types plus those of enabled add-ons.
# Every block type available now: the built-in ones plus those of enabled
# add-ons (add-on types go in the "From add-ons" group unless they say).
sub block_types { my %a=addon_block_types();$_->{group}//='addons' for values %a;my %t=(%{core_block_types()},%a);return \%t }
# The block type names in the order the editor lists them.
sub block_type_names { my $t=block_types(); return sort {$t->{$a}{order} <=> $t->{$b}{order}} keys %$t }
# One line on each built-in block, for the "add a block" choices (add-ons give their own as `about`).
# A one-line description of each built-in block, shown on its "add" button.
sub block_about {
    return {text=>'Headings and paragraphs, with links and lists.',about=>'A few lines about you, with your picture if you like.',
        picture_text=>'Any picture from the library beside some text.',contact_form=>'A form visitors use to send you a message.',
        gallery=>'Pictures from a library folder, or ones you pick, as a grid or rows.',
        music=>'Tracks from the music library, with a player.',download=>'Files to download, with their size, version and sha256.',videos=>'Videos from the video library.',posts=>'Your latest articles, linking to each one.',
picture=>'One picture, with a caption.',slideshow=>'Pictures one at a time, with arrows.',
        video=>'One video, played in the page.',audio=>'One track, with a player.',hero=>'A big heading over a picture or colour, with a button.',
        columns=>'Two to four columns of text side by side.',divider=>'A line or some space.',button=>'A button that links somewhere.',
        quote=>'A quote, with who said it.',faq=>'Questions that fold out to their answers.',timeline=>'Dated entries down a line.',
        table=>'Rows and columns of text.',cards=>'A grid of cards with a picture, title, text and link.'};
}
# Where a block can sit: full width, the left or right of two columns, or the
# page's sidebar.
sub widths { return ([full=>'Full width'],[left=>'Left column (wider)'],[right=>'Right column'],[side=>'Sidebar']) }
# The pages an install started with (its seed), recorded when the pages were
# first built (without that record, the seed's own list). Their addresses
# can't be changed and they lead the navigation; Home can't be removed.
sub builtin_pages {
    my $list=json_cached(scalar $db->selectrow_array("SELECT value FROM site_settings WHERE key='seed_pages'"));
    return ref $list eq 'ARRAY' ? @$list : map {$_->{slug}} @{page_seed()->{pages}};
}
# Pages that can't be deleted: only Home.
sub fixed_page ($slug) { return $slug eq 'home' }

# ---- Storage and the new site's pages ------------------------------------
# New installs start from content/starter-pages.json; BLOWFISH_PAGES_SEED
# points elsewhere (the tests use their own sample pages). Read when
# the code loads: a FastCGI worker's environment is replaced on every request.
my $pages_seed_file=$ENV{BLOWFISH_PAGES_SEED} // source_file('content/starter-pages.json');
# Reads the seed file (the pages a new site starts with) once per worker.
sub page_seed {
    state $seed=do {
        my $file=$pages_seed_file;
        open my $fh,'<:raw',$file or die "Page seed unavailable: $file";local $/;decode_json(<$fh>);
    };
    return $seed;
}
# Build the pages from the seed (the starter pages, or the tests' sample site).
# Turns the seed into pages ready to store: each page's fields, and each
# block with an id made from the page and its position (so building the same
# seed twice gives the same ids). In the seed each value is {"value": ...};
# only the value is kept.
sub seeded_pages {
    my $value=sub ($spec) { return $spec ? $spec->{value} // '' : '' };
    my @pages;
    for my $p (@{page_seed()->{pages}}) {
        my %page=(slug=>$p->{slug},path=>$p->{path},nav_label=>$p->{nav_label},title=>$value->($p->{title}),
            description=>$p->{description}//'',style=>(ref $p->{style} eq 'HASH' ? JSON::PP->new->canonical->encode($p->{style}) : '{}'),blocks=>[]);
        my $i=0;
        for my $b (@{$p->{blocks}}) {
            my %d;
            for my $k (keys %{$b->{data}}) {
                my $spec=$b->{data}{$k};$d{$k}=$value->($spec);
            }
            push @{$page{blocks}},{id=>substr(sha256_hex("$p->{slug}/$i"),0,16),type=>$b->{type},width=>$b->{width},data=>\%d};
            $i++;
        }
        push @pages,\%page;
    }
    return \@pages;
}
# Called from --migrate (as the catalogue's owner) inside its transaction.
# Creates the pages and page_blocks tables. A page is a row in `pages`; its
# blocks are rows in `page_blocks` (type, width, order on the page, and the
# block's settings as JSON in `data`). On a new site (no pages yet) it stores
# the seed's pages and records their slugs as `seed_pages`.
sub ensure_page_tables {
    $db->do("CREATE TABLE IF NOT EXISTS pages (slug TEXT PRIMARY KEY, path TEXT NOT NULL UNIQUE, nav_label TEXT NOT NULL, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', style TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, updated_at TEXT NOT NULL, noindex INTEGER NOT NULL DEFAULT 0, addon TEXT NOT NULL DEFAULT '')");
    $db->do("CREATE TABLE IF NOT EXISTS page_blocks (id TEXT PRIMARY KEY, page TEXT NOT NULL, sort_order INTEGER NOT NULL, type TEXT NOT NULL, width TEXT NOT NULL DEFAULT 'full', data TEXT NOT NULL)");
    $db->do('CREATE INDEX IF NOT EXISTS page_blocks_page ON page_blocks(page, sort_order)');
    my $record=sub (@slugs) {$db->do("INSERT OR IGNORE INTO site_settings(key,value) VALUES ('seed_pages',?)",undef,encode_json(\@slugs))};
    return if $db->selectrow_array('SELECT count(*) FROM pages');
    my @pages=@{seeded_pages()};
    $record->(map {$_->{slug}} @pages);
    for my $p (@pages) {
        $db->do('INSERT INTO pages (slug,path,nav_label,title,description,style,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)',undef,
            @$p{qw(slug path nav_label title description style)},now(),now());
        my $i=0;
        $db->do('INSERT INTO page_blocks (id,page,sort_order,type,width,data) VALUES (?,?,?,?,?,?)',undef,
            $_->{id},$p->{slug},$i++,$_->{type},$_->{width},JSON::PP->new->canonical->encode($_->{data})) for @{$p->{blocks}};
    }
    say 'Pages made from the seed: '.join(', ',map {$_->{slug}} @pages).'.';
}

my $page_cache;our $nav_cache;  # cleared at the start of every request
# Forgets the pages and navigation read during this request (called after
# any change, and at the start of every request).
sub reset_page_cache { undef $page_cache;undef $nav_cache }
# Every page with its blocks, read once per request and kept in
# $page_cache. Two queries (pages, then all blocks) instead of one per page.
# Each block's `data` is tied to LazyJSON (bottom of this file), so its JSON
# is only decoded if that block is actually drawn. The starter pages come
# first, in the seed's order; the rest follow by creation date.
sub all_pages {
    return $page_cache if $page_cache;
    my @pages=@{$db->selectall_arrayref('SELECT * FROM pages ORDER BY created_at, slug',{Slice=>{}})};
    my %by=map {($_->{slug}=>$_)} @pages;$_->{blocks}=[] for @pages;
    for my $b (@{$db->selectall_arrayref('SELECT * FROM page_blocks ORDER BY page, sort_order, id',{Slice=>{}})}) {
        next unless $by{$b->{page}};
        # Decoded when first read: a request shows one page, and decoding
        # every block of every page was most of a page's time.
        tie $b->{data},'BlowfishCMS::LazyJSON',$b->{data};
        push @{$by{$b->{page}}{blocks}},$b;
    }
    my %rank;my $i=0;$rank{$_}=$i++ for builtin_pages();
    return $page_cache=[sort {($rank{$a->{slug}}//99) <=> ($rank{$b->{slug}}//99)} @pages];
}
# One page by its slug ("about"), or undef.
sub page_by_slug ($slug) { my ($p)=grep {$_->{slug} eq ($slug//'')} @{all_pages()}; return $p }
# One page by its address ("/about/"), or undef.
sub page_by_path ($path) { my ($p)=grep {$_->{path} eq $path} @{all_pages()}; return $p }

# ---- Public rendering -----------------------------------------------------
# Every block is drawn as one window. Its body gets exactly one class, chosen
# by the block (see body_class); spacing at the edges comes from the window's
# padding alone (site.css). print_hide on any block leaves it out of printouts;
# subtitle_html is trusted markup used in place of the plain-text subtitle.
# Draws one panel: a title bar (title and an optional subtitle on the right)
# and a body. Options: print_hide, bg/pad/nobar/backdrop (the section style),
# aria (a label for screen readers), body_class, subtitle_html (ready-made
# HTML for the subtitle, used instead of escaping it).
sub window_html ($title,$subtitle,$body,%o) {
    my $meta=defined $o{subtitle_html} ? $o{subtitle_html} : h($subtitle//'');
    my $cls=join '',map {" $_"} grep {length} ($o{print_hide} ? 'print-hide' : ''),(length($o{bg}//'') ? "section--bg-$o{bg}" : ''),(length($o{pad}//'') ? "section--pad-$o{pad}" : ''),
        ($o{nobar} ? 'section--no-bar' : ''),($o{backdrop} ? 'section--backdrop' : '');
    return '<section class="window'.$cls.'"'.(length($o{aria}//'') ? ' aria-label="'.h($o{aria}).'"' : '').'>'
        .'<div class="window__bar"><div class="window__title"><span class="window__glyph" aria-hidden="true"></span>'.h($title).'</div>'
        .(length $meta ? '<div class="window__meta">'.$meta.'</div>' : '').'</div>'
        .($o{backdrop}//'').'<div class="window__body'.(length($o{body_class}//'') ? ' '.h($o{body_class}) : '').'">'.$body.'</div></section>';
}
# Markdown text as HTML in a <div class="page-copy">, or '' when empty.
sub markdown_copy ($text) { return length($text//'') ? '<div class="page-copy">'.render_markdown($text).'</div>' : '' }
# The one CSS class a block's panel body gets: an introduction text panel
# and an article list have their own looks.
sub body_class ($b) {
    my $d=$b->{data};
    return 'media-intro' if $b->{type} eq 'text' && ($d->{style}//'') eq 'intro';
    return 'blog-list' if $b->{type} eq 'posts';
    return '';
}
# A block's large heading, or '' when it has none.
sub block_heading ($text) { return length($text//'') ? '<h1 class="block-heading">'.h($text).'</h1>' : '' }

# Text with a picture (or none) left, right, above or below it.
# Lays text and a picture out together; the CSS classes say where the
# picture goes and how large it is ("none" when there's no picture).
sub picture_text_html ($img,$text,$pos,$size) {
    $text='<div class="picture-text__text">'.$text.'</div>';
    return '<div class="picture-text picture-text--'.($img ? $pos : 'none').' picture-text--'.$size.'">'.($pos eq 'below' ? $text.$img : $img.$text).'</div>';
}
# A gallery's pictures: a folder (and maybe its subfolders), or the chosen ones in order.
# The pictures a gallery or slideshow shows. "picked": the chosen ones, in
# the order chosen. "folder": that folder's pictures (and its subfolders' if
# ticked), leaving out pictures and folders kept out of galleries, unless
# the gallery shows that hidden folder itself. Then an optional tag filter.
sub gallery_pictures ($d) {
    my @all=@{items('photography')};
    if (($d->{source}//'folder') eq 'picked') {
        my %by=map {($_->{id}=>$_)} @all;
        return tag_filter('photography',$d->{tag},[map {$by{$_} // ()} grep {length} split /,/,($d->{pictures}//'')]);
    }
    my $f=$d->{folder}//'';
    # Pictures and folders hidden from galleries stay out, unless the gallery
    # shows that hidden folder itself (chosen pictures always show).
    my @hidden=grep {!($f eq $_ || index($f,"$_/")==0)} hidden_folders();
    return tag_filter('photography',$d->{tag},[grep {my $g=$_->{folder}//'';!$_->{gallery_hidden} && !grep({$g eq $_ || index($g,"$_/")==0} @hidden)
        && ($g eq $f || ($d->{subfolders} && ($f eq '' || index($g,"$f/")==0)))} @all]);
}
# Draws a grid of pictures. Each is a button that opens the picture viewer
# (site.js reads data-src and data-title); a picture that's public also gets
# its own page (/picture/ID/) and, with captions on, its likes and comments
# count. Optional tag buttons let visitors filter the grid.
sub gallery_html ($list,$layout,$captions,$columns='',%o) {
    return '<p class="empty-media">Nothing published yet. Check back soon.</p>' unless @$list;
    my $tmap=$o{tag_buttons} ? item_tags_map('photography') : undef;
    my $cols=$layout eq 'grid' && ($columns//'') =~ /\A[2-5]\z/ ? " photo-grid--cols-$columns" : '';
    my $html=tag_buttons_html($tmap,$list).'<div class="photo-grid photo-grid--'.h($layout).$cols.($captions ? '' : ' photo-grid--bare').'">';
    my ($likes,$talk)=talk_counts('photography');my $stats=talk_library_on('photography') && comments_enabled();
    for my $item (@$list) {
        my $title=h($item->{title});my $alt=h(length($item->{description}//'') ? $item->{description} : $item->{title});
        my $thumb=$layout eq 'large' ? media_url($item) : media_url($item,1);
        my $page=$item->{gallery_hidden} || folder_hidden($item->{folder}//'') ? '' : "/picture/$item->{id}/";
        $html.='<figure class="photo-card"'.tags_data_attr($tmap,$item->{id}).'><button type="button" class="photo-open" data-src="'.h(media_url($item)).'" data-title="'.$title.'"'.(length $page ? ' data-page="'.$page.'"' : '').' aria-label="View '.$title.' larger"><img src="'.h($thumb).'" alt="'.$alt.'"'
            .($item->{width} ? ' width="'.$item->{width}.'" height="'.$item->{height}.'"' : '').' loading="lazy" decoding="async" draggable="false"></button>'
            .($captions ? '<figcaption><h2>'.(length $page ? '<a href="'.$page.'">'.$title.'</a>' : $title).'</h2>'.(length($item->{description}//'') ? '<p>'.h($item->{description}).'</p>' : '')
                .(length $page && $stats && !$item->{talk_off} ? talk_stats_html($likes->{$item->{id}},$talk->{$item->{id}}) : '').'</figcaption>' : '').'</figure>';
    }
    return $html.'</div>';
}

# A picture from the library, as an <img> (undef when it's gone).
# An <img> for a library picture by id, with its size (so the page doesn't
# jump while it loads) and lazy loading; undef when the picture is gone.
# "decorative" pictures get an empty alt text, so screen readers skip them.
sub library_img ($id,$alt='',%o) {
    my $p=length($id//'') ? picture_by_id($id) : undef or return undef;
    $alt=length($p->{description}//'') ? $p->{description} : $p->{title} unless length $alt;
    return '<img'.($o{class} ? ' class="'.h($o{class}).'"' : '').' src="'.h(picture_url($p)).'" alt="'.h($o{decorative} ? '' : $alt).'"'.($p->{width} ? ' width="'.$p->{width}.'" height="'.$p->{height}.'"' : '').' loading="lazy" decoding="async">';
}
# Addresses blocks may link to: this site's own (/…) or https://, http://, mailto:.
# Addresses blocks may link to: this site's own (starting with one /, not //,
# which would be another site), http(s) and mailto. Anything else
# (javascript:, data:) is refused.
sub link_ok ($l) { return ($l//'') =~ m{\A(?:/(?!/)|https?://|mailto:)\S*\z} || ($l//'') =~ /\A#[a-z][a-z0-9-]{0,39}\z/ ? 1 : 0 }
# A timeline entry's date as a sortable key ("2024", "March 2024", "2024-03",
# "3/2024"): year, then month; '' when it has no year.
# Turns a timeline entry's "when" into a sortable key "YYYY-MM": finds a year
# (1000-2999), then a month by name or number next to the year. '' when
# there's no year (such entries go last).
sub when_key ($when) {
    my $w=lc($when//'');
    my ($y)=$w =~ /\b(1\d{3}|2\d{3})\b/ or return '';
    my %m=(jan=>1,feb=>2,mar=>3,apr=>4,may=>5,jun=>6,jul=>7,aug=>8,sep=>9,oct=>10,nov=>11,dec=>12);
    my $mo=$w =~ /\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\b/ ? $m{$1} : $w =~ /\b$y[-\/.](\d{1,2})\b/ ? $1 : $w =~ /\b(\d{1,2})[-\/.]$y\b/ ? $1 : 0;
    return sprintf '%04d-%02d',$y,($mo>=1 && $mo<=12 ? $mo : 0);
}
# Timeline entries newest or oldest first by their dates; undated ones last.
# Sorts timeline entries by their when_key, newest or oldest first, with
# undated entries kept at the end in the order they were entered.
sub timeline_sorted ($dir,@entries) {
    my @dated=map {[$_,when_key($_->{when})]} @entries;
    my @sorted=sort {$a->[1] cmp $b->[1]} grep {length $_->[1]} @dated;
    @sorted=reverse @sorted if $dir eq 'newest';
    return ((map {$_->[0]} @sorted),map {$_->[0]} grep {!length $_->[1]} @dated);
}
# Markdown for one short line (a table cell, a quote's source): no paragraph around it.
# Markdown for a short piece (a table cell, a quote's source), without the
# <p> it would otherwise be wrapped in.
sub markdown_inline ($text) { my $html=render_markdown($text//'');$html =~ s{\A\s*<p>(.*)</p>\s*\z}{$1}s;return $html }
# The page editor's canvas: the page drawn as visitors see it, with each
# block marked (data-pe-block) and each of its texts marked (data-pe-field,
# named as the editor's form names it) so the editor can edit them in place.
# Texts are swapped for markers before the block is drawn and the drawing is
# then searched for them: in a tag they become the value again; in text, an
# editable span; a Markdown field's paragraph becomes its rendered Markdown.
# Links, addresses and contact details aren't marked (they must stay valid).
our $edit_canvas=0;
# Which fields the in-page editor may edit in place: texts and Markdown,
# but not addresses, links, contact details, tags or section settings, which
# must stay valid and are edited in the block's settings card instead.
sub canvas_markable ($name,$kind) { return $kind =~ /\A(?:text|markdown)\z/ && $name !~ /url|link|href|email|phone|slug|address|\Asection_|\Aprint_hide\z|\Atag\z/ }
# Draws one block. Normally that's render_block_html. In the page editor
# ($edit_canvas on) it first swaps each editable text for a unique marker
# (zpe1x, zpe2x ...), draws the block, then finds the markers in the result:
#   - a marker that is a whole paragraph of a Markdown field becomes an
#     editable box with the rendered Markdown (data-pe-md);
#   - a marker inside a tag (an attribute) becomes the real value again;
#   - a marker in the text becomes an editable <span data-pe-field="...">.
# The block's first tag gets data-pe-block="ID" so clicking it selects it.
# admin.js uses these attributes to edit the page in place.
# Either way, the block's anchor becomes its first tag's id.
sub render_block ($b) { return anchor_html($edit_canvas ? render_block_canvas($b) : render_block_html($b),$b->{data}{section_anchor}) }
sub render_block_canvas ($b) {
    my $t=block_types()->{$b->{type}} or return render_block_html($b);
    my (%tok,$n);
    my $mark=sub ($field,$kind,$value,$label) {my $k='zpe'.++$n.'x';$tok{$k}=[$field,$kind,$value//'',$label];return $k};
    my %d=%{$b->{data}};
    for my $f (@{$t->{fields}//[]}) {
        my ($name,$label,$kind,$opt)=@$f;
        if ($kind eq 'items' && ref $d{$name} eq 'ARRAY') {
            my $i=0;
            $d{$name}=[map {
                my %e=ref $_ eq 'HASH' ? %$_ : ();my $N=$i++;
                for my $sf (@$opt) {
                    my ($sn,$sl,$sk)=@$sf;
                    next unless canvas_markable($sn,$sk) && ($sk eq 'markdown' || length($e{$sn}//''));
                    $e{$sn}=$mark->("b.$b->{id}.$name.$N.$sn",$sk,$e{$sn},$sl);
                }
                \%e;
            } @{$d{$name}}];
            next;
        }
        next unless canvas_markable($name,$kind);
        # An empty text stays empty (a title bar or caption isn't added by
        # editing); an empty Markdown text shows where to write.
        next unless $kind eq 'markdown' || length($d{$name}//'');
        $d{$name}=$mark->("b.$b->{id}.$name",$kind,$d{$name},$label);
    }
    my $html=render_block_html({%$b,data=>\%d});
    my $md=sub ($e) {'<div class="pe-md" data-pe-field="'.h($e->[0]).'" data-pe-md data-placeholder="'.h($e->[3]).'">'.($e->[2] =~ /\S/ ? render_markdown($e->[2]) =~ s/\A\s+|\s+\z//gr : '').'</div>'};
    $html =~ s{<p>(zpe\d+x)</p>}{my $e=$tok{$1};$e && $e->[1] eq 'markdown' ? $md->($e) : "<p>$1</p>"}ge;
    $html =~ s{(<[^>]*>)|([^<]+)}{defined $1 ? ($1 =~ s/(zpe\d+x)/$tok{$1} ? h($tok{$1}[2]) : $1/ger)
        : ($2 =~ s/(zpe\d+x)/$tok{$1} ? '<span class="pe-text" data-pe-field="'.h($tok{$1}[0]).'" data-placeholder="'.h($tok{$1}[3]).'">'.h($tok{$1}[2]).'<\/span>' : $1/ger)}ge;
    $html =~ s/\A(\s*<[a-zA-Z][\w-]*)/$1 data-pe-block="@{[h($b->{id})]}"/;
    return $html;
}
# The HTML for one block as visitors see it: one branch per block type.
# Common to most: %o carries the section style for window_html; a block with
# no title gets no title bar.
sub render_block_html ($b) {
    my $d=$b->{data};my $type=$b->{type};
    my %o=(body_class=>body_class($b),print_hide=>$d->{print_hide},bg=>($d->{section_bg}//''),pad=>($d->{section_pad}//''),nobar=>($d->{section_bar} || ($d->{section_bg}//'') eq 'none'));
    if (my $img=library_img($d->{section_picture},'',class=>'section__backdrop',decorative=>1)) {$o{backdrop}=$img}
    # Picture: a link if it has one, otherwise optionally a button that opens it
    # larger; then size, alignment, shape and caption.
    if ($type eq 'picture') {
        my $img=library_img($d->{picture},$d->{alt}) // return '';
        if (link_ok($d->{link})) {$img='<a'.link_attrs($d,'link').'>'.$img.'</a>'}
        elsif ($d->{zoom}) {my $p=picture_by_id($d->{picture});$img='<button type="button" class="photo-open" data-src="'.h(picture_url($p)).'" data-title="'.h($d->{caption}||$p->{title}).'" aria-label="View it larger">'.$img.'</button>'}
        my $fig='<figure class="block-picture block-picture--'.h($d->{size}||'full').' block-picture--'.h($d->{align}||'center').shape_class($d).'">'.$img.(length($d->{caption}//'') ? '<figcaption>'.h($d->{caption}).'</figcaption>' : '').'</figure>';
        return window_html($d->{title},'',$fig,%o,nobar=>($o{nobar} || !length($d->{title}//'')));
    }
    # Slideshow: every picture as a slide in a track; site.js moves the track.
    # data-interval and data-controls tell the script how it behaves.
    if ($type eq 'slideshow') {
        my $list=gallery_pictures($d);
        return '' unless @$list;
        my %h=(wide=>1,video=>1);my %c=(dots=>1,none=>1);
        my $html='<div class="slideshow'.($h{$d->{height}//''} ? ' slideshow--'.$d->{height}.shape_class({picture_focus=>$d->{picture_focus}}) : '').'" data-slideshow'.($d->{interval} ? ' data-interval="'.(0+$d->{interval}).'"' : '').($c{$d->{controls}//''} ? ' data-controls="'.$d->{controls}.'"' : '').' aria-roledescription="slideshow" aria-label="'.h($d->{title}||'Pictures').'"><div class="slideshow__track">'
            .join('',map {my $alt=length($_->{description}//'') ? $_->{description} : $_->{title};
                '<figure class="slideshow__slide"><img src="'.h(media_url($_)).'" alt="'.h($alt).'"'.($_->{width} ? ' width="'.$_->{width}.'" height="'.$_->{height}.'"' : '').' loading="lazy" decoding="async" draggable="false">'
                .($d->{captions} && length($_->{title}//'') ? '<figcaption>'.h($_->{title}).'</figcaption>' : '').'</figure>'} @$list).'</div></div>';
        return window_html($d->{title},@$list.' '.(@$list==1 ? 'picture' : 'pictures'),$html,%o,nobar=>($o{nobar} || !length($d->{title}//'')));
    }
    # One video or track. An "ambient" video plays muted and looping by itself,
    # like a moving picture.
    if ($type eq 'video' || $type eq 'audio') {
        my ($kind,$key)=$type eq 'video' ? ('video','video') : ('music','track');
        my ($item)=grep {$_->{id} eq ($d->{$key}//'')} @{items($kind)};
        return '' unless $item;
        my $body=$kind eq 'video' && $d->{ambient}
            ? '<div class="video-list"><article class="video-card"><video class="video-ambient" autoplay muted loop playsinline disableremoteplayback controls src="'.h(media_url($item)).'" aria-label="'.h($item->{title}).'"></video></article></div>'
            : $kind eq 'video' ? video_list_html([$item],0) : music_list_html([$item],0);
        return window_html($d->{title},'',$body,%o,nobar=>($o{nobar} || !length($d->{title}//'')));
    }
    # Hero header: a wide band with a heading, text and up to two buttons over a
    # background picture or colour.
    if ($type eq 'hero') {
        my $bg=library_img($d->{picture},'',class=>'hero__bg',decorative=>1) // '';
        my $buttons=join ' ',grep {length} button_html($d,'button','primary'),button_html($d,'button2','outline');
        my $button=length $buttons ? '<p class="hero__buttons">'.$buttons.'</p>' : '';
        return '<section class="hero hero--'.h($d->{height}||'medium').' hero--'.h($d->{tint}||'dark').' hero--'.h($d->{align}||'center').($bg ? ' hero--picture'.shape_class({picture_focus=>$d->{picture_focus}}) : '').($d->{print_hide} ? ' print-hide' : '').'">'.$bg
            .'<div class="hero__content">'.(length($d->{heading}//'') ? '<h1>'.h($d->{heading}).'</h1>' : '').markdown_copy($d->{body}).$button.'</div></section>';
    }
    # Columns: 2-4 Markdown columns side by side, with optional width and
    # vertical alignment classes.
    if ($type eq 'columns') {
        my $n=($d->{count}//2) =~ /\A[234]\z/ ? $d->{count} : 2;
        my $cols=join '',map {'<div class="block-columns__col">'.markdown_copy($d->{"col$_"}).'</div>'} 1..$n;
        my %w=(wide=>1,narrow=>1);my %v=(center=>1,bottom=>1);
        my $cls='block-columns block-columns--'.$n.($w{$d->{widths}//''} ? " block-columns--$d->{widths}" : '').($v{$d->{valign}//''} ? " block-columns--v-$d->{valign}" : '');
        return window_html($d->{title},'','<div class="'.$cls.'">'.$cols.'</div>',%o,nobar=>($o{nobar} || !length($d->{title}//'')));
    }
    # Divider: a line, space or three dots; role="separator" for screen readers.
    if ($type eq 'divider') {
        my $style=$d->{style}//'line';
        return '<div class="block-divider block-divider--'.h($style).' block-divider--'.h($d->{size}||'medium').(($d->{colour}//'') eq 'accent' ? ' block-divider--accent' : '').(($d->{span}//'') eq 'short' ? ' block-divider--short' : '').($d->{print_hide} ? ' print-hide' : '').'" role="separator">'.($style eq 'dots' ? '<span aria-hidden="true">· · ·</span>' : '').'</div>';
    }
    if ($type eq 'button') {
        return '' unless length($d->{label}//'') && link_ok($d->{link});
        return '<div class="block-button block-button--'.h($d->{align}||'center').($d->{print_hide} ? ' print-hide' : '').'">'.cta_html($d->{label},$d->{link},style=>$d->{style}||'primary',size=>$d->{size},fill=>$d->{fill},newtab=>$d->{link_newtab})
            .(length($d->{note}//'') ? '<p class="block-button__note">'.h($d->{note}).'</p>' : '').'</div>';
    }
    if ($type eq 'quote') {
        my $cite=join ', ',grep {length} (length($d->{who}//'') ? '<strong>'.h($d->{who}).'</strong>' : ''),(length($d->{where}//'') ? markdown_inline($d->{where}) : '');
        my $face=library_img($d->{picture},$d->{who}//'',class=>'block-quote__face') // '';
        my $q='<figure class="block-quote block-quote--'.h($d->{size}||'large').(($d->{align}//'') eq 'center' ? ' block-quote--center' : '').'">'.$face.'<blockquote>'.render_markdown($d->{text}//'').'</blockquote>'.(length $cite ? '<figcaption>— '.$cite.'</figcaption>' : '').'</figure>';
        return window_html($d->{title},'',$q,%o,nobar=>($o{nobar} || !length($d->{title}//'')));
    }
    if ($type eq 'faq') {
        my $i=0;
        my $group=$d->{one} ? ' name="faq-'.h($b->{id}//'q').'"' : '';
        my $list=join '',map {'<details class="faq__item"'.$group.($d->{open} && !$i++ ? ' open' : '').'><summary>'.h($_->{q}//'').'</summary><div class="faq__answer">'.render_markdown($_->{a}//'').'</div></details>'} grep {length($_->{q}//'')} @{ref $d->{items} eq 'ARRAY' ? $d->{items} : []};
        return window_html($d->{title},$d->{subtitle},'<div class="faq">'.$list.'</div>',%o);
    }
    if ($type eq 'timeline') {
        my @entries=@{ref $d->{items} eq 'ARRAY' ? $d->{items} : []};
        @entries=timeline_sorted($1,@entries) if ($d->{order}//'') =~ /\A(newest|oldest)\z/;
        my $list=join '',map {'<li class="timeline__entry">'.(length($_->{when}//'') ? '<p class="timeline__when">'.h($_->{when}).'</p>' : '').(length($_->{what}//'') ? '<h3>'.h($_->{what}).'</h3>' : '').markdown_copy($_->{text}).'</li>'} @entries;
        return window_html($d->{title},$d->{subtitle},'<ol class="timeline">'.$list.'</ol>',%o);
    }
    # Table: each line of the text is a row, cells split at "|"; empty cells at
    # the very start and end (from "| a | b |") are dropped. Every row is padded
    # to the widest row's number of cells.
    if ($type eq 'table') {
        my @rows=map {[map {s/\A\s+|\s+\z//gr} split /\|/,$_,-1]} grep {/\S/} split /\n/,($d->{rows}//'');
        @rows=map {my @r=@$_;shift @r if @r>1 && $r[0] eq '';pop @r if @r>1 && $r[-1] eq '';\@r} @rows;
        my $head=$d->{header} && @rows ? shift @rows : undef;
        my $cols=0;for (@rows,$head ? $head : ()) {$cols=@$_ if @$_>$cols}
        my $cell=sub ($tag,$r) {return '<tr>'.join('',map {"<$tag>".markdown_inline($r->[$_]//'')."</$tag>"} 0..$cols-1).'</tr>'};
        my %al=(center=>1,numbers=>1);
        my $t='<div class="block-table'.($d->{striped} ? ' block-table--striped' : '').($al{$d->{cell_align}//''} ? " block-table--$d->{cell_align}" : '').'"><table>'.(length($d->{caption}//'') ? '<caption>'.h($d->{caption}).'</caption>' : '')
            .($head ? '<thead>'.$cell->('th',$head).'</thead>' : '').'<tbody>'.join('',map {$cell->('td',$_)} @rows).'</tbody></table></div>';
        return window_html($d->{title},$d->{subtitle},$t,%o);
    }
    # Cards: each card has an optional picture, title, text and link; the link is
    # an arrow link, a small button, or the whole card ("card"). When the
    # picture and the title both link, the picture's link is hidden from screen
    # readers and the keyboard, so the same link isn't announced twice.
    if ($type eq 'cards') {
        my $n=($d->{count}//3) =~ /\A[234]\z/ ? $d->{count} : 3;
        my $as=($d->{link_as}//'') =~ /\A(button|card)\z/ ? $1 : 'arrow';
        my $cards=join '',map {my $c=$_;my $img=library_img($c->{picture},$c->{heading}) // '';my $at=link_attrs($c,'link');
            $img='<a'.$at.' tabindex="-1" aria-hidden="true">'.$img.'</a>' if $img && length $at && $as ne 'card';
            my $label=length($c->{link_label}//'') ? $c->{link_label} : '';
            my $foot=!length $at || !length $label || $as eq 'card' ? ''
                : $as eq 'button' ? '<p class="card__link">'.cta_html($label,$c->{link},style=>'theme',size=>'small',newtab=>$c->{link_newtab}).'</p>'
                : '<p class="card__link"><a'.$at.'>'.h($label).' →</a></p>';
            '<article class="card">'.($img ? '<div class="card__picture">'.$img.'</div>' : '').'<div class="card__body">'
            .(length($c->{heading}//'') ? '<h3>'.(length $at ? '<a'.$at.'>'.h($c->{heading}).'</a>' : h($c->{heading})).'</h3>' : '').markdown_copy($c->{text}).$foot.'</div></article>'} @{ref $d->{items} eq 'ARRAY' ? $d->{items} : []};
        my $cls='cards cards--'.$n.(grep({$_->[0] eq ($d->{tone}//'')} tones()) ? ' cards--tone-'.$d->{tone} : '')
            .(($d->{text_align}//'') eq 'center' ? ' cards--center' : '').($as eq 'card' ? ' cards--whole' : '').shape_class($d,'wide');
        return window_html($d->{title},$d->{subtitle},'<div class="'.$cls.'">'.$cards.'</div>',%o,nobar=>($o{nobar} || !length($d->{title}//'')));
    }
    if ($type eq 'text') {
        my $body=block_heading($d->{heading}).markdown_copy($d->{body});
        $body.='<p class="feed-link"><a href="/blog/feed.xml">RSS feed</a> · follow new posts in a feed reader</p>' if $d->{feed_link};
        return window_html($d->{title},$d->{subtitle},$body,%o);
    }
    if ($type eq 'about') {
        # Your bio, with a picture from the library or none.
        my $p=length($d->{picture}//'') ? picture_by_id($d->{picture}) : undef;my $pos=$d->{position}//'';
        my $text=block_heading($d->{heading}).markdown_copy($d->{body});
        if (length(my $btn=button_html($d))) {$text.='<p class="block-buttons">'.$btn.'</p>'}
        return window_html($d->{title},$d->{subtitle},$text,%o) unless $p;
        my $alt=length($p->{description}//'') ? $p->{description} : 'Portrait of '.(setting('author') || setting('site_title'));
        my $tag='<img src="'.h(picture_url($p)).'" alt="'.h($alt).'"'.($p->{width} ? ' width="'.$p->{width}.'" height="'.$p->{height}.'"' : '').' decoding="async">';
        return window_html($d->{title},$d->{subtitle},'<div class="about-card"><div class="about-card__photo'.shape_class($d).'">'.$tag.'</div><div class="about-card__text">'.$text.'</div></div>',%o) if $pos eq '';
        return window_html($d->{title},$d->{subtitle},picture_text_html('<figure class="picture-text__picture picture-text__picture--portrait'.shape_class($d).'">'.$tag.'</figure>',$text,$pos,$d->{picture_size}||'medium'),%o);
    }
    if ($type eq 'picture_text') {
        my $p=picture_by_id($d->{picture});my $img='';
        if ($p) {
            my $alt=length($d->{alt}//'') ? $d->{alt} : length($p->{description}//'') ? $p->{description} : $p->{title};
            my $tag='<img src="'.h(picture_url($p)).'" alt="'.h($alt).'"'.($p->{width} ? ' width="'.$p->{width}.'" height="'.$p->{height}.'"' : '').' loading="lazy" decoding="async">';
            $tag='<a'.link_attrs($d,'link').'>'.$tag.'</a>' if link_ok($d->{link});
            $img='<figure class="picture-text__picture'.shape_class($d).'">'.$tag.(length($d->{caption}//'') ? '<figcaption>'.h($d->{caption}).'</figcaption>' : '').'</figure>';
        }
        my $text=block_heading($d->{heading}).markdown_copy($d->{body});
        if (length(my $btn=button_html($d))) {$text.='<p class="block-buttons">'.$btn.'</p>'}
        return window_html($d->{title},$d->{subtitle},picture_text_html($img,$text,$d->{position}||'left',$d->{picture_size}||'medium'),%o);
    }
    if ($type eq 'gallery') {
        my $all=gallery_pictures($d);
        my $meta=length($d->{subtitle}//'') ? $d->{subtitle} : @$all.' '.(@$all==1 ? 'picture' : 'pictures');
        my ($list,$more)=list_cut($d,$all);
        return window_html($d->{title},$meta,gallery_html($list,$d->{layout}||'grid',$d->{captions},$d->{columns},tag_buttons=>$d->{tag_buttons}).$more,%o);
    }
    # Comments and sharing: the same likes, comments and share links that
    # library items have, for this page (the block's id is the item).
    if ($type eq 'talk') {
        my $item=item_find('page',$b->{id},all=>1) or return '';
        return item_engagement_html($item);
    }
    # Contact form: fills the {{name}} placeholders in contact_form_html with the
    # block's labels (escaped), and removes the subject field if it's not asked.
    if ($type eq 'contact_form') {
        my %ok=map {($_->[0]=>1)} button_colours();my $style=$ok{$d->{button_style}//''} ? $d->{button_style} : 'theme';
        my %fill=(%$d,button_class=>$style eq 'theme' ? 'form-submit' : "cta cta--$style",sent_message=>$d->{sent_message}//'');
        (my $form=contact_form_html()) =~ s/\{\{(\w+)\}\}/h($fill{$1}\/\/'')/ge;
        $form =~ s{\s*<div class="contact-field contact-field--subject">.*?</div>}{}s if defined $d->{subject} && !$d->{subject};
        return window_html($d->{title},$d->{subtitle},$form,%o);
    }
    if ($type eq 'music') {
        my $all=items('music');my $only=$d->{collection}//'';
        $all=[grep {$_->{collection} eq $only} @$all] if length $only;
        $all=tag_filter('music',$d->{tag},$all);
        my $meta=length($d->{subtitle}//'') ? $d->{subtitle} : @$all.' '.(@$all==1 ? 'track' : 'tracks');
        my ($list,$more)=list_cut($d,$all);
        return window_html($d->{title},$meta,music_list_html($list,!length $only,tag_buttons=>$d->{tag_buttons}).$more,%o);
    }
    if ($type eq 'download') {
        my $all=items('file');
        if (length($d->{file}//'')) {
            my ($one)=grep {$_->{id} eq $d->{file}} @$all;
            return $one ? window_html($d->{title},'',file_list_html([$one]),%o,nobar=>($o{nobar} || !length($d->{title}//''))) : '';
        }
        my $only=$d->{collection}//'';
        $all=[grep {$_->{collection} eq $only} @$all] if length $only;
        $all=tag_filter('file',$d->{tag},$all);
        my ($list,$more)=list_cut($d,$all);
        return window_html($d->{title},@$all.' '.(@$all==1 ? 'file' : 'files'),file_list_html($list,tag_buttons=>$d->{tag_buttons}).$more,%o);
    }
    if ($type eq 'videos') {
        my $all=items('video');my $only=$d->{collection}//'';
        $all=[grep {$_->{collection} eq $only} @$all] if length $only;
        $all=tag_filter('video',$d->{tag},$all);
        my $meta=length($d->{subtitle}//'') ? $d->{subtitle} : @$all.' '.(@$all==1?'video':'videos');
        my ($list,$more)=list_cut($d,$all);
        return window_html($d->{title},$meta,video_list_html($list,!length $only,tag_buttons=>$d->{tag_buttons}).$more,%o);
    }
    # Article list: published articles, newest first, while the Blog page is on.
    if ($type eq 'posts') {
        # Articles live at /blog/: with the Blog page off there's nothing to link to.
        my $posts=page_enabled('blog') ? $db->selectall_arrayref('SELECT id,title,body,published_at FROM posts WHERE published_at IS NOT NULL ORDER BY published_at DESC,id DESC',{Slice=>{}}) : [];
        $posts=tag_filter('blog',$d->{tag},$posts);
        splice @$posts,$d->{limit} if $d->{limit} && @$posts>$d->{limit};
        return window_html($d->{title},$d->{subtitle},post_list_html($posts,cards=>($d->{layout}//'') eq 'cards',date=>($d->{show_date}//1),excerpt=>$d->{show_excerpt}),%o);
    }
    # An add-on's block (nothing while the add-on is off).
    # Any other type is an add-on's: its own render function draws it. If that
    # fails, the block is left out rather than breaking the page.
    if (my $t=block_types()->{$type}) {return (attempt {$t->{render}->($b,%o)}) // '' if $t->{render}}
    return '';
}
# Full and half-width blocks: a run of half-width blocks becomes two columns,
# each stacking its blocks in order.
# Lays a page's blocks out. Sidebar blocks go in a column of their own
# beside everything else. Of the rest, full-width blocks are drawn one after
# another; a run of left/right blocks becomes two columns (grid-2), each
# stacking its own blocks in order.
sub render_blocks (@blocks) {
    # Sidebar blocks go in a column of their own beside the rest (render_page
    # passes the side as a leading "left:"/"right:" marker).
    my $side=!ref $blocks[0] ? shift @blocks : 'right';
    my @aside=grep {($_->{width}//'') eq 'side'} @blocks;
    if (@aside) {
        my $main=render_blocks($side,grep {($_->{width}//'') ne 'side'} @blocks);
        return '<div class="with-sidebar with-sidebar--'.($side eq 'left' ? 'left' : 'right').'"><div class="with-sidebar__main">'.$main.'</div><aside class="with-sidebar__side">'.join('',map {render_block($_)} @aside).'</aside></div>';
    }
    my $html='';my $i=0;
    while ($i<@blocks) {
        if (($blocks[$i]{width}//'full') eq 'full') {$html.=render_block($blocks[$i++]);next}
        my (@left,@right);
        while ($i<@blocks && ($blocks[$i]{width}//'full') ne 'full') {push @{$blocks[$i]{width} eq 'right' ? \@right : \@left},$blocks[$i];$i++}
        $html.='<div class="grid-2"><div>'.join('',map {render_block($_)} @left).'</div><div>'.join('',map {render_block($_)} @right).'</div></div>';
    }
    return $html;
}
# What start_page needs to know about a page: its title is complete, its
# description, and whether it has a Comments and sharing block (which needs
# talk.js and link-preview tags).
sub page_meta ($page,%extra) {
    my %types=map {($_->{type}=>1)} @{$page->{blocks}};
    return {full_title=>1,page=>$page,($types{talk} ? (talk=>1,og=>1) : ()),
        (length $page->{description} ? (description=>$page->{description}) : ()),%extra};
}
# Draws a whole public page: the head and menu, its blocks, the picture
# viewer if anything on it opens pictures larger, and the footer.
sub render_page ($page) {
    start_page($page->{title},$page->{path},200,page_meta($page));
    print render_blocks(page_style($page)->{sidebar},@{$page->{blocks}});
    print photo_viewer_html() if grep {$_->{type} eq 'gallery' || ($_->{type} eq 'picture' && $_->{data}{zoom})} @{$page->{blocks}};
    end_page();
}

# The contact form's markup. The text between <<'HTML' and HTML is the form
# itself (a "here document"); {{name}} marks are filled in by the contact_form
# block. The hidden "company" field is a trap for spam robots: people never
# see it, robots fill it in, and the server then ignores the message.
sub contact_form_html { return <<'HTML' =~ s/\n\z//r }
<form action="/contact/send" method="POST" class="contact-form">
  <input type="hidden" name="form_name" value="contact">
  <div class="contact-field honeypot" aria-hidden="true">
    <label for="contact-company">Company</label>
    <input type="text" id="contact-company" name="company" tabindex="-1" autocomplete="off">
  </div>
  <div class="contact-field">
    <label for="contact-name">{{label_name}}</label>
    <input type="text" id="contact-name" name="name" placeholder="Your name" autocomplete="name" maxlength="120" required>
  </div>
  <div class="contact-field">
    <label for="contact-email">{{label_email}}</label>
    <input type="email" id="contact-email" name="email" placeholder="your@email.com" autocomplete="email" maxlength="190" required>
  </div>
  <div class="contact-field contact-field--subject">
    <label for="contact-subject">{{label_subject}}</label>
    <input type="text" id="contact-subject" name="subject" placeholder="What's this about?" maxlength="160" required>
  </div>
  <div class="contact-field">
    <label for="contact-message">{{label_message}}</label>
    <textarea id="contact-message" name="message" placeholder="Write your message here..." maxlength="8000" required></textarea>
  </div>
  <p class="form-note" id="contact-status" role="status" aria-live="polite" data-sent="{{sent_message}}">{{note}}</p>
  <button type="submit" class="{{button_class}}">{{button}}</button>
</form>
HTML

# ---- Admin: page builder --------------------------------------------------
# Whether a page address (slug) may be used: 1-40 lowercase letters, digits
# and dashes, not starting or ending with a dash, not a reserved name (the
# site's own folders and addresses), and not a file or folder in public/.
sub slug_ok ($slug) {
    return 0 unless $slug =~ /\A[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?\z/;
    my %reserved=map {$_=>1} qw(admin media css js assets run cgi-bin index themes stats sitemap feed picture track video file download tags talk);
    return 0 if $reserved{$slug};
    # Folders and files in the public root (other than the original pages) are taken.
    return 0 if -e source_file("public/$slug") && !grep {$_ eq $slug} builtin_pages();
    return 1;
}
# Numbers in ascending order (sort compares as text otherwise).
sub numbers_sorted (@n) { return sort {$a <=> $b} @n }
# A list field (questions, timeline entries, cards): b.ID.NAME.N.SUB for each
# entry N, in N's order; entries left empty are dropped.
# Reads a list field (questions, timeline entries, cards) from the posted
# form. Each entry's sub-fields arrive as b.BLOCKID.FIELD.N.SUB; the entries
# are taken in the order of N, each sub-field checked by its kind, and
# entries left completely empty are dropped. At most 100.
sub block_items_value ($b,$f) {
    my ($name,$label,undef,$subs)=@$f;my $prefix="b.$b->{id}.$name.";
    my %n;for ($q->param) {$n{$1}=1 if /\A\Q$prefix\E(\d{1,3})\./}
    my @items;
    for my $i (numbers_sorted(keys %n)) {
        my %item;
        my $filled=0;
        for my $sf (@$subs) {
            my ($sn,$sl,$sk,$so)=@$sf;
            # Each sub-field read as its kind: a choice from its options, a tick box as 1 or 0.
            my $v=param("$prefix$i.$sn",$sk eq 'picture' ? 32 : $sk =~ /\A(?:text|markdown)\z/ ? $so : 300);
            $v =~ s/\r\n?/\n/g if $sk eq 'markdown';
            die "$label: a chosen picture is no longer in the library. Choose another.\n" if $sk eq 'picture' && length $v && !picture_by_id($v);
            if ($sk eq 'check') {$v=$v eq '1' ? 1 : 0}
            elsif ($sk eq 'select') {$v=$so->[0][0] unless grep {$_->[0] eq $v} @$so}
            else {$filled||=length $v}
            $item{$sn}=$v;
        }
        # An entry with nothing typed or chosen in it is left out.
        push @items,\%item if $filled;
    }
    die "$label: up to 100.\n" if @items>100;
    return \@items;
}
# Reads and checks one block setting from the posted form, by its kind: a
# select must be one of its options, a tick box is 1 or 0, a number must be
# in range, pictures, folders and library items must still exist. A bad value
# stops the save with a message naming the setting.
sub block_field_value ($b,$f) {
    my ($name,$label,$kind,$opt)=@$f;
    return block_items_value($b,$f) if $kind eq 'items';
    # A text's limit is its spec's fourth entry; one an add-on leaves out gets a sensible one.
    my $raw=param("b.$b->{id}.$name",$kind eq 'markdown' ? ($opt||20000) : $kind eq 'text' ? ($opt||300) : $kind eq 'pictures' ? 7000 : 300);
    if ($kind eq 'select') {die "$label: choose one of the options.\n" unless grep {$_->[0] eq $raw} @$opt; return $raw}
    if ($kind eq 'check') {return $raw eq '1' ? 1 : 0}
    if ($kind eq 'number') {$raw='0' unless length $raw;die "$label: enter a whole number from $opt->[0] to $opt->[1].\n" unless $raw =~ /\A\d{1,4}\z/ && $raw>=$opt->[0] && $raw<=$opt->[1];return 0+$raw}
    if ($kind eq 'picture') {die "$label: that picture is no longer in the library. Choose another.\n" unless $raw eq '' || picture_by_id($raw);return $raw}
    if ($kind eq 'pictures') {
        my @ids=grep {length} split /,/,$raw;
        die "$label: choose up to 200 pictures.\n" if @ids>200;
        for (@ids) {die "$label: a chosen picture is no longer in the library. Remove it and save again.\n" unless picture_by_id($_)}
        return join ',',@ids;
    }
    if ($kind eq 'folder') {die "$label: that folder no longer exists.\n" unless folder_ok($raw) && folder_exists($raw);return $raw}
    if ($kind =~ /\Aitem:(music|video|file)\z/) {my $k=$1;die "$label: that one is no longer in the library. Choose another.\n" unless $raw eq '' || $db->selectrow_array('SELECT count(*) FROM uploads WHERE kind=? AND id=?',undef,$k,$raw);return $raw}
    if ($kind =~ /\Acollection:(\w+)\z/) {my $k=$1;die "$label: choose a collection.\n" unless $raw eq '' || $db->selectrow_array('SELECT count(*) FROM uploads WHERE kind=? AND collection=?',undef,$k,$raw);return $raw}
    $raw =~ s/\r\n?/\n/g if $kind eq 'markdown';
    # An anchor typed as "#Pricing" or "our prices" is kept as pricing, our-prices.
    if ($name eq 'section_anchor') {$raw=lc $raw;$raw =~ s/\A#+//;$raw =~ s/[\s_]+/-/g}
    return $raw;
}
# The page builder's submitted settings and blocks, checked; nothing is saved.
# Reads the whole page editor form: the page's title, description, menu
# label, search engine and on/off choices, its layout choices, a new address
# if it was changed (not allowed for starter pages), and every block's
# settings and width. Everything is checked; nothing is saved here.
sub page_form_values ($page) {
    my %v=(title=>param('title',200),description=>param('description',300),nav_label=>param('nav_label',40),noindex=>(param('noindex',1) eq '1' ? 1 : 0),
        visible=>(defined $q->param('visible') ? (param('visible',1) eq '1' ? 1 : 0) : undef),
        menu=>(defined $q->param('menu') ? (param('menu',1) eq '1' ? 1 : 0) : undef));
    die "Enter a browser title.\n" unless length $v{title};
    die "Enter a navigation label.\n" unless length $v{nav_label};
    my $choices=style_choices();my %style;
    my $current=page_style($page);
    for my $key (keys %$choices) {my $s=param('style_'.$key,30);$s=$current->{$key} unless length $s;die "Choose a valid $key.\n" unless grep {$_ eq $s} @{$choices->{$key}};$style{$key}=$s}
    $v{slug}=$page->{slug};
    unless (grep {$_ eq $page->{slug}} builtin_pages()) {
        my $slug=param('slug',40);
        if ($slug ne $page->{slug}) {
            die "Address: use 1–40 lowercase letters, numbers and dashes (not a reserved name such as admin or css).\n" unless slug_ok($slug);
            die "Another page already uses /$slug/.\n" if page_by_slug($slug);
            $v{slug}=$slug;
        }
    }
    my @blocks;
    for my $b (@{$page->{blocks}}) {
        my $type=block_types()->{$b->{type}} or next;
        my %d=%{$b->{data}};
        $d{$_->[0]}=block_field_value($b,$_) for @{$type->{fields}};
        my $width=param("b.$b->{id}.width",10);
        die "Choose a width for each block.\n" unless grep {$_->[0] eq $width} widths();
        push @blocks,[$b->{id},$width,\%d];
    }
    # Anchors: usable names, each on one block only.
    my %anchor;
    for my $name (grep {length} map {$_->[2]{section_anchor}//''} @blocks) {
        die "Anchor “$name”: use 1–40 lowercase letters, numbers and dashes, starting with a letter (main, comments and names starting contact- are taken by the page).\n" unless anchor_ok($name);
        die "Anchor “$name” is on two blocks: give each its own.\n" if $anchor{$name}++;
    }
    return (\%v,\%style,\@blocks);
}
# The page as it would look with the submitted values (the builder's preview).
# The page as it would look with the form's values, without saving: what
# the editor's live preview draws.
sub page_from_form ($page) {
    my ($v,$style,$blocks)=page_form_values($page);
    my %by=map {($_->{id}=>$_)} @{$page->{blocks}};
    return {%$page,(map {($_=>$v->{$_})} qw(title description nav_label noindex)),style=>JSON::PP->new->canonical->encode($style),
        blocks=>[map {{%{$by{$_->[0]}},width=>$_->[1],data=>$_->[2]}} @$blocks]};
}
# Saves the page editor form in one transaction: the page row, every block,
# its on/off state and, if the address changed, its place in the navigation
# plus a redirect from the old address to the new one.
sub page_settings_save ($page) {
    my ($vr,$styler,$blocksr)=page_form_values($page);my %v=%$vr;my %style=%$styler;my @blocks=@$blocksr;
    $db->begin_work;
    attempt {
        $db->do('UPDATE pages SET slug=?,path=?,nav_label=?,title=?,description=?,noindex=?,style=?,updated_at=? WHERE slug=?',undef,
            $v{slug},($v{slug} eq 'home' ? '/' : "/$v{slug}/"),@v{qw(nav_label title description)},$v{noindex},JSON::PP->new->canonical->encode(\%style),now(),$page->{slug});
        $db->do('UPDATE page_blocks SET width=?,data=?,page=? WHERE id=?',undef,$_->[1],JSON::PP->new->canonical->encode($_->[2]),$v{slug},$_->[0]) for @blocks;
        if (defined $v{visible} && $page->{slug} ne 'home') {
            save_nav(map {$_->{page} eq $page->{slug} ? {%$_,visible=>$v{visible}} : $_} nav_items());
        }
        if (defined $v{menu}) {
            save_nav(map {$_->{page} eq $page->{slug} ? {%$_,menu=>$v{menu}} : $_} nav_items());
        }
        if ($v{slug} ne $page->{slug}) {
            save_nav(map {$_->{page} eq $page->{slug} ? {%$_,page=>$v{slug}} : $_} nav_items());
            # The old address keeps working: it redirects to the new one.
            redirect_record($page->{path},"/$v{slug}/");
        }
        $db->commit;1;
    } or do {my $e=$@;$db->rollback;die $e};
    reset_page_cache();
    addon_pages_claim() if $v{slug} ne $page->{slug};
    return $v{slug};
}
# The settings a new block of a type starts with: its own defaults, else the
# first option of a select, 0 for numbers and tick boxes, an empty list for
# list fields, and '' for the rest.
sub block_defaults_of ($t) { return {map {($_->[0]=>$t->{defaults}{$_->[0]} // ($_->[2] eq 'select' ? $_->[3][0][0] : $_->[2] eq 'number' || $_->[2] eq 'check' ? 0 : $_->[2] eq 'items' ? [] : ''))} @{$t->{fields}//[]}} }
sub block_defaults ($type) { return block_defaults_of(block_types()->{$type}) }
# Adds a block at the bottom of a page, refusing a second "once" block. Its
# id is 16 random hex characters.
sub block_add ($page,$type,$width,$data=undef) {
    my $t=block_types()->{$type} or die "Choose a block type.\n";
    die "Choose a width.\n" unless grep {$_->[0] eq $width} widths();
    die "A page can have one $t->{label} block.\n" if $t->{once} && grep {$_->{type} eq $type} @{$page->{blocks}};
    my $id=substr(random_id(),0,16);
    my $order=1+($db->selectrow_array('SELECT max(sort_order) FROM page_blocks WHERE page=?',undef,$page->{slug})//-1);
    $db->do('INSERT INTO page_blocks (id,page,sort_order,type,width,data) VALUES (?,?,?,?,?,?)',undef,$id,$page->{slug},$order,$type,$width,JSON::PP->new->canonical->encode($data//block_defaults($type)));
    $db->do('UPDATE pages SET updated_at=? WHERE slug=?',undef,now(),$page->{slug});
    reset_page_cache();
    return $id;
}
# Makes a new page: works out an address from the name if none was given,
# checks it, stores the page with one introduction text panel, forgets any
# redirect that used to start at this address, and adds it to the navigation
# switched off. Then add-ons may claim it (addon_pages_claim), if its
# address is one an add-on owns.
sub page_create ($label,$slug) {
    die "Enter a name for the page.\n" unless length $label;
    unless (length $slug) {($slug=lc NFKC($label)) =~ s/[^a-z0-9]+/-/g;$slug =~ s/\A-+|-+\z//g;$slug=substr($slug,0,40) =~ s/-+\z//r}
    die "Address: use 1–40 lowercase letters, numbers and dashes (not a reserved name such as admin or css).\n" unless slug_ok($slug);
    die "A page already uses /$slug/.\n" if page_by_slug($slug);
    $db->begin_work;
    attempt {
        $db->do('INSERT INTO pages (slug,path,nav_label,title,description,style,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)',undef,
            $slug,"/$slug/",lc $label,"$label | ".setting('site_title'),'','{}',now(),now());
        reset_page_cache();
        redirect_forget_from("/$slug/");
        block_add(page_by_slug($slug),'text','full',{%{block_defaults('text')},title=>lc $label,heading=>$label,style=>'intro',body=>'Write something here.'});
        # New pages start switched off so they can be built first.
        save_nav(nav_items(),{page=>$slug,visible=>0});
        $db->commit;1;
    } or do {my $e=$@;$db->rollback;reset_page_cache();die $e};
    reset_page_cache();
    addon_pages_claim();
    return $slug;
}

# The Markdown help beside the admin's Markdown boxes (the page editor's bar,
# the article editor): each way of writing something next to what it
# becomes, drawn by render_markdown itself so the two can't drift apart.
# It's a <details>, so it works without the script; the toolbar's "?" opens it.
# %o: class (the <details>' classes), note (one more line at its foot).
sub markdown_help_html (%o) {
    my @rows=(
        ['**bold**, *italic*, ~~struck~~','emphasis; select words and press B or I'],
        ['[a link](/contact/ "Shown on hover")','a link to a page, a #name on one, or another site; the title is optional'],
        ['https://example.org/','an address on its own is a link'],
        ["### A heading {#prices}",'## large, ### smaller; {#name} lets a link jump to it: /page/#prices'],
        ["- one\n  - inside it\n- two",'a list: Enter carries it on, Tab moves an item in'],
        ["1. first\n2. second",'a numbered list'],
        ["- [x] done\n- [ ] to do",'tick boxes'],
        ['> Quoted words','a quotation'],
        ['`code`','code in a line; a block of code goes between two lines of ```'],
        ["| Plan | Price |\n|:-----|------:|\n| Basic | 10 |",'a table: :--- left, :---: centred, ---: right'],
        ["A claim[^1]\n\n[^1]: The source.",'a footnote: its note is listed at the end'],
        ["First line\\\nsecond line",'a line break inside a paragraph'],
        # The page tools (also in the toolbar's "more…" menu).
        ["> [!NOTE]\n> Something worth knowing.",'a callout box: NOTE, TIP, IMPORTANT, WARNING or CAUTION, and a title after it if you like'],
        ['[Book a repair](/contact/){.button}','a button; add .outline, .soft, .dark, .light or .theme for its colour, .small or .large, .full for the whole width'],
        ["+++ What does it cost?\nTen a month.\n+++",'a fold-out: the line after +++ shows; the rest opens from it'],
        ["::: center lead\nWelcome in.\n:::",'a container: center, right, lead (larger), small, muted, box, soft, accent, dark or light, as many as you like'],
        ["::: columns\nLeft side.\n|||\nRight side.\n:::",'columns (up to four, split by |||), side by side on wide screens'],
        ["Hosting\n: Your site, kept running.",'a definition (one term, then lines starting with :)'],
        ['==highlight==, H~2~O, x^2^, [[Ctrl]]','highlighted, below and above the line, a key'],
        ["```perl\nmy \$name = 'world'; # who\nsay \"Hello, \$name\";\n```",'code coloured by its language: perl, sh, python, js, c, go, rust, java, css, html, json, yaml, ini, toml, make, diff or markdown'],
        ['![A caption](/video/…/)','a library video, track or file on its own line: its player or download, the caption under it. Choose one with the library button',
            'the video’s player (a track’s player alone, or the file’s download), with “A caption” under it'],
        ['![A description](/media/pictures/… "A caption"){.small .right}','a picture on its own line, with a caption; .small or .medium, .left, .right or .center, .round. Choose one with the picture button',
            'the picture, small, on the right, with “A caption” under it'],
    );
    return '<details class="'.h($o{class}//'md-help').'" id="md-help"><summary>Markdown help</summary><table class="md-help__table"><thead><tr><th scope="col">Write</th><th scope="col">Shows</th></tr></thead><tbody>'
        .join('',map {'<tr><td><pre>'.h($_->[0]).'</pre><span class="optional">'.h($_->[1]).'</span></td><td class="md-help__out">'.(defined $_->[2] ? '<span class="optional">'.h($_->[2]).'</span>' : render_markdown($_->[0])).'</td></tr>'} @rows)
        .'</tbody></table><p class="optional">Leave a blank line between paragraphs. HTML is shown as text, never run.'.(length($o{note}//'') ? ' '.h($o{note}) : '').'</p></details>'
        .markdown_library_json();
}
# The libraries the toolbar's "library" dialog offers, as JSON in a data
# block (not a script: the security policy runs none inline), in the
# libraries' order: each is {ref, label, one, items: [{id, title, note}]},
# ref the first word of an item's address (/video/ID/), note its collection.
# Pictures come first and carry no items: the dialog opens the picture
# chooser for them, in boxes that take pictures. Every library a text can
# embed (markdown_embed_kinds) is offered once it has something in it.
sub markdown_library_json {
    my $embeds=markdown_embed_kinds();my %ref_of=map {($embeds->{$_}{kind}=>$_)} keys %$embeds;
    my @list=({ref=>'picture',label=>library_spec('photography')->{title},one=>library_spec('photography')->{one},items=>[]});
    for my $kind (grep {$ref_of{$_}} library_kinds()) {
        my @items=map {{id=>$_->{id},title=>$_->{title}//'',note=>$_->{collection}//''}} @{items($kind)} or next;
        push @list,{ref=>$ref_of{$kind},label=>library_spec($kind)->{title},one=>library_spec($kind)->{one},items=>\@items};
    }
    my $json=JSON::PP->new->canonical->encode(\@list) =~ s/</\\u003c/gr =~ s/>/\\u003e/gr =~ s/&/\\u0026/gr;
    return '<script type="application/json" id="md-library">'.$json.'</script>';
}
# The editor's input for one block setting, by its kind (tick box, text
# area, number, picture chooser, picture list, folder menu, library item
# menu, list of entries, select or text). Every input says form="bulk-edit",
# so they all belong to the page's one save form wherever they are on the
# screen. A tick box is followed by a hidden 0, so an unticked box still
# sends a value.
sub field_html ($b,$f) {
    my ($name,$label,$kind,$opt,$hint)=@$f;my $id="b.$b->{id}.$name";my $v=$b->{data}{$name}//'';
    my $hintx=$hint ? '<span class="optional">'.h($hint).'</span>' : '';
    if ($kind eq 'check') {return switch_field($id,$label,$v,form=>'bulk-edit',hint=>$hint//'')}
    # data-markdown: admin.js gives it the Markdown toolbar and shortcuts (with a picture button).
    if ($kind eq 'markdown') {return '<label class="block-wide">'.h($label).$hintx.'<textarea name="'.h($id).'" rows="'.($v =~ tr/\n// > 6 ? 12 : 6).'" maxlength="'.$opt.'" form="bulk-edit" data-markdown="pictures">'.h($v).'</textarea></label>'}
    if ($kind eq 'number') {return '<label>'.h($label).'<input type="number" name="'.h($id).'" min="'.$opt->[0].'" max="'.$opt->[1].'" value="'.h($v).'" form="bulk-edit">'.$hintx.'</label>'}
    if ($kind eq 'picture') {
        # The chosen picture's id, set by the picture chooser (admin.js).
        my $p=picture_by_id($v);
        return '<div class="picture-field" data-picture-field><span class="picture-field__label">'.h($label).'</span><input type="hidden" name="'.h($id).'" value="'.h($p ? $v : '').'" form="bulk-edit">'
            .'<div class="picture-field__preview">'.($p ? '<img src="'.h(picture_url($p,1)).'" alt=""><span>'.h($p->{title}).'</span>' : '<span class="optional">No picture chosen.</span>').'</div>'
            .'<button type="button" class="buttonlike" data-choose-picture>'.($p ? 'change picture' : 'choose picture').'</button> <button type="button" class="text-button" data-clear-picture'.($p ? '' : ' hidden').'>remove</button></div>';
    }
    if ($kind eq 'pictures') {
        my @chosen=grep {defined} map {picture_by_id($_)} grep {length} split /,/,$v;
        return '<div class="picture-field picture-field--many block-wide" data-pictures-field><span class="picture-field__label">'.h($label).$hintx.'</span><input type="hidden" name="'.h($id).'" value="'.h(join ',',map {$_->{id}} @chosen).'" form="bulk-edit">'
            .'<ol class="picture-list">'.join('',map {'<li data-id="'.h($_->{id}).'"><img src="'.h(picture_url($_,1)).'" alt="" title="'.h($_->{title}).'"><span class="picture-list__tools"><button type="button" class="text-button" data-move="-1" aria-label="Move '.h($_->{title}).' earlier">←</button><button type="button" class="text-button" data-move="1" aria-label="Move '.h($_->{title}).' later">→</button><button type="button" class="text-button danger" data-remove aria-label="Remove '.h($_->{title}).'">×</button></span></li>'} @chosen).'</ol>'
            .'<button type="button" class="buttonlike" data-add-pictures>add pictures</button></div>';
    }
    if ($kind eq 'folder') {return '<label>'.h($label).'<select name="'.h($id).'" form="bulk-edit">'.folder_select_options($v).'</select>'.$hintx.'</label>'}
    if ($kind =~ /\Aitem:(music|video|file)\z/) {
        my $list=$db->selectall_arrayref('SELECT id,title,collection FROM uploads WHERE kind=? ORDER BY collection,sort_order,created_at DESC',{Slice=>{}},$1);
        return '<label>'.h($label).'<select name="'.h($id).'" form="bulk-edit"><option value="">Choose one…</option>'.join('',map {'<option value="'.h($_->{id}).'"'.($_->{id} eq $v ? ' selected' : '').'>'.h($_->{title}.(length $_->{collection} ? " ($_->{collection})" : '')).'</option>'} @$list).'</select>'
            .(@$list ? $hintx : '<span class="optional">The library is empty: upload one first.</span>').'</label>';
    }
    # A list field: one row per entry (each with its own sub-fields), one empty
    # row to type a new entry into, and a <template> admin.js copies for "add".
    # $one is the label made singular ("Questions" -> "question", "Entries" ->
    # "entry") for the "add" button.
    if ($kind eq 'items') {
        # One fieldset per entry, plus a template the page script copies for "add".
        my $one=lc($label) =~ s/ies\z/y/r =~ s/(?<!y)s\z//r;
        my $entry=sub ($i,$item) {
            my $fake={id=>"$b->{id}.$name.$i",data=>$item};
            return '<li class="items-field__item">'.drag_handle().'<div class="items-field__fields">'.join('',map {field_html($fake,$_)} @$opt).'</div>'
                .'<span class="items-field__tools"><button type="button" class="text-button" data-item-move="-1" aria-label="Move up">↑</button><button type="button" class="text-button" data-item-move="1" aria-label="Move down">↓</button><button type="button" class="text-button danger" data-item-remove>remove</button></span></li>';
        };
        my @items=ref $v eq 'ARRAY' ? @$v : ();
        my $i=0;
        return '<div class="items-field block-wide" data-items-field><span class="picture-field__label">'.h($label).($hintx ? " $hintx" : '').'</span><ol class="items-field__list">'
            .join('',map {$entry->($i++,$_)} @items).$entry->($i,{}).'</ol>'
            .'<template data-items-template>'.$entry->('__N__',{}).'</template><button type="button" class="buttonlike" data-items-add>add '.h($one).'</button></div>';
    }
    my @options=$kind eq 'select' ? @$opt : ();
    if ($kind =~ /\Acollection:(\w+)\z/) {@options=([''=>'Everything'],map {[$_=>"Collection: $_"]} @{$db->selectcol_arrayref("SELECT DISTINCT collection FROM uploads WHERE kind=? AND collection<>'' ORDER BY collection",undef,$1)})}
    if (@options) {return '<label>'.h($label).'<select name="'.h($id).'" form="bulk-edit">'.join('',map {'<option value="'.h($_->[0]).'"'.($_->[0] eq $v?' selected':'').'>'.h($_->[1]).'</option>'} @options).'</select>'.$hintx.'</label>'}
    return '<label>'.h($label).'<input name="'.h($id).'" value="'.h($v).'" maxlength="'.$opt.'" form="bulk-edit">'.$hintx.'</label>';
}
# Settings that only matter once another is filled in: "open in a new tab"
# once there's a link, a button's link and colour once it has text, "See
# all" once the list is limited, and a picture's position, size, shape,
# focus, description and caption once one is chosen (and the Picture
# block's size, alignment, link and zoom). Returns the setting it depends on,
# or ''. admin.js hides them until then; without the script they all show.
sub field_depends ($t,$type,$name) {
    my %has=map {($_->[0]=>$_->[2])} @{$t->{fields}//[]};
    return $1 if $name =~ /\A(.+)_newtab\z/ && $has{$1};
    return $1 if $name =~ /\A(button2?)_(?:link|style)\z/ && $has{$1};
    return 'limit' if $name eq 'more_link' && $has{limit};
    return '' unless ($has{picture}//'') eq 'picture';
    return 'picture' if $name =~ /\A(?:position|picture_size|picture_shape|picture_focus|alt|caption)\z/;
    return 'picture' if $type eq 'picture_text' && $name eq 'link';
    return 'picture' if $type eq 'picture' && $name =~ /\A(?:size|align|link|zoom)\z/;
    return '';
}
# A block's settings card in the editor: its note, its settings, its width,
# the section style folded away, and a link to the library it draws from.
sub block_card_html ($page,$b,$n,$count) {
    my $t=block_types()->{$b->{type}};my $id=$b->{id};
    # A block from an add-on that's switched off: kept, but hidden on the page.
    $t //= {label=>'Block from an add-on that’s off',fields=>[],note=>'Not shown on the page. Switch its add-on on again under Add-ons, or remove the block.'};
    # The card the editor opens beside the block: everything about it that isn't
    # edited on the page itself is here too, so nothing needs the canvas.
    my $html='<article class="block-card pe-fields admin-form" id="block-'.h($id).'" data-pe-fields="'.h($id).'" aria-label="'.h($t->{label}).' block settings">'
        .'<header class="pe-fields__head"><span class="block-card__n">'.$n.'</span> <strong>'.h($t->{label}).'</strong>'.(length($b->{data}{title}//'') ? ' · '.h($b->{data}{title}) : '')
        .'<button type="button" class="text-button pe-fields__close" data-pe-close aria-label="Close">×</button></header><div class="block-card__fields">';
    $html.='<p class="panel-note">'.h($t->{note}).'</p>' if $t->{note};
    my @style=grep {$_->[0] =~ /\Asection_|\Aprint_hide\z/} @{$t->{fields}};
    for my $f (grep {$_->[0] !~ /\Asection_|\Aprint_hide\z/} @{$t->{fields}}) {
        my $field=field_html($b,$f);
        if (length(my $on=field_depends($t,$b->{type},$f->[0]))) {$field =~ s/\A(<[a-z]+)/$1.' data-show-when="'.h("b.$id.$on").'"'/e}
        $html.=$field;
    }
    $html.='<label>Width<select name="b.'.h($id).'.width" form="bulk-edit">'.join('',map {'<option value="'.$_->[0].'"'.($_->[0] eq ($b->{width}//'full')?' selected':'').'>'.h($_->[1]).'</option>'} widths()).'</select></label>';
    $html.='<details class="block-style block-wide"><summary>Section style <span class="optional">anchor, background, picture, spacing, title bar, printing</span></summary><div class="block-style__fields">'.join('',map {field_html($b,$_)} @style).'</div></details>' if @style;
    $html.='</div>';
    $html.='<div class="block-card__actions"><a class="buttonlike" href="/admin/?kind='.$t->{manage}[0].'">'.h($t->{manage}[1]).'</a></div>' if $t->{manage};
    return $html.'</article>';
}
# Deletes a page and its blocks (the library items its blocks show stay).
# Deletes a page and its blocks, takes it out of the navigation and drops
# redirects that pointed to it. Home can't be deleted.
sub page_remove ($page) {
    die "The ".$page->{nav_label}." page can't be deleted: every site needs a homepage. You can change or remove its blocks instead.\n" if fixed_page($page->{slug});
    $db->begin_work;
    attempt {
        $db->do('DELETE FROM page_blocks WHERE page=?',undef,$page->{slug});
        $db->do('DELETE FROM pages WHERE slug=?',undef,$page->{slug});
        save_nav(grep {$_->{page} ne $page->{slug}} nav_items());
        redirect_forget_to($page->{path});
        $db->commit;1;
    } or do {my $e=$@;$db->rollback;die $e};
    reset_page_cache();
}
# The warning shown before deleting a page.
sub page_delete_note ($slug) {
    return $slug eq 'blog'
        ? 'Deletes this page and its blocks. Your articles stay in the Articles library, but they won’t be public until a page at /blog/ exists again.'
        : 'Deletes this page and its blocks. Pictures, music, articles and links stay in their libraries.';
}
# The page editor. %o: page (a page, not from the address), section and
# crumbs (when it's shown on an add-on's Page tab).
# The page editor (/admin/?kind=page&page=SLUG). First the actions it
# receives:
#   page_save        save everything (JSON for admin.js, or a redirect)
#   page_preview     the page drawn with the unsaved values, as HTML for the
#                    preview frame (with edit=1, marked for in-place editing)
#   block_add        add a block, then open it
#   addon_blocks_add give an add-on's page its blocks back
#   order / move     the blocks' order (list_order)
#   block_delete
#   page_delete
# Then the screen: the hidden save form (#bulk-edit), the page itself in a
# preview frame (filled by admin.js), and the bar beside it with the page
# switcher, the list of blocks, "add a block", and the page's layout, search
# and address settings. Each block's settings card is printed after it.
sub page_builder_admin (%o) {
    my $slug=$o{page} ? $o{page}{slug} : param('page',40);my $message=param('notice',2000);
    my $page=$o{page} // page_by_slug($slug) or do {admin_page('Page not found',section=>'pages',status=>404,crumbs=>[['Pages','/admin/?kind=pages']]);window('not found','<p>That page no longer exists. <a href="/admin/?kind=pages">All pages</a></p>');end_page();return};
    # Where this editor is shown: under Pages (any page, an add-on's too), or
    # on an add-on's Page tab (x-NAME-page). Its forms post to kind=page and
    # carry the tab as "tab", so every action comes back to where it started.
    my $tab=($o{section}//'') =~ /\Ax-[a-z][a-z0-9]{1,19}-page\z/ ? $o{section} : param('tab',30);
    $tab='' unless $tab =~ /\Ax-[a-z][a-z0-9]{1,19}-page\z/;
    my $here=hidden(page=>$page->{slug},(length $tab ? (tab=>$tab) : ()));
    my $fetch=($ENV{HTTP_X_REQUESTED_WITH}//'') eq 'fetch';
    if ($method eq 'POST') {
        my $action=param('action',30);
        attempt {
            my $back=length $tab ? "/admin/?kind=$tab" : '/admin/?kind=page&page='.CGI::escape($page->{slug});
            if ($action eq 'page_save') {
                my $new=page_settings_save($page);
                json_response({ok=>JSON::PP::true,message=>'Page saved.'.($new ne $page->{slug} ? " Its address is now /$new/." : ''),address=>page_by_slug($new)->{path}}) if $fetch;
                redirect((length $tab ? "/admin/?kind=$tab" : '/admin/?kind=page&page='.CGI::escape($new)).'&notice=Page%20saved.');
            }
            if ($action eq 'page_preview') {
                my $preview=page_from_form($page);
                my $edit=param('edit',1) eq '1';
                my $html=do {local $edit_canvas=$edit;public_preview(sub {render_page($preview)})};
                $html =~ s{</head>}{<link rel="stylesheet" href="/css/page-canvas.css?v=2"></head>} if $edit;
                json_response({ok=>JSON::PP::true,html=>$html});
            }
            if ($action eq 'block_add') {
                my $id=block_add($page,param('type',20),param('width',10));
                redirect($back.'&open='.$id.'&notice=Block%20added.#block-'.$id);
            }
            if ($action eq 'addon_blocks_add') {
                my $n=addon_page_blocks_add($page) or die "This page already has its add-on’s blocks.\n";
                redirect($back.'&notice='.CGI::escape("Added $n ".($n==1 ? 'block' : 'blocks').' at the end of the page.'));
            }
            list_order(ids=>[map {$_->{id}} @{$page->{blocks}}],back=>sub ($id) {$back.'&open='.$id.'#block-'.$id},
                save=>sub (@ids) {sort_order_save($db,'page_blocks','id',@ids);$db->do('UPDATE pages SET updated_at=? WHERE slug=?',undef,now(),$page->{slug});reset_page_cache()});
            my $id=param('id',32);my ($index)=grep {$page->{blocks}[$_]{id} eq $id} 0..$#{$page->{blocks}};
            if ($action eq 'block_delete') {
                die "That block no longer exists. Reload the page.\n" unless defined $index;
                my @ids=map {$_->{id}} @{$page->{blocks}};splice @ids,$index,1;
                $db->do('DELETE FROM page_blocks WHERE id=?',undef,$id);sort_order_save($db,'page_blocks','id',@ids);
                $db->do('UPDATE pages SET updated_at=? WHERE slug=?',undef,now(),$page->{slug});
                redirect($back.'&notice=Block%20removed.');
            }
            if ($action eq 'page_delete') {
                page_remove($page);
                redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8','Deleted the '.$page->{nav_label}.' page.')));
            }
            die "Choose an action.\n";
        } or do {
            $message=failed_action($@);
            json_response({ok=>JSON::PP::false,message=>$message},400) if $fetch;
            reset_page_cache();$page=page_by_slug($page->{slug});
        };
    }
    my $builtin=grep {$_ eq $page->{slug}} builtin_pages();
    my ($nav)=grep {$_->{page} eq $page->{slug}} nav_items();my $on=$page->{slug} eq 'home' || ($nav && $nav->{visible});
    admin_page(ucfirst $page->{nav_label},section=>$o{section}//'pages',crumbs=>$o{crumbs}//[['Pages','/admin/?kind=pages']],notice=>$message,save=>['save','All changes saved'],
        intro=>($on ? 'On, at <a href="'.h($page->{path}).'" target="_blank" rel="noopener">'.h($page->{path}).' ↗</a>.' : 'Off: visitors get “not found” at '.h($page->{path}).'. Turn it on under Address, menu &amp; on/off.').' Click any text on the page to change it; click a block for its other settings.',
        class=>'is-page-editor');
    print '<form id="bulk-edit" method="post" action="/admin/" class="admin-form">'.fields('page_save','page').$here.'</form>';
    my $n=0;my $count=@{$page->{blocks}};
    # Each block is a button: clicking one adds it (at the bottom, at the width chosen above).
    my $add='<form method="post" action="/admin/" class="admin-form page-add">'.fields('block_add','page').$here
        .'<div class="page-add__head"><label>Width of the new block<select name="width">'.join('',map {'<option value="'.$_->[0].'">'.h($_->[1]).'</option>'} widths()).'</select></label><p class="media-label">Click a block to add it at the bottom of the page.</p></div>';
    for my $g (block_groups()) {
        my @types=grep {(block_types()->{$_}{group}//'addons') eq $g->[0]} block_type_names();
        next unless @types;
        $add.='<fieldset class="block-choices"><legend>'.h($g->[1]).'</legend>';
        for my $type (@types) {
            my $t=block_types()->{$type};my $taken=$t->{once} && grep {$_->{type} eq $type} @{$page->{blocks}};
            my $about=$t->{about} // block_about()->{$type} // '';
            $add.='<button type="submit" class="block-choice'.($taken ? ' is-taken' : '').'" name="type" value="'.h($type).'"'.($taken ? ' disabled' : '').' title="'.h($taken ? '' : 'Add a '.lc($t->{label}).' block').'"><span class="block-choice__name">'.h($t->{label}).'</span><span class="block-choice__about">'.h($taken ? 'Already on this page (one per page).' : $about).'</span></button>';
        }
        $add.='</fieldset>';
    }
    $add.='</form>';
    my $style=page_style($page->{slug});my $labels=style_labels();
    my $l='<div class="admin-form page-settings"><div class="theme-editor__grid">';
    for my $key (qw(width sidebar layout spacing font size align)) {
        $l.='<label>'.h($labels->{$key}[0]).'<select name="style_'.$key.'" form="bulk-edit">'.join('',map {'<option value="'.$_.'"'.($_ eq $style->{$key} ? ' selected' : '').'>'.h($labels->{$key}[1]{$_}).'</option>'} @{style_choices()->{$key}}).'</select>'
            .($key eq 'sidebar' ? '<span class="optional">For blocks whose width is “Sidebar”.</span>' : '').'</label>';
    }
    $l.='</div>';
    $l.='<p class="media-label">Each block also has a width (full, two columns side by side, or the sidebar) and a section style (background, picture, spacing), in the block itself. A <strong>Hero header</strong> block makes a wide band for the top of the page.</p></div>';
    my $se='<div class="admin-form page-settings"><label>Browser title<input name="title" value="'.h($page->{title}).'" maxlength="200" required form="bulk-edit"><span class="optional">In browser tabs and search results; about 60 characters show.</span></label>'
        .'<label>Search description<input name="description" value="'.h($page->{description}).'" maxlength="300" form="bulk-edit"><span class="optional">Optional; shown by search engines and link previews (about 155 characters show).</span></label>'
        .switch_field('noindex','Hide this page from search engines',$page->{noindex},form=>'bulk-edit').'</div>';
    my $am='<div class="admin-form page-settings"><div class="theme-editor__grid"><label>Navigation label<input name="nav_label" value="'.h($page->{nav_label}).'" maxlength="40" required form="bulk-edit"><span class="optional">The word in the navigation bar.</span></label>'
        .($builtin ? '<label>Address<input value="'.h($page->{path}).'" disabled><span class="optional">A starter page’s address stays.</span></label>' : '<label>Address<input name="slug" value="'.h($page->{slug}).'" maxlength="40" pattern="[a-z0-9][a-z0-9-]*" required form="bulk-edit"><span class="optional">'.h($instance{domain}).'/<b>address</b>/. The old address forwards to a new one.</span></label>').'</div>'
        .($page->{slug} eq 'home' ? '<p class="media-label">Home is always on.</p>'
            : switch_field('visible','On: open to visitors',$on,form=>'bulk-edit',hint=>'Off, its address answers “not found”; you can still edit and preview it.'))
        .switch_field('menu','In the navigation menu',!$nav || $nav->{menu},form=>'bulk-edit',hint=>'Off for a page that’s on but only reached through links (a landing page, say).').'</div>';
    unless (fixed_page($page->{slug})) {
        $am.='<div class="box-part"><h3>Delete this page</h3><form method="post" action="/admin/" class="delete-form" data-confirm="'.h('Delete the '.$page->{nav_label}.' page? This cannot be undone.').'">'.fields('page_delete','page').$here.'<p>'.page_delete_note($page->{slug}).'</p><button class="buttonlike danger" type="submit">delete this page</button></form></div>';
    }
    # The page, drawn as visitors see it and edited in place (the canvas);
    # the bar beside it lists the blocks and holds the page's settings; each
    # block's other settings are a card opened beside it. Without the admin
    # script the cards are simply shown one after another.
    # Every page, for the switcher at the top of the bar and for the
    # preview's links: a link to one of these addresses opens it here.
    my %shown=map {($_->{page}=>$_->{visible})} nav_items();
    my @all=@{all_pages()};
    my %paths=map {($_->{path}=>$_->{slug})} @all;
    my $switch='<form method="get" action="/admin/" class="admin-form pe-switch" data-pe-switch>'.hidden(kind=>'page')
        .'<label>Editing<select name="page">'.join('',map {'<option value="'.h($_->{slug}).'"'.($_->{slug} eq $page->{slug} ? ' selected' : '').'>'.h($_->{nav_label}).($_->{slug} eq 'home' || $shown{$_->{slug}} ? '' : ' (off)').'</option>'} @all).'</select></label>'
        .'<button type="submit" class="buttonlike">open</button><a class="text-button" href="/admin/?kind=pages#new-page">new page</a></form>';
    print '<div class="pe" data-page-editor data-pe-pages="'.h(JSON::PP->new->canonical->encode(\%paths)).'">';
    print '<div class="pe-canvas"><div class="preview-frame" data-pe-preview></div><noscript><p class="panel-note">The page preview needs JavaScript; the blocks’ settings are below.</p></noscript></div>';
    my $i=0;
    my $list=join '',map {
        my $b=$_;my $t=block_types()->{$b->{type}} // {label=>'Block from an add-on that’s off'};$i++;
        '<li class="pe-list__item" data-pe-item="'.h($b->{id}).'"'.order_row_attrs($b->{id}).'>'.drag_handle().'<button type="button" class="pe-item" data-pe-select="'.h($b->{id}).'"><span class="pe-item__n">'.$i.'</span><span class="pe-item__name">'.h($t->{label}).(length($b->{data}{title}//'') ? '<small>'.h($b->{data}{title}).'</small>' : '').'</span></button>'
        .'<span class="pe-item__tools">'.move_buttons('page',$b->{id},$i,$count,compact=>1,label=>'this '.lc($t->{label}).' block',post=>{page=>$page->{slug},(length $tab ? (tab=>$tab) : ())})
        .'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h('Remove this '.lc($t->{label}).' block?').'">'.fields('block_delete','page',$b->{id}).$here.'<button class="text-button danger" aria-label="Remove block '.$i.'" title="Remove">×</button></form></span></li>'
    } @{$page->{blocks}};
    # An add-on's page, edited under Pages: where its own content is managed.
    if (!length $tab && length($page->{addon}//'') && addon_enabled($page->{addon})) {
        my ($g)=grep {$_->{name} eq $page->{addon}} attempt {addon_admin_sections()};
        my ($own)=grep {$_->[0] ne "x-$page->{addon}-page"} @{$g ? $g->{screens} : []};
        $switch.='<p class="panel-note pe-addon-note">This is '.h($g ? $g->{label} : $page->{addon}).'’s page'
            .($own ? '; what it shows is managed on <a href="'.h($own->[2]).'">its '.h($g->{label}).' screen</a>' : '').'.</p>';
    }
    # An add-on's page made before the add-on (or emptied) can get its blocks back.
    my $missing=addon_page_blocks_missing($page);
    $switch.='<div class="panel-note pe-addon-blocks"><p>This page has none of '.h($missing).'’s blocks yet.</p><form method="post" action="/admin/">'.fields('addon_blocks_add','page').$here
        .'<button class="buttonlike is-primary" type="submit">add '.h($missing).'’s blocks</button></form></div>' if length $missing;
    print '<aside class="pe-bar" aria-label="Blocks and page settings">'.$switch
        .'<h2 class="pe-bar__title">Blocks <span class="media-label">'.$count.'</span></h2>'
        .($count ? '<ol class="pe-list"'.order_list_attrs('page',page=>$page->{slug},(length $tab ? (tab=>$tab) : ())).'>'.$list.'</ol>' : '<p class="empty-media">No blocks yet. Add one below.</p>')
        .'<details class="pe-fold pe-add"'.($count ? '' : ' open').'><summary>Add a block</summary>'.$add.'</details>'
        .'<details class="pe-fold pe-page" data-tab-panel="layout" id="tab-layout"><summary>Layout</summary>'.$l.'</details>'
        .'<details class="pe-fold pe-page" data-tab-panel="search" id="tab-search"><summary>Search engines</summary>'.$se.'</details>'
        .'<details class="pe-fold pe-page" data-tab-panel="address" id="tab-address"'.(($BlowfishCMS::admin_failed && param('action',30) eq 'page_delete') ? ' open' : '').'><summary>Address, menu &amp; on/off</summary>'.$am.'</details>'
        .markdown_help_html(class=>'pe-fold md-help')
        .'</aside>';
    $n=0;
    print '<div class="pe-panels">'.join('',map {block_card_html($page,$_,++$n,$count)} @{$page->{blocks}}).'</div>';
    print '</div>';
    end_page();
}

1;

# A block's data, decoded from its JSON when first read (and kept); a new
# value can be stored over it as with any hash element.
# How the lazy decoding works: Perl's "tie" lets a variable run code when
# it's read (FETCH) or written (STORE). A block's data is tied to this class
# with its JSON text; the first read decodes it (via json_cached) and keeps
# the result; writing a new value replaces it. So a request that draws one
# page never decodes the blocks of all the others.
package BlowfishCMS::LazyJSON;
sub TIESCALAR { my ($class,$raw)=@_;return bless {raw=>$raw},$class }
sub FETCH { my $s=shift;return $s->{data} //= do {my $d=BlowfishCMS::json_cached($s->{raw});ref $d eq 'HASH' ? $d : {}} }
sub STORE { my ($s,$v)=@_;delete $s->{raw};$s->{data}=$v }
1;