repository

BlowfishCMS

A small content management system for OpenBSD

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

276 lines · 22.0 KB · download this file

package BlowfishCMS;
# Pages: page styles, the page registry, navigation and the Pages admin
# screen (the page builder itself, and how pages are stored, are in Blocks.pm).
# 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);

# The layout options a page can have (set on the page editor's Page tab), each
# with its allowed values; the first value of each list is the default. They
# end up as data-page-* attributes on <main>, which site.css styles.
sub style_choices {return {width=>[qw(original narrow wide full)],font=>[qw(theme sans serif mono)],size=>[qw(normal small large)],spacing=>[qw(normal compact spacious)],align=>[qw(original left center)],layout=>[qw(original single)],sidebar=>[qw(right left)]}}
# How each choice is shown in the page editor.
sub style_labels {
    return {width=>['Page width',{original=>'Standard (the theme’s)',narrow=>'Narrow (for reading)',wide=>'Wide',full=>'Full width, edge to edge'}],
        font=>['Text font',{theme=>'The theme’s',sans=>'Sans-serif',serif=>'Serif',mono=>'Monospace'}],
        size=>['Text size',{normal=>'Normal',small=>'Small',large=>'Large'}],
        spacing=>['Spacing inside panels',{normal=>'Normal',compact=>'Compact',spacious=>'Roomy'}],
        align=>['Text alignment',{original=>'The theme’s',left=>'Left',center=>'Centred'}],
        layout=>['Side-by-side blocks',{original=>'Side by side',single=>'One under another'}],
        sidebar=>['Sidebar',{right=>'On the right',left=>'On the left'}]};
}
# A page's layout choices; takes a page's slug or the page itself (previews).
# A page's layout choices as a hash (width => 'narrow', ...). Starts from the
# defaults, then takes each saved choice from the page's `style` JSON only if
# it's one of the allowed values, so a bad stored value can't reach the page.
sub page_style ($slug) {
    my %s=map {$_=>style_choices()->{$_}[0]} keys %{style_choices()};
    my $page=ref $slug ? $slug : page_by_slug($slug);
    my $saved=$page ? json_cached($page->{style}||'{}') : undef;
    if (ref $saved eq 'HASH') {for my $k (keys %s) {$s{$k}=$saved->{$k} if defined $saved->{$k} && grep {$_ eq $saved->{$k}} @{style_choices()->{$k}}}}
    return \%s;
}
# The page's layout choices as HTML attributes for <main>:
# data-page-width="narrow" data-page-font="serif" ...
sub page_attributes ($slug) {my $s=page_style($slug);return join '',map {' data-page-'.$_.'="'.h($s->{$_}).'"'} sort keys %$s}

# ---- Pages & navigation ---------------------------------------------------
# slug => {key, path, label (navigation), title (admin)} for every page.
# A lookup of every page by its slug (its short name, "about"): its address,
# its label in the navigation and its title in the admin.
sub page_registry {
    return {map {($_->{slug}=>{key=>$_->{slug},path=>$_->{path},label=>$_->{nav_label},title=>ucfirst($_->{nav_label}),kind=>'page'})} @{all_pages()}};
}
# Every page's order and state, as a list of {page => slug, visible => 1|0,
# menu => 1|0}: "visible" is whether the page is on (open to visitors; off,
# it answers "not found"), "menu" whether it's in the navigation bar while
# it's on (a page can be on without being in the menu, for one you link to
# from elsewhere). The saved order (the `nav` setting) comes first, minus
# pages that no longer exist; pages it doesn't mention are added at the end
# (the site's starter pages on, ones made later off); duplicates are dropped,
# Home is always on, and "menu" is on unless it was turned off. Worked out
# once a request ($nav_cache) and handed out as copies, so a caller changing
# an item can't change the cached one.
sub nav_items {
    # Built once a request (several parts of a page ask); callers get copies.
    return map {+{%$_}} @$BlowfishCMS::nav_cache if $BlowfishCMS::nav_cache;
    my %builtin=map {$_=>1} builtin_pages();
    my @default=map {+{page=>$_->{slug},visible=>($builtin{$_->{slug}} ? 1 : 0)}} @{all_pages()};
    my $registry=page_registry();
    my $saved=json_cached(scalar attempt {$db->selectrow_array("SELECT value FROM site_settings WHERE key='nav'")});
    my @items=ref $saved eq 'ARRAY' ? (grep {ref $_ eq 'HASH' && $registry->{$_->{page}//''}} @$saved) : ();
    my %seen=map {($_->{page}=>1)} @items;
    push @items,grep {!$seen{$_->{page}}} @default;
    my %once;@items=grep {!$once{$_->{page}}++} @items;
    my %groups=map {($_->{id}=>1)} nav_groups();
    for (@items) {$_->{visible}=$_->{page} eq 'home' ? 1 : ($_->{visible}?1:0);$_->{menu}=exists $_->{menu} ? ($_->{menu}?1:0) : 1;$_->{group}=$groups{$_->{group}//''} ? $_->{group} : ''}
    $BlowfishCMS::nav_cache=[map {+{%$_}} @items];
    return @items;
}
# Whether visitors may see a page: a page that's off answers "not found"
# (Home is always on). An add-on's page is also off while its add-on is
# switched off.
sub page_enabled ($slug) {
    return 1 if ($slug//'') eq 'home';
    # An add-on's page answers "not found" while its add-on is off.
    my $page=page_by_slug($slug//'');return 0 if $page && length($page->{addon}//'') && !addon_enabled($page->{addon});
    my ($item)=grep {$_->{page} eq ($slug//'')} nav_items();
    return $item && $item->{visible} ? 1 : 0;
}
# The contact form only accepts messages while some page that's on shows a
# contact form block, so a hidden form can't be used to send mail.
sub contact_form_enabled {
    return scalar grep {page_enabled($_->{slug}) && grep {$_->{type} eq 'contact_form'} @{$_->{blocks}}} @{all_pages()};
}
# Saves the pages' order and states (an UPSERT: insert the row, or update it
# if it exists) and forgets the cached copy.
sub save_nav (@items) {
    undef $BlowfishCMS::nav_cache;
    $db->do("INSERT INTO site_settings(key,value) VALUES ('nav',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",undef,JSON::PP->new->encode([map {+{page=>$_->{page},visible=>$_->{visible}?1:0,menu=>(($_->{menu}//1)?1:0),(length($_->{group}//'') ? (group=>$_->{group}) : ())}} @items]));
}
# Menu groups (0.43): a label in the navigation bar that drops down to show
# its pages ("media": Music, Photography, Videos). Kept in the nav_groups
# setting as [{id, label}]; a page's navigation item names its group. A group
# stands where its first page is, so the pages' order stays the one list
# above, and a group with no page in the menu isn't shown.
sub nav_groups {
    my $saved=json_cached(scalar attempt {$db->selectrow_array("SELECT value FROM site_settings WHERE key='nav_groups'")});
    return map {+{id=>$_->{id},label=>$_->{label}}} grep {ref $_ eq 'HASH' && ($_->{id}//'') =~ /\A[a-f0-9]{8}\z/ && length($_->{label}//'')} @{ref $saved eq 'ARRAY' ? $saved : []};
}
sub save_nav_groups (@groups) {
    undef $BlowfishCMS::nav_cache;
    $db->do("INSERT INTO site_settings(key,value) VALUES ('nav_groups',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",undef,JSON::PP->new->encode([map {+{id=>$_->{id},label=>$_->{label}}} @groups]));
}
# The navigation as it's shown: pages on their own, and each group (where
# its first page is) with its pages: {group=>{id, label}, items=>[…]}.
sub nav_tree (@items) {
    my %groups=map {($_->{id}=>$_)} nav_groups();my (%done,@tree);
    for my $it (@items) {
        my $g=$groups{$it->{group}//''};
        unless ($g) {push @tree,$it;next}
        next if $done{$g->{id}}++;
        push @tree,{group=>$g,items=>[grep {($_->{group}//'') eq $g->{id}} @items]};
    }
    return @tree;
}
# Whether a page is in the navigation bar: on, and in the menu.
sub in_menu ($item) { return $item->{visible} && $item->{menu} && page_enabled($item->{page}) }
# The links in the site's menu: each page that's on and in the menu, with
# aria-current="page" on the one being shown (for screen readers and styling).
# A menu group is a <details>: it opens without a script, by keyboard too;
# site.js closes the others, and closes it on Escape or a click elsewhere.
sub nav_links ($current) {
    my $pages=page_registry();
    my $link=sub ($it) {my $p=$pages->{$it->{page}};'<a href="'.h($p->{path}).'"'.($current eq $p->{path}?' aria-current="page"':'').'>'.h($p->{label}).'</a>'};
    return join '',map {my $t=$_;
        ref $t->{group} eq 'HASH'
            ? '<details class="nav-group'.((grep {$current eq $pages->{$_->{page}}{path}} @{$t->{items}}) ? ' is-current' : '').'"><summary>'.h($t->{group}{label}).'<span class="nav-group__caret" aria-hidden="true"></span></summary><div class="nav-group__menu" data-label="'.h($t->{group}{label}).'">'.join('',map {$link->($_)} @{$t->{items}}).'</div></details>'
            : $link->($t)} nav_tree(grep {in_menu($_)} nav_items());
}

# The admin's Pages screen (/admin/?kind=pages): the list of pages, and the
# actions posted from it:
#   page_create  make a page (it starts off), then open its editor
#   order / move the navigation's order (list_order: dragged, or one place)
#   page_delete  delete a page (not Home)
#   nav_toggle   switch a page on or off
#   nav_menu     put a page in the navigation bar, or take it out
#   nav_tree     the whole menu, dragged: the pages' order and their groups
#   nav_group_add / nav_group_rename / nav_group_delete   menu groups
#   nav_group_set  put a page in a group, or back on its own
# Each action redirects back with a notice; a failure shows the screen again
# with the error. Below that, the screen itself: one row per page with its
# address, state, block count, its on/off and menu switches, edit and a "…"
# menu for the rarer actions; then the "New page" form.
sub pages_admin {
    my $message=param('notice',2000);
    my $add=$method eq 'POST' && param('action',30) eq 'page_create';
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',30);
            if ($action eq 'page_create') {
                my $slug=page_create(param('label',40),param('slug',40));
                redirect('/admin/?kind=page&page='.$slug.'&notice='.CGI::escape('Page created. It stays off (visitors get “not found”) until you turn it on in Pages.'));
            }
            if ($action eq 'nav_tree') {
                # Dragging: every page in its new place, each with its group ('' on its own).
                my @order=map {utf8::is_utf8($_) ? $_ : decode('UTF-8',$_)} $q->multi_param('order');my @in=$q->multi_param('in');
                die "Drag the pages into the order you want.\n" unless @order && @order==@in;
                my @all=nav_items();my %by=map {($_->{page}=>$_)} @all;my %g=map {($_->{id}=>1)} nav_groups();my (%seen,@items);
                for my $i (0..$#order) {my $it=$by{$order[$i]} or next;next if $seen{$it->{page}}++;$it->{group}=$g{$in[$i]//''} ? $in[$i] : '';push @items,$it}
                die "Drag the pages into the order you want.\n" unless @items;
                save_nav(@items,grep {!$seen{$_->{page}}} @all);
                json_response({ok=>JSON::PP::true,message=>'Menu saved.'}) if fetch_request();
                redirect('/admin/?kind=pages');
            }
            if ($action eq 'nav_group_add') {
                my $label=param('label',40);die "Give the menu group a name, such as media.\n" unless length $label;
                my @groups=nav_groups();die "There’s already a menu group called $label.\n" if grep {lc $_->{label} eq lc $label} @groups;
                save_nav_groups(@groups,{id=>substr(random_id(),0,8),label=>$label});
                redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8',"Made the menu group “$label”. Drag pages into it, or choose it in a page’s “…” menu.")).'#nav-groups');
            }
            if ($action =~ /\Anav_group_(?:rename|delete)\z/) {
                my $id=param('group',8);my @groups=nav_groups();my ($g)=grep {$_->{id} eq $id} @groups;
                die "That menu group no longer exists.\n" unless $g;
                if ($action eq 'nav_group_rename') {
                    my $label=param('label',40);die "Give the menu group a name.\n" unless length $label;
                    $g->{label}=$label;save_nav_groups(@groups);
                    redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8',"Renamed the menu group “$label”.")));
                }
                save_nav_groups(grep {$_->{id} ne $id} @groups);
                save_nav(map {($_->{group}//'') eq $id ? {%$_,group=>''} : $_} nav_items());
                redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8',"Deleted the menu group “$g->{label}”. Its pages are on their own in the menu again.")));
            }
            list_order(ids=>[map {$_->{page}} nav_items()],back=>'/admin/?kind=pages',
                save=>sub (@ids) {my %by=map {($_->{page}=>$_)} nav_items();save_nav(map {$by{$_}} @ids)});
            my $key=param('page',40);
            my @items=nav_items();my ($index)=grep {$items[$_]{page} eq $key} 0..$#items;
            die "Choose a page.\n" unless defined $index;
            my $title=page_registry()->{$key}{title};
            if ($action eq 'page_delete') {
                my $page=page_by_slug($key) or die "That page no longer exists.\n";
                page_remove($page);
                redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8','Deleted the '.$page->{nav_label}.' page.')));
            }
            if ($action eq 'nav_toggle') {
                die "Home is always on.\n" if $key eq 'home';
                $items[$index]{visible}=defined $q->param('on') ? (param('on',1) eq '1' ? 1 : 0) : $items[$index]{visible} ? 0 : 1;save_nav(@items);
                redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8',$title.($items[$index]{visible}?' is on: open to visitors'.($items[$index]{menu} ? ' and in the navigation.' : ', but not in the navigation.'):($key eq 'blog' ? ' is off. Its address, articles, feed and comments answer “not found”.' : ' is off. Its address answers “not found”; you can still edit and preview it.')))));
            }
            if ($action eq 'nav_group_set') {
                my $id=param('group',8);my ($g)=grep {$_->{id} eq $id} nav_groups();
                die "That menu group no longer exists.\n" if length $id && !$g;
                my $it=splice @items,$index,1;$it->{group}=$g ? $id : '';
                # Into a group: after its last page, so the group stays where it was.
                my ($last)=reverse grep {($items[$_]{group}//'') eq $id} 0..$#items;
                splice @items,($g && defined $last ? $last+1 : $index),0,$it;
                save_nav(@items);
                redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8',$g ? "$title is in the menu group “$g->{label}”." : "$title is on its own in the menu.")));
            }
            if ($action eq 'nav_menu') {
                $items[$index]{menu}=defined $q->param('on') ? (param('on',1) eq '1' ? 1 : 0) : $items[$index]{menu} ? 0 : 1;save_nav(@items);
                redirect('/admin/?kind=pages&notice='.CGI::escape(encode('UTF-8',$title.($items[$index]{menu} ? ' is in the navigation'.($items[$index]{visible} ? '.' : ' once it’s on.') : ' is out of the navigation; its address still works while it’s on.'))));
            }
            die "Choose an action.\n";
        } or do {$message=failed_action($@);json_response({ok=>JSON::PP::false,message=>$message},400) if fetch_request()};
    }
    admin_page('Pages',section=>'pages',notice=>$message,intro=>'Edit any page, make new ones, and drag them into the navigation bar’s order, or into menu groups that drop down. A page that’s off answers “not found” to visitors (you can still edit and preview it); a page can also be on without being in the navigation.');
    my @items=nav_items();my $i=0;my %pos;$pos{$_->{page}}=++$i for @items;
    my %pages=map {($_->{slug}=>$_)} @{all_pages()};my @groups=nav_groups();
    my $row=sub ($item) {
        my $p=page_registry()->{$item->{page}};my $pg=$pages{$item->{page}};my $what="the $p->{title} page";
        # The "…" menu: the library screens its blocks show (a gallery names
        # Pictures), its add-on's own screen, moving it, and deleting it.
        my %manage;
        for my $b (@{$pg->{blocks}}) {my $m=block_types()->{$b->{type}}{manage};$manage{$m->[0]}=$m->[1] if $m}
        my $menu=join '',map {'<a class="text-button" href="/admin/?kind='.$_.'">'.h($manage{$_}).'</a>'} sort keys %manage;
        my $a=$pg->{addon}//'';
        if (length $a) {
            my ($g)=grep {$_->{name} eq $a} attempt {addon_admin_sections()};
            my ($own)=grep {$_->[0] ne "x-$a-page"} @{$g ? $g->{screens} : []};
            $menu.='<a class="text-button" href="'.h($own->[2]).'">manage on the '.h($g->{label}).' tab</a>' if $own;
        }
        # Its menu group: chosen here too (by keyboard, or without the script).
        $menu.='<form method="post" action="/admin/" class="row-menu__group" data-auto-submit>'.fields('nav_group_set','pages').hidden(page=>$item->{page})
            .'<label>Menu group<select name="group"><option value="">none: on its own</option>'.join('',map {'<option value="'.h($_->{id}).'"'.(($item->{group}//'') eq $_->{id} ? ' selected' : '').'>'.h($_->{label}).'</option>'} @groups).'</select></label>'
            .'<button class="text-button no-js-only" type="submit">put it there</button></form>' if @groups;
        $menu.=move_buttons('pages',$item->{page},$pos{$item->{page}},scalar @items,label=>$what);
        $menu.='<form method="post" action="/admin/" class="delete-form" data-confirm="'.h('Delete the '.$p->{title}.' page? '.page_delete_note($item->{page}).' This cannot be undone.').'">'.fields('page_delete','pages').hidden(page=>$item->{page}).'<button class="text-button danger" aria-label="Delete the '.h($p->{title}).' page">delete</button></form>' unless fixed_page($item->{page});
        my $n=@{$pg->{blocks}};
        return admin_row(title=>$p->{title},order=>$item->{page},menu_for=>$what,menu=>$menu,
            badges=>[($item->{visible} ? () : 'Off'),($item->{visible} && !$item->{menu} ? 'Not in menu' : ())],
            meta=>[h($p->{path}),($item->{visible} ? () : 'visitors get “not found”'),(length $a ? 'from '.h((addons_available()->{$a}//{})->{label}//$a).(addon_enabled($a) ? '' : ' (switched off, so the page is hidden)') : ()),($n==1 ? '1 block' : "$n blocks")],
            # In view: on/off (Home is always on), in the menu, and edit.
            actions=>switch_button('pages','nav_toggle','',$item->{visible},'on',what=>'On',name=>$what,post=>{page=>$item->{page}},disabled=>$item->{page} eq 'home' ? 'Home is always on' : '')
                .switch_button('pages','nav_menu','',$item->{menu},'in menu',what=>'In the navigation menu',name=>$what,post=>{page=>$item->{page}})
                .'<a class="buttonlike" href="/admin/?kind=page&amp;page='.h($item->{page}).'">edit</a>');
    };
    # A menu group: its row (dragged with its pages), then its pages.
    my $group_html=sub ($g,@in) {
        return '<section class="nav-group-row'.(@in ? '' : ' is-empty').'" data-nav-group="'.h($g->{id}).'" id="group-'.h($g->{id}).'">'
            .admin_row(title=>$g->{label},lead=>drag_handle(),class=>'nav-group-row__head',badges=>['menu group'],menu_for=>"the menu group $g->{label}",
                meta=>[@in ? scalar(@in).' '.(@in==1 ? 'page drops' : 'pages drop').' down from it' : 'empty: drag pages here, or choose it in a page’s “…” menu'],
                actions=>'<details class="row-menu"><summary class="buttonlike" aria-label="Rename the menu group '.h($g->{label}).'">rename</summary><div class="row-menu__items link-edit"><form method="post" action="/admin/" class="admin-form">'.fields('nav_group_rename','pages').hidden(group=>$g->{id})
                    .'<label>Name<input name="label" maxlength="40" required value="'.h($g->{label}).'"></label><button class="buttonlike is-primary" type="submit">save</button></form></div></details>',
                menu=>'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete the menu group $g->{label}? Its pages stay in the menu, on their own.").'">'.fields('nav_group_delete','pages').hidden(group=>$g->{id}).'<button class="text-button danger" type="submit">delete</button></form>')
            .'<div class="nav-group-pages" data-nav-group-pages="'.h($g->{id}).'">'.join('',map {$row->($_)} @in).'</div></section>';
    };
    my %placed;
    my $tree=join('',map {ref $_->{group} eq 'HASH' ? do {$placed{$_->{group}{id}}=1;$group_html->($_->{group},@{$_->{items}})} : $row->($_)} nav_tree(@items))
        .join('',map {$group_html->($_)} grep {!$placed{$_->{id}}} @groups);
    my $groups_box='<div class="box-part" id="nav-groups"><h3>Menu groups</h3><p>A menu group is one item in the navigation bar that drops down to show its pages, such as “media” for Music, Photography and Videos. Drag pages into it and out again, or drag a group by its handle to move it with its pages.</p>'
        .'<form method="post" action="/admin/" class="admin-form inline-form">'.fields('nav_group_add','pages').'<label>Name<input name="label" maxlength="40" required placeholder="media"></label><button type="submit" class="buttonlike">add menu group</button></form></div>';
    window('pages','<div class="theme-list nav-tree" data-nav-tree>'.$tree.'</div>'.$groups_box.'<div class="box-part" id="new-page"><h3>New page</h3>'.('<form method="post" action="/admin/" class="admin-form" data-warn-unsaved>'.fields('page_create','pages').'<p>Starts with one text panel, switched off until you turn it on.</p><div class="theme-editor__grid"><label>Name<input name="label" maxlength="40" required placeholder="Gear" value="'.($add?h(param('label',40)):'').'"></label><label>Address<input name="slug" maxlength="40" pattern="[a-z0-9][a-z0-9-]*" placeholder="gear" value="'.($add?h(param('slug',40)):'').'"><span class="optional">optional; made from the name</span></label></div><button type="submit" class="buttonlike">add page</button></form>').'</div>');
    end_page();
}

1;