repository

BlowfishCMS

A small content management system for OpenBSD

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

408 lines · 29.2 KB · download this file

package BlowfishCMS;
# Admin: the admin's own layout (sidebar, top bar) and the overview screen.
# Every admin screen starts with admin_page and ends with end_page; the public
# site's navigation, theme picker and themes are not used here, so the admin
# looks the same whichever theme visitors see.
# 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);

# Set by failed_action for the rest of the request (reset by handle_request).
our $admin_failed=0;
# The message for an action that failed, marked so admin_page shows it as an error.
# Turns an action's error into a message to show (clean_error), and marks
# the request as failed, so admin_page shows the message in red.
sub failed_action ($error) {$admin_failed=1;return clean_error($error)}

# ---- Lists put in order ----------------------------------------------------------
# Every list the owner puts in order (pages, theme variants, a page's blocks,
# an add-on's links or offerings…) works the same way: drag a row by its
# handle, or use "move up" and "move down" (in the row's "…" menu), which is
# also the way without the script or a mouse. A screen:
#   - marks the list with order_list_attrs(KIND) and each row with
#     order_row_attrs(ID), and starts each row with drag_handle();
#   - puts move_buttons(KIND, ID, POSITION, COUNT) in the row's menu;
#   - handles both actions with list_order(ids=>[...], save=>sub (@ids) {...},
#     back=>URL), before its own actions. "order" is every id dragged into
#     place (admin.js sends it); "move" is one id (the form's "id") one place
#     up or down. Ids it doesn't know are ignored and ids left out keep
#     their place after the rest. It saves through the screen's callback
#     (sort_order_save for a table with a sort_order column) and answers:
#     JSON to the script, a redirect to a form. Anything else returns 0.
# Extra fields the screen's actions need (the page editor's page) go in
# order_list_attrs's and move_buttons' %post.
sub order_list_attrs ($kind,%post) {
    return ' data-reorder="'.h($kind).'"'.(%post ? ' data-reorder-fields="'.h(join '&',map {CGI::escape($_).'='.CGI::escape($post{$_})} sort keys %post).'"' : '');
}
sub order_row_attrs ($id) { return ' data-reorder-id="'.h($id).'"' }
sub drag_handle { return '<span class="drag-handle" aria-hidden="true" title="Drag to reorder">⠿</span>' }
# compact=>1 gives ↑ and ↓ (for the page editor's narrow list of blocks);
# label=>'the Contact page' names the row for screen readers.
sub move_buttons ($kind,$id,$position,$count,%o) {
    my %post=%{$o{post}//{}};my $what=length($o{label}//'') ? ' '.$o{label} : '';
    my $button=sub ($dir,$text,$off) {'<button class="text-button" type="submit" name="direction" value="'.$dir.'"'.($off ? ' disabled' : '').($o{compact} || length $what ? ' aria-label="'.h("Move$what $dir").'" title="Move '.$dir.'"' : '').'>'.$text.'</button>'};
    return '<form method="post" action="/admin/" class="move-form">'.fields('move',$kind,$id).hidden(%post)
        .$button->('up',$o{compact} ? '↑' : 'move up',$position<=1).$button->('down',$o{compact} ? '↓' : 'move down',$position>=$count).'</form>';
}
sub list_order (%o) {
    my $action=param('action',30);
    return 0 unless $action eq 'order' || $action eq 'move';
    my @ids=@{$o{ids}};my %have=map {($_=>1)} @ids;my @order;my $moved='';
    if ($action eq 'order') {
        my %seen;@order=grep {$have{$_} && !$seen{$_}++} map {utf8::is_utf8($_) ? $_ : decode('UTF-8',$_)} $q->multi_param('order');
        die "Drag the rows into the order you want.\n" unless @order;
        push @order,grep {!$seen{$_}} @ids;
    }
    else {
        $moved=param('id',120);my ($i)=grep {$ids[$_] eq $moved} 0..$#ids;
        die "That’s no longer in the list. Reload the page.\n" unless defined $i;
        my $j=$i+(param('direction',4) eq 'up' ? -1 : 1);
        @order=@ids;@order[$i,$j]=@order[$j,$i] if $j>=0 && $j<=$#ids;
    }
    $o{save}->(@order);
    json_response({ok=>JSON::PP::true,message=>'Order saved.'}) if fetch_request();
    redirect(ref $o{back} ? $o{back}->($moved) : $o{back});
}
# A row's "…" menu: the rarer actions (moving, duplicating, deleting), out of
# the way. $what names the row for screen readers: "More for the Contact page".
sub row_menu ($what,$items) {
    return '<details class="row-menu"><summary class="buttonlike" aria-label="'.h("More for $what").'">…</summary><div class="row-menu__items">'.$items.'</div></details>';
}
# ---- Words on buttons -----------------------------------------------------------
# One word for one thing, on every screen (add-ons too):
#   save          a form's button, and the save at the top of a screen
#                 (status "All changes saved"); "save draft" only beside publish
#   add X         a form's button that makes something; "new X" opens an
#                 empty editor
#   delete        destroys something you made (a page, an article, a picture,
#                 a form); on the thing's own editor "delete this X"
#   remove        takes something out of a list or off the site (an add-on,
#                 a theme, a user, a redirect, a subscriber, the logo, a key)
#   ×             closes a panel or a note; "dismiss" sets advice aside
#   edit, open, preview ↗, view ↗, move up, move down, duplicate
# Filters apply as soon as they're chosen (form[data-auto-submit]); their
# show button is only for browsers without the script (no-js-only). An empty
# list says "No things yet. Add the first one below."

# ---- Lists of things -----------------------------------------------------------
# Every list of things the owner manages (pages, theme variants, add-ons,
# users, articles, links, products…) is drawn the same way, a row each:
#   [⠿] [picture] Title BADGE                        [switches] [buttons] […]
#                 what it is, a sentence or two
#                 details · details
# Switches first, then the everyday buttons (edit, open, preview), and the
# rarer actions (move, duplicate, remove, delete) in the "…" menu, so a
# delete is never one stray click away. Tables are for records read across
# columns (orders, bookings, visits, logs), not for things you manage.
#   admin_row(title=>TEXT | title_html=>HTML, href=>URL (the title links
#     there), badges=>[TEXT | [TEXT,'live']…], text=>HTML, meta=>[HTML…]
#     (joined with ·), lead=>HTML (a picture or colour swatches),
#     order=>ID (a drag handle; the list has order=>KIND), off=>1 (dimmed:
#     hidden, closed, past), id=>ANCHOR, attrs=>' data-x="…"', class=>EXTRA,
#     actions=>HTML, menu=>HTML (row_menu's items), menu_for=>'the Contact page')
#   admin_list(\@rows | HTML, order=>KIND, post=>{…}, id=>ID, empty=>HTML)
sub admin_row (%o) {
    my $title=$o{title_html} // h($o{title}//'');
    $title='<a href="'.h($o{href}).'">'.$title.'</a>' if length($o{href}//'');
    my $badges=join '',map {my ($t,$live)=ref $_ ? @$_ : ($_);' <span class="state-badge'.($live ? ' is-live' : '').'">'.h($t).'</span>'} @{$o{badges}//[]};
    my @meta=grep {defined && length} @{$o{meta}//[]};
    return '<article class="theme-row'.($o{off} ? ' is-disabled' : '').(length($o{class}//'') ? ' '.h($o{class}) : '').'"'
        .(length($o{id}//'') ? ' id="'.h($o{id}).'"' : '').(defined $o{order} ? order_row_attrs($o{order}) : '').($o{attrs}//'')
        .'><div class="theme-row__info">'.(defined $o{order} ? drag_handle() : '').($o{lead}//'').'<div><h2>'.$title.$badges.'</h2>'
        .(length($o{text}//'') ? '<p>'.$o{text}.'</p>' : '').(@meta ? '<p class="media-label">'.join(' · ',@meta).'</p>' : '').'</div></div>'
        .'<div class="theme-row__actions">'.($o{actions}//'').(length($o{menu}//'') ? row_menu($o{menu_for}//$o{title}//'this',$o{menu}) : '').'</div></article>';
}
sub admin_list ($rows,%o) {
    my $html=ref $rows ? join('',@$rows) : $rows//'';
    return '<p class="empty-media">'.($o{empty}//'Nothing here yet.').'</p>' unless length $html;
    return '<div class="theme-list"'.(length($o{id}//'') ? ' id="'.h($o{id}).'"' : '').(length($o{order}//'') ? order_list_attrs($o{order},%{$o{post}//{}}) : '').'>'.$html.'</div>';
}

# ---- Switches ------------------------------------------------------------------
# Whatever is simply on or off is a switch, everywhere:
#   - switch_button(KIND, ACTION, ID, ON, LABEL, …) in a list's row acts at
#     once: a small form posting ACTION with on=1 or 0 (the state wanted).
#     what=>'Shown to visitors' and name=>'Modern' make its screen-reader
#     label ("Shown to visitors: yes. Change it for Modern"); disabled=>WHY
#     greys it out with WHY as its tooltip; post=>{…} adds fields; to=>URL
#     posts to a service's screen instead of /admin/.
#   - switch_field(NAME, LABEL, ON, …) in a form saved with a button is a
#     field like the others: a tick box drawn as a switch (role="switch"),
#     with a hidden 0 after it so that "off" is sent too. hint=>TEXT goes
#     under the label, form=>ID ties it to a form elsewhere on the screen,
#     html=>1 when LABEL is already HTML (a link in it).
# Tick boxes stay for choosing things (pictures to act on, pages in setup)
# and for agreeing to something (terms, "I'm sure").
sub switch_button ($kind,$action,$id,$on,$label,%o) {
    my $aria=($o{what}//ucfirst $label).': '.($on ? 'yes' : 'no').'. Change it'.(length($o{name}//'') ? " for $o{name}" : '');
    return '<form method="post" action="'.h($o{to}//'/admin/').'" class="switch-form">'.fields($action,$kind,$id).hidden(on=>$on ? 0 : 1,%{$o{post}//{}})
        .'<button class="switch'.($on ? ' is-on' : '').'" type="submit" aria-pressed="'.($on ? 'true' : 'false').'"'
        .(length($o{disabled}//'') ? ' disabled title="'.h($o{disabled}).'"' : '').' aria-label="'.h($aria).'"><span class="switch__track" aria-hidden="true"></span>'.h($label).'</button></form>';
}
sub switch_field ($name,$label,$on,%o) {
    my $form=length($o{form}//'') ? ' form="'.h($o{form}).'"' : '';
    return '<label class="switch-field'.(length($o{class}//'') ? ' '.h($o{class}) : '').'"><input type="checkbox" role="switch" name="'.h($name).'" value="1"'.$form.($on ? ' checked' : '').($o{disabled} ? ' disabled' : '').'>'
        .'<span class="switch__track" aria-hidden="true"></span><span class="switch-field__text">'.($o{html} ? $label : h($label)).(length($o{hint}//'') ? '<span class="optional">'.h($o{hint}).'</span>' : '').'</span>'
        .($o{disabled} ? '' : '<input type="hidden" name="'.h($name).'" value="0"'.$form.'>').'</label>';
}
# Numbers a table's rows 0, 1, 2… in the order of @ids, in one transaction.
sub sort_order_save ($dbh,$table,$key,@ids) {
    die "sort_order_save: bad table\n" unless "$table.$key" =~ /\A[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*\z/;
    my $own=$dbh->{AutoCommit};$dbh->begin_work if $own;
    attempt {my $sth=$dbh->prepare("UPDATE $table SET sort_order=? WHERE $key=?");$sth->execute($_,$ids[$_]) for 0..$#ids;1}
        or do {my $e=$@;$dbh->rollback if $own;die $e};
    $dbh->commit if $own;
}

# The sidebar: groups of [key, label, address]. Editors don't see the
# owners' screens (and a group left empty disappears). Articles and Comments
# stay here even when an add-on (Blog) also lists them on its tab.
sub admin_sections {
    my @all=(
        [''        ,[overview=>'Overview','/admin/'],[pages=>'Pages','/admin/?kind=pages']],
        ['Libraries',[photography=>'Pictures','/admin/?kind=photography'],[music=>'Music','/admin/?kind=music'],[video=>'Videos','/admin/?kind=video'],[file=>'Files','/admin/?kind=file'],[blog=>'Articles','/admin/?kind=blog'],[comments=>'Comments','/admin/comments/']],
        ['Site'     ,[look=>'Look','/admin/?kind=themes'],[settings=>'Settings','/admin/?kind=settings'],[analytics=>'Analytics','/admin/analytics/'],[addons=>'Add-ons','/admin/?kind=addons']],
    );
    return @all if is_owner();
    # Editors see the content; the site's settings are for owners.
    my %owner=map {$_=>1} qw(look settings search mail themes branding users signin system addons analytics);
    return grep {@$_>1} map {my ($label,@items)=@$_;[$label,grep {!$owner{$_->[0]}} @items]} @all;
}
# The tabs of the sidebar entries that hold several screens: [key, label, address].
sub admin_tab_groups {
    return (
        settings=>[[settings=>'Site','/admin/?kind=settings'],[search=>'Search & sharing','/admin/?kind=search'],[mail=>'Mail','/admin/mail/'],[users=>'Users','/admin/?kind=users'],[signin=>'Sign-in','/admin/?kind=signin'],[system=>'System','/admin/?kind=system']],
        look=>[[themes=>'Themes','/admin/?kind=themes'],[branding=>'Logo & icons','/admin/?kind=branding']],
    );
}
# The number on the sidebar's Comments: visible comments from the last week.
sub recent_comment_count {
    my $c=comments_enabled() ? (attempt {comments_db()}) : undef;
    return 0 unless $c;
    my $since=strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-7*86400));
    return (attempt {$c->selectrow_array('SELECT count(*) FROM comments WHERE hidden=0 AND created_at>?',undef,$since)}) // 0;
}

# Starts an admin screen. Options: section (sidebar item to mark), intro (one
# line under the title, HTML), crumbs ([label, address] pairs before the
# title), actions (HTML at the right of the top bar), notice (a message from
# the last action, shown under the top bar), save ([button label, status
# text]: a save button for the #bulk-edit form, kept in view in the top bar,
# with the save status beside it), status (HTTP status).
# Starts every admin screen: the <head>, the sidebar (marking the current
# section; Notifications with its count for owners; your account; sign out),
# the top bar (crumbs, title, intro, actions, and a save button for screens
# with one form, #bulk-edit), the tabs for Settings and for Add-ons, any
# notification pop-ups, and the message from the last action. The admin
# always uses its own look (admin.css), whatever theme visitors see.
sub admin_page ($title,%o) {
    header($o{status}//200);
    print '<!doctype html><html lang="en" class="admin"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
        .'<title>'.h($title).' · admin · '.h(setting('site_title')).'</title>'.icon_head()
        .'<link rel="stylesheet" href="/css/site.css?v=18"><link rel="stylesheet" href="/css/admin.css?v=55">'
        .'<script defer src="/js/admin.js?v=41"></script></head><body'.($o{class} && $o{class} =~ /\A[a-z -]+\z/ ? ' class="'.$o{class}.'"' : '').'><a class="skip-link" href="#main">skip to content</a><div class="admin-shell">';
    my $section=$o{section}//'';my $new=recent_comment_count();
    # Screens that share a sidebar entry, with tabs: Settings (Site, Search &
    # sharing, Mail, Users, Sign-in, System) and Look (Themes, Logo & icons).
    # Add-ons and each add-on's screens share another (x-NAME, x-NAME-service).
    my %groups=admin_tab_groups();
    my %tabbed;for my $g (keys %groups) {$tabbed{$_->[0]}=$g for @{$groups{$g}}}
    my $in_addons=$section eq 'addons' || $section =~ /\Ax-/;
    my $marked=$tabbed{$section} ? $tabbed{$section} : $in_addons ? 'addons' : $section;
    print '<nav class="admin-nav" aria-label="Admin"><a class="admin-nav__brand" href="/admin/">'.h(setting('site_title')).' <span>admin</span></a>';
    for my $group (admin_sections()) {
        my ($label,@items)=@$group;
        print '<p class="admin-nav__group">'.h($label).'</p>' if length $label;
        for my $item (@items) {
            my ($key,$text,$href)=@$item;
            print '<a href="'.h($href).'"'.($key eq $marked ? ' aria-current="page"' : '').'>'.h($text)
                .($key eq 'comments' && $new ? ' <span class="admin-nav__count" title="'.$new.' in the last 7 days">'.$new.'</span>' : '').'</a>';
        }
        # Notifications, for owners, end the Site group.
        if ($label eq 'Site' && is_owner()) {
            my @notices=attempt {notices_open()};
            print '<a class="admin-nav__notices" href="/admin/?kind=notices"'.($section eq 'notices' ? ' aria-current="page"' : '').'>Notifications'.(@notices ? ' <span class="admin-nav__count" title="'.scalar(@notices).' to look at">'.scalar(@notices).'</span>' : '').'</a>';
        }
    }
    print '<a class="admin-nav__site" href="/" target="_blank" rel="noopener">View site ↗</a>';
    print '<a class="admin-nav__account" href="/admin/?kind=account"'.($section eq 'account' ? ' aria-current="page"' : '').'>'.h(signed_in_admin()).' · your account</a>' if session_mode() && length signed_in_admin();
    # Sign out (when the admin signs in through the login page). The form posts to the admin service with its own key.
    print '<form method="post" action="/admin/" class="admin-nav__signout">'.hidden(kind=>'logout',csrf=>admin_csrf_token()).'<button class="text-button" type="submit">sign out</button></form>' if session_mode() && length admin_csrf_token();
    print '</nav>';
    print '<div class="admin-main"><header class="admin-top"><div class="admin-top__text">';
    print '<p class="admin-crumbs">'.join(' › ',map {'<a href="'.h($_->[1]).'">'.h($_->[0]).'</a>'} @{$o{crumbs}}).'</p>' if $o{crumbs} && @{$o{crumbs}};
    print '<h1>'.h($title).'</h1>';
    print '<p class="admin-top__intro">'.$o{intro}.'</p>' if $o{intro};
    my $actions=$o{actions}//'';
    $actions='<span class="admin-top__status" id="edit-status" role="status">'.h($o{save}[1]).'</span>'.$actions.'<button type="submit" class="buttonlike is-primary" form="bulk-edit">'.h($o{save}[0]).'</button>' if $o{save};
    print '</div>'.(length $actions ? '<div class="admin-top__actions">'.$actions.'</div>' : '').'</header>';
    if (my $g=$tabbed{$section}) {
        print '<nav class="admin-tabs" aria-label="'.($g eq 'look' ? 'Look' : 'Settings').'">'.join('',map {'<a href="'.h($_->[2]).'"'.($_->[0] eq $section ? ' aria-current="page"' : '').'>'.h($_->[1]).'</a>'} @{$groups{$g}}).'</nav>';
    }
    print addon_tabs($section) if $in_addons;
    print '<main id="main" class="admin-content">';
    print((attempt {notice_toasts()}) // '') if is_owner() && $section ne 'notices';
    # Messages from a failed action show as errors; everything else as confirmation.
    print $admin_failed ? '<p class="panel-note admin-notice admin-notice--error" role="alert">'.h($o{notice}).'</p>' : '<p class="panel-note admin-notice" role="status">'.h($o{notice}).'</p>' if length($o{notice}//'');
}

# The tabs on the Add-ons screens: Add-ons (the list, where each add-on's
# "open" leads to its screens), then the add-on that's open, if any. Its
# screens get a second row when it has several (the Store's Products and
# Orders, which run in different services), and a line about its page.
# Only the open add-on is listed, so the row stays short however many are on.
sub addon_tabs ($section) {
    my @groups=attempt {addon_admin_sections()};
    my $tab=sub ($key,$label,$href,$current) {'<a href="'.h($href).'"'.($current ? ' aria-current="page"' : '').'>'.h($label).'</a>'};
    my ($open)=grep {grep {$_->[0] eq $section} @{$_->{screens}}} @groups;
    my $html='<nav class="admin-tabs" aria-label="Add-ons">'.$tab->('addons','Add-ons','/admin/?kind=addons',$section eq 'addons')
        .($open ? $tab->($open->{name},$open->{label},$open->{screens}[0][2],1) : '').'</nav>';
    $html.='<nav class="admin-tabs admin-tabs--sub" aria-label="'.h($open->{label}).'">'.join('',map {$tab->($_->[0],$_->[1],$_->[2],$_->[0] eq $section)} @{$open->{screens}}).'</nav>'
        if $open && @{$open->{screens}}>1;
    # The add-on's own page, when it has one (on its other screens).
    if ($open && $section ne "x-$open->{name}-page" && (my $page=attempt {addon_page($open->{name})})) {
        my $on=page_enabled($page->{slug}) && grep {$_->{page} eq $page->{slug} && $_->{visible}} nav_items();
        $html.='<p class="panel-note addon-page-note">Its page: '.h(ucfirst $page->{nav_label}).' at '.($on ? '<a href="'.h($page->{path}).'" target="_blank" rel="noopener">'.h($page->{path}).'</a>, on' : h($page->{path}).', off')
            .'. Its layout and blocks are edited under <a href="/admin/?kind=x-'.h($open->{name}).'-page">Page</a>.</p>';
    }
    return $html;
}

# The "edit the … page" button at the top of a library: its own page
# (Photography, Music, Blog), or else the first page in the navigation with a
# block that shows this library (a Videos or Downloads page).
sub library_page_action ($kind) {
    my $slug={photography=>'photography',music=>'music',blog=>'blog'}->{$kind}//'';
    my $page=length $slug ? (attempt {page_by_slug($slug)}) : undef;
    unless ($page) {
        my %by=map {($_->{slug}=>$_)} @{(attempt {all_pages()}) // []};
        for my $item (attempt {nav_items()}) {
            my $p=$by{$item->{page}} or next;
            if (grep {((((block_types()->{$_->{type}}//{})->{manage}//[])->[0]) // '') eq $kind} @{$p->{blocks}}) {$page=$p;last}
        }
    }
    return '' unless $page;
    return '<a class="buttonlike" href="/admin/?kind=page&amp;page='.h($page->{slug}).'">edit the '.h(ucfirst $page->{nav_label}).' page</a>';
}

# ---- Previews -------------------------------------------------------------------
# Renders a public page (the page builder's or an article's unsaved version) and
# returns its HTML for the preview frame, as a visitor would see it: public
# navigation and theme, links opening in a new tab. Nothing is saved.
# Draws a public page into a string instead of sending it, as a visitor
# would see it ($admin off), for the preview frames (the page editor, the
# article editor, the theme editor). The response headers are cut off, and
# <base target="_blank"> makes links in the preview open in a new tab rather
# than inside the frame.
sub public_preview ($render) {
    open my $fh,'>:encoding(UTF-8)',\my $buffer or die "Preview unavailable.\n";
    my $previous=select $fh;
    my $ok=attempt {local $admin=0;local $cookie_header;$render->();1};
    my $error=$@;select $previous;close $fh;
    die $error unless $ok;
    my $html=decode('UTF-8',$buffer);
    $html =~ s/\A.*?\r\n\r\n//s;   # the response headers
    $html =~ s/<head>/<head><base target="_blank">/;
    return $html;
}

# ---- What needs attention ---------------------------------------------------------
# Problems and waiting work for the top of the Overview, worst first: the
# server not picking up requests (so updates and backups wait), last night's
# backup failing, the last request failing (for a day), and updates waiting.
# Each is [text, link, link text]. Owners only: editors can't act on any.
sub attention_items {
    return () unless is_owner();
    my @a;
    if (system_ready()) {
        my $state=system_state();
        unless ($state->{off}) {
            my $results=system_results();
            # A long request (an update) stops the check-ins while it runs, so
            # the runner only counts as missing when nothing is running.
            my $seen=$state->{checked} ? time-$state->{checked} : undef;
            push @a,['The server hasn’t picked up requests '.(defined $seen ? 'for '.(age_text($seen) =~ s/ ago\z//r) : 'yet').', so updates and backups are waiting.','/admin/?kind=system','open System']
                if (defined $seen ? $seen>900 : 1) && !grep {($_->{status}//'') eq 'running'} @$results;
            my $n=$state->{nightly}//{};
            push @a,['Last night’s backup failed'.(length($n->{message}//'') ? ': '.$n->{message} : '').'.','/admin/?kind=system#nightly','see backups']
                if ($n->{status}//'') eq 'failed' && time-($n->{at}//0) < 2*86400;
            my $r=$results->[0];
            push @a,['The last request ('.join(' ',grep {length} $r->{action}//'',$r->{arg}//'').') failed '.age_text(time-($r->{at}//0)).'.','/admin/?kind=system&log='.$r->{id},'see what happened']
                if $r && ($r->{status}//'') eq 'failed' && ($r->{id}//'') =~ /\A[a-f0-9]{32}\z/ && time-($r->{at}//0) <= 86400;
        }
    }
    # Videos an add-on handed over (Live's saved streams) that couldn't be added.
    if (my @f=videos_failed()) {
        push @a,[(@f==1 ? 'A saved stream couldn’t be added to Videos'.(length $f[0][1] ? ': '.($f[0][1] =~ s/\s+\z//r) : '.') : scalar(@f).' saved streams couldn’t be added to Videos.')
            .' The server keeps '.(@f==1 ? 'it' : 'them').' for a week in its videos-in/failed folder.','/admin/?kind=video','open Videos'];
    }
    my @n=notices_open();
    push @a,@n==1 ? [$n[0]{title}.'.',$n[0]{href},'open'] : [scalar(@n).' updates are available.','/admin/?kind=notices','see them'] if @n;
    return @a;
}
# The list as a panel, or nothing when all is well.
sub attention_html {
    my @a=attention_items();return '' unless @a;
    return window_html('needs attention','','<ul class="attention-list">'.join('',map {'<li>'.h($_->[0]).' <a href="'.h($_->[1]).'">'.h($_->[2]).'</a></li>'} @a).'</ul>');
}

# ---- Overview -------------------------------------------------------------------
# The Overview (/admin/): what needs attention, the finishing touches, a card per library with its
# count and size, the latest drafts and comments, and the server's free
# space and release.
sub overview_admin {
    my $count=sub ($sql,@bind) {return (attempt {$db->selectrow_array($sql,undef,@bind)}) // 0};
    my $bytes=sub ($kind) {return $count->('SELECT COALESCE(SUM(bytes),0) FROM uploads WHERE kind=?',$kind)};
    admin_page('Overview',section=>'overview',notice=>param('notice',2000),intro=>'Everything on the site at a glance.',
        actions=>'<a class="buttonlike is-primary" href="/admin/?kind=blog">New article</a><a class="buttonlike" href="/admin/?kind=photography#upload">Upload pictures</a><a class="buttonlike" href="/admin/?kind=video#upload">Upload a video</a>');
    my @cards=(
        ['Pages',scalar(@{all_pages()}),'/admin/?kind=pages',scalar(grep {in_menu($_)} nav_items()).' in the navigation'],
        ['Pictures',$count->("SELECT count(*) FROM uploads WHERE kind='photography'"),'/admin/?kind=photography',megabytes($bytes->('photography'))],
        ['Music',$count->("SELECT count(*) FROM uploads WHERE kind='music'"),'/admin/?kind=music',megabytes($bytes->('music'))],
        ['Videos',$count->("SELECT count(*) FROM uploads WHERE kind='video'"),'/admin/?kind=video',megabytes($bytes->('video'))],
        ['Files',$count->("SELECT count(*) FROM uploads WHERE kind='file'"),'/admin/?kind=file',megabytes($bytes->('file'))],
        ['Articles',$count->('SELECT count(*) FROM posts WHERE published_at IS NOT NULL'),'/admin/?kind=blog',$count->('SELECT count(*) FROM posts WHERE published_at IS NULL').' drafts'],
    );
    print attention_html();
    print setup_todo_html();
    print '<div class="admin-cards">'.join('',map {'<a class="admin-card" href="'.h($_->[2]).'"><span class="admin-card__label">'.h($_->[0]).'</span><span class="admin-card__value">'.h($_->[1]).'</span><span class="admin-card__note">'.h($_->[3]).'</span></a>'} @cards).'</div>';

    my $drafts=(attempt {$db->selectall_arrayref('SELECT id,title,updated_at FROM posts WHERE published_at IS NULL ORDER BY updated_at DESC LIMIT 5',{Slice=>{}})}) // [];
    my $html=@$drafts ? '<ul class="admin-list">'.join('',map {'<li><a href="/admin/?kind=blog&amp;id='.h($_->{id}).'">'.h($_->{title}).'</a><span class="media-label">edited '.h(substr($_->{updated_at},0,10)).'</span></li>'} @$drafts).'</ul>'
        : '<p class="empty-media">No drafts. <a href="/admin/?kind=blog">Start an article</a>.</p>';
    my $comments='';
    my $c=comments_enabled() ? (attempt {comments_db()}) : undef;
    if ($c) {
        my $latest=(attempt {$c->selectall_arrayref('SELECT post_id,display,body,created_at FROM comments WHERE hidden=0 ORDER BY created_at DESC LIMIT 5',{Slice=>{}})}) // [];
        $comments=@$latest ? '<ul class="admin-list">'.join('',map {
            my $text=$_->{body};$text =~ s/\s+/ /g;$text=substr($text,0,140).(length($text)>140?'…':'');
            # What it's on: any library's item or a page (found even when it isn't public now).
            my ($kind,$id)=item_from_ref($_->{post_id});my $item=$kind ? item_find($kind,$id,all=>1) : undef;
            my $on=$item ? '<a href="'.h(item_path($item)).'" target="_blank" rel="noopener">'.h($item->{title}).'</a> ('.h(item_kinds()->{$kind}{one}).')' : '<em>something deleted</em>';
            '<li><span><strong>'.h($_->{display}).'</strong> on '.$on.': '.h($text).'</span><span class="media-label">'.h(substr($_->{created_at},0,10)).'</span></li>'
        } @$latest).'</ul><p><a href="/admin/comments/">All comments</a></p>' : '<p class="empty-media">No comments yet.</p>';
    } else {$comments='<p class="empty-media">Comments aren’t set up on the server.</p>'}
    print '<div class="admin-columns">';
    window('drafts',$html);
    window('latest comments',$comments);
    print '</div>';

    my $free=free_bytes($store);
    my @server;
    push @server,['Free disk space',sprintf('%.1f GB',$free/1024**3).' on the media disk'] if defined $free;
    push @server,['Media stored',megabytes($bytes->('photography')+$bytes->('music')+$bytes->('video')+$bytes->('file'))];
    push @server,['BlowfishCMS',$BlowfishCMS::VERSION];
    window('server','<dl class="admin-facts">'.join('',map {'<div><dt>'.h($_->[0]).'</dt><dd>'.h($_->[1]).'</dd></div>'} @server).'</dl>');
    end_page();
}

1;