BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
334 lines · 28.0 KB · download this file
package BlowfishCMS;
# The System screen (owners): update to an uploaded release, roll back, back up
# and download backups. The admin service runs without root, so it only files
# requests in $data/system/requests; `blowfishctl requests` (root's crontab,
# every minute) carries them out and writes each result and its log in
# $data/system/results, which the admin service can read but not change. See
# the request runner in bin/blowfishctl.
use v5.36;
use utf8;
use Encode qw(encode);
use JSON::PP ();
use POSIX qw(strftime);
our ($base,$data,$db,$q,$method,$csrf,$cookie_header,%instance);
our $stream_path; # a file handle_request sends after the headers (downloads)
# The System spool: requests/ and releases/ (the admin writes), results/ and
# downloads/ (root writes, the admin reads).
sub system_dir { "$data/system" }
# Whether the spool's folders exist and the admin can file requests.
sub system_ready { -d system_dir().'/requests' && -w system_dir().'/requests' && -d system_dir().'/results' }
# A JSON file's contents, or undef.
sub read_json_file ($path) {
open my $fh,'<:raw',$path or return undef;local $/;my $raw=<$fh>;close $fh;
return attempt {JSON::PP->new->decode($raw)};
}
# What the runner last reported (state.json): when it last looked, the kept
# releases, nightly backups, free space, whether the System screen is off.
sub system_state { return read_json_file(system_dir().'/results/state.json') // {} }
# Recent requests, newest first: {id, status, action, by, at}.
# Every request's result file, newest first.
sub system_results {
my $dir=system_dir().'/results';opendir my $dh,$dir or return [];
my @r=grep {ref eq 'HASH'} map {read_json_file("$dir/$_")} grep {/\A[a-f0-9]{32}\.json\z/} readdir $dh;
closedir $dh;
return [sort {($b->{at}//0) <=> ($a->{at}//0)} @r];
}
# The red "last request failed" note on the Add-ons and Themes screens. It
# shows for a day after the failure, and the × hides it for good in this
# browser (admin.js remembers the request's id).
sub request_failed_notice ($r) {
return '' unless $r && ($r->{status}//'') eq 'failed' && ($r->{id}//'') =~ /\A[a-f0-9]{32}\z/;
return '' if ($r->{action}//'') =~ /update_all\z|\Aupdates_all\z/; # updates_all_status_html says what happened
return '' if time-($r->{at}//0) > 86400;
return '<p class="panel-note admin-notice admin-notice--error admin-notice--dismissable" role="alert" data-dismiss="'.h($r->{id}).'">The last request ('.h(($r->{action}//'').' '.($r->{arg}//'')).') failed '.age_text(time-($r->{at}//0)).'. <a href="/admin/?kind=system&log='.h($r->{id}).'">See what happened</a>.'
.'<button type="button" class="notice-dismiss" aria-label="Hide this message" title="Hide this message" hidden>×</button></p>';
}
# Whether a request is waiting or running (only one at a time).
sub system_pending {
my $dir=system_dir().'/requests';opendir my $dh,$dir or return 0;
my $n=grep {/\A[a-f0-9]{32}\.json\z/} readdir $dh;closedir $dh;
return $n || scalar grep {($_->{status}//'') eq 'running'} @{system_results()};
}
# The backups offered for download (links the runner made), newest first.
# Only names of the shape the runner uses are listed.
sub system_backups {
my $dir=system_dir().'/downloads';opendir my $dh,$dir or return [];
my @b=map {{name=>$_,bytes=>(-s "$dir/$_")//0,at=>(stat "$dir/$_")[9]//0}} grep {/\A[a-z][a-z0-9-]*-\d{8}T\d{6}Z\.tar\.gz\z/} readdir $dh;
closedir $dh;
return [sort {$b->{at} <=> $a->{at}} @b];
}
# %extra: more for the runner to read, such as update_all's pinned versions.
# Files a request for root's runner: a small JSON file (what, an argument,
# who, when, and any extras), written under a temporary name and renamed into
# place so the runner never reads half of one. One at a time.
# A Repositories add-on's address updates can come from: https, a host, plain
# path words (as blowfishctl's address_ok and json_address check it again).
sub updates_address_ok ($a) { return length($a)<=300 && $a =~ m{\Ahttps://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._~-]+)*/?\z} ? 1 : 0 }
sub system_request ($action,$arg='',$id=random_id(),%extra) {
die "The server isn't set up for this yet. Update it once from the command line (doas blowfishctl update …), then try again.\n" unless system_ready();
die "The server is still busy with the last request. Wait for it to finish.\n" if system_pending();
my $file=system_dir()."/requests/$id.json";
open my $fh,'>:raw',"$file.tmp" or die "The request could not be filed.\n";
print {$fh} JSON::PP->new->canonical->encode({%extra,action=>$action,arg=>$arg,by=>signed_in_admin(),at=>time});
close $fh or die "The request could not be filed.\n";
rename "$file.tmp",$file or die "The request could not be filed.\n";
return $id;
}
# An uploaded archive (a release, add-ons, themes), saved for the request
# runner. $name says what to choose, $plural what's too large.
# Saves an uploaded archive for the runner: it must start with the gzip
# signature (bytes 1f 8b) and be under $mb MB; it's copied in 64 KB pieces
# to releases/ID.tar.gz. Returns the id.
sub system_upload ($field,$name,$plural,$mb) {
die "The server isn't set up for this yet. Update it once from the command line (doas blowfishctl update …), then try again.\n" unless system_ready();
die "The server is still busy with the last request. Wait for it to finish.\n" if system_pending();
my $up=$q->upload($field);
die "Choose the $name.\n" unless $up;
binmode $up;read($up,my $magic,2);seek($up,0,0);
die "That isn’t a .tar.gz archive.\n" unless $magic eq "\x1f\x8b";
my $id=random_id();my $to=system_dir()."/releases/$id.tar.gz";
open my $out,'>:raw',$to or die "The upload could not be saved.\n";
my $size=0;
while (read($up,my $buf,65536)) {
$size+=length $buf;
if ($size>$mb*1048576) {close $out;unlink $to;die "$plural are smaller than $mb MB.\n"}
print {$out} $buf;
}
close $out or do {unlink $to;die "The upload could not be saved.\n"};
chmod 0640,$to;
return $id;
}
# Uploads the admin takes, by the upload= in their form's address: the most
# each can be (in MB), and what's too large.
# The largest release (64 MB), add-ons and themes archive (32 MB) accepted.
# dispatch() uses these to refuse a too-large upload before reading it.
sub system_upload_limits { return {release=>[64,'Releases','system'],addons=>[32,'Add-on archives','addons'],themes=>[32,'Theme archives','themes']} }
# The Add-ons screen's and Themes tab's box of what can be installed: the
# list (archives owners uploaded, and those from the server's address when it
# has one), the upload form, and "check now" when there's an address.
# $kind is addons or themes; $rows the list's rows; $left how many aren't installed.
# The Add-ons screen's (and Themes tab's) box for adding new ones: what to
# do, the upload form (with "check now" when the server also fetches from an
# address), and the rows of what's in the list but not installed.
sub catalog_box ($kind,$list,$rows,$left,$ready,$pending) {
my ($one,$cmd)=$kind eq 'addons' ? ('add-on','addon') : ('theme','theme');
my $src=$list && length($list->{source}//'') ? $list->{source} : '';
my $html='<p>Upload a .tar.gz of '.($kind eq 'addons' ? 'an add-on’s' : 'a theme’s').' folder, or of several (a whole '.$one.'s archive), to add '.($kind eq 'addons' ? 'them' : 'them').' to the list below; '
.($kind eq 'addons' ? '<strong>install</strong> puts one on this server and switches it on' : '<strong>install</strong> adds its variants above, hidden until you show them')
.'. A newer version of one that’s installed appears as <strong>update to X</strong> above. Updates are never installed by themselves. Only upload '.$one.'s from a source you trust'.($kind eq 'addons' ? ': they run with the site’s rights.' : '.').'</p>';
if ($ready) {
$html.='<form method="post" action="/admin/?kind='.$kind.'&upload='.$kind.'" enctype="multipart/form-data" class="admin-form">'.fields($kind.'_upload',$kind)
.'<label>Upload '.$one.'s<input type="file" name="archive" accept=".gz,application/gzip" required><span class="optional">A .tar.gz, up to 32 MB. The server adds it to the list within a minute.</span></label>'
.'<button class="buttonlike" type="submit"'.($pending?' disabled':'').'>upload</button></form>';
$html.='<form method="post" action="/admin/" class="catalog-check"><p>This server also takes '.$one.'s from <code>'.h($src).'</code>, every night. '
.($list->{fetched} ? 'Checked '.age_text(time-$list->{fetched}).'.' : 'Not checked yet.').'</p>'.fields($kind.'_refresh',$kind)
.'<button class="buttonlike" type="submit"'.($pending?' disabled':'').'>check now</button></form>' if length $src;
}
else {$html.='<p>On this server, add them with <code class="addon-command">doas blowfishctl '.$cmd.' add FILE.tar.gz</code>.</p>'}
my @list=$list && ref $list->{$kind} eq 'ARRAY' ? @{$list->{$kind}} : ();
$html.=$left ? '<div class="theme-list">'.$rows.'</div>' : '<p class="empty-media">'.(@list ? "Every $one in the list is installed." : "No ${one}s uploaded yet.").'</p>';
return $html;
}
# Release ids are UTC timestamps (20261116T120000Z).
# "just now", "5 minutes ago", "2 hours ago", "3 days ago".
sub age_text ($secs) {
return 'just now' if $secs<90;
my ($n,$unit)=$secs<5400 ? (int($secs/60),'minute') : $secs<129600 ? (int($secs/3600),'hour') : (int($secs/86400),'day');
return "$n $unit".($n==1 ? '' : 's').' ago';
}
# How a running update is getting on, from the progress file blowfishctl
# writes at each step ({step, steps, key, label, started, at, done}), and the
# step times of the last update that finished (update-timings.json), which
# give the estimate. Returns undef when no update is running or waiting.
# How far a running update has got, for the progress bar. blowfishctl
# writes results/ID.progress at each step (which step, of how many, when it
# started). The time left is estimated from the last finished update's step
# times (update-timings.json): what's left of this step plus every step not
# reached yet. Without an earlier update to go by, the steps to come are
# assumed to take as long as those so far. Never shows more than 99% until
# it's done.
sub update_progress {
my $dir=system_dir();my $now=time;
my ($run)=grep {($_->{status}//'') eq 'running' && ($_->{action}//'') =~ /\Aupdate(?:_fetch)?\z/ && ($_->{id}//'') =~ /\A[a-f0-9]{32}\z/} @{system_results()};
unless ($run) {
# Uploaded, but the server hasn't started it yet (it looks every minute).
opendir my $dh,"$dir/requests" or return undef;
my @waiting=grep {((read_json_file("$dir/requests/$_")//{})->{action}//'') =~ /\Aupdate(?:_fetch)?\z/} grep {/\A[a-f0-9]{32}\.json\z/} readdir $dh;closedir $dh;
return @waiting ? {percent=>0,label=>'Waiting for the server to start the update (it looks every minute)',left=>undef} : undef;
}
my $p=read_json_file("$dir/results/$run->{id}.progress");
# No steps yet: the update has just started (blowfishctl hasn't written its
# first step), or its progress file is missing. Show it as moving.
return {percent=>undef,label=>'Updating… follow it in the log below',left=>undef,id=>$run->{id}} unless ref $p eq 'HASH' && $p->{steps};
my $last=read_json_file("$dir/results/update-timings.json");my %before=ref $last eq 'HASH' && ref $last->{done} eq 'HASH' ? %{$last->{done}} : ();
my %done=ref $p->{done} eq 'HASH' ? %{$p->{done}} : ();
my $key=$p->{key}//'';my $in_step=$now-($p->{at}//$now);my $elapsed=$now-($p->{started}//$now);
my $left;
if (%before) {
# What's left of this step, then every step the last update had that this one hasn't reached.
$left=($before{$key} // 0)-$in_step;$left=0 if $left<0;
$left+=$before{$_} for grep {!exists $done{$_} && $_ ne $key} keys %before;
} elsif (($p->{step}//0)>=3) {
# No earlier update to go by: assume the steps to come take as long as those so far.
my $per=$elapsed/(($p->{step}-1)||1);$left=$per*($p->{steps}-$p->{step}+1)-$in_step;$left=0 if $left<0;
}
my $percent=defined $left && $elapsed+$left>0 ? 100*$elapsed/($elapsed+$left) : 100*(($p->{step}//1)-1)/$p->{steps};
$percent=99 if $percent>99;
return {percent=>int($percent),label=>$p->{label}//'Updating',left=>$left,step=>$p->{step},steps=>$p->{steps},elapsed=>$elapsed,id=>$run->{id}};
}
# The time left in words.
sub left_text ($secs) {
return 'Estimating the time left…' unless defined $secs;
return 'Almost done' if $secs<20;
return 'Less than a minute left' if $secs<60;
my $m=int(($secs+30)/60);return "About $m minute".($m==1?'':'s').' left';
}
# The System screen (owners):
# ?download=NAME sends a backup; the file itself is streamed after the
# headers by handle_request ($stream_path), so a large
# backup is never held in memory
# ?log=ID one request's log (refreshing while it runs)
# actions system_update (an uploaded release), system_update_fetch
# (the newest published release), system_releases_check,
# system_updates_from (where updates come from: an address
# sent as the request's "address", kept by root),
# system_rollback, system_backup, backup_plan (nightly
# backups on or off and how many to keep), backup_remove
# Then the screen: a warning if the runner hasn't checked in for 5 minutes
# (unless a long request is visibly running), the progress of an update,
# the release and its update and roll-back forms, the backups, and recent
# requests. While something runs, the page refreshes itself (data-refresh,
# read by admin.js).
sub system_admin {
my $message=param('notice',2000);
# Downloads and logs.
if ($method eq 'GET' && length(my $name=param('download',80))) {
my ($b)=grep {$_->{name} eq $name} @{system_backups()};
unless ($b) {header(404,'text/plain; charset=UTF-8');print 'That backup is no longer available.';return}
header(200,'application/gzip',"Content-Disposition: attachment; filename=\"$b->{name}\"\r\nContent-Length: $b->{bytes}\r\nCache-Control: no-store\r\n");
$stream_path=system_dir()."/downloads/$b->{name}" unless $method eq 'HEAD';
return;
}
if ($method eq 'GET' && length(my $id=param('log',32))) {
unless ($id =~ /\A[a-f0-9]{32}\z/ && -f system_dir()."/results/$id.json") {header(404,'text/plain; charset=UTF-8');print 'No such request.';return}
my $log='';
if (open my $fh,'<:encoding(UTF-8)',system_dir()."/results/$id.log") {local $/;$log=<$fh>//'';close $fh}
my $r=read_json_file(system_dir()."/results/$id.json") // {};
admin_page('Request log',section=>'system',crumbs=>[['System','/admin/?kind=system']],intro=>h(ucfirst($r->{action}//'request')).' by '.h($r->{by}//'?').' · '.h($r->{status}//'unknown'));
print '<div data-refresh="'.(($r->{status}//'') eq 'running' ? 5 : 0).'"></div>';
window('log','<pre class="system-log">'.h(length $log ? $log : 'Nothing logged yet.').'</pre>');
end_page();return;
}
if ($method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'system_update') {my $id=system_upload('release','release (blowfishcms.tar.gz)','Releases',64);system_request('update','',$id);redirect('/admin/?kind=system¬ice='.CGI::escape('Release uploaded. The server installs it within a minute or two; follow it below.'))}
if ($action eq 'system_update_fetch') {
my $l=release_newer() or die "There’s no newer release to install. Check for updates first.\n";
die "That release has changed since this page was opened. Reload and try again.\n" unless param('version',20) eq $l->{version};
system_request('update_fetch',$l->{version});
redirect('/admin/?kind=system¬ice='.CGI::escape("Updating to $l->{version}. The server fetches it, checks its sha256 and installs it, tests first."));
}
if ($action eq 'system_releases_check') {system_request('releases_refresh');redirect('/admin/?kind=system¬ice='.CGI::escape('Checking for a new release.').'#release')}
# Where updates come from: a Repositories address, kept by root (blowfishctl updates-from).
if ($action eq 'system_updates_from') {
my $a=param('address',300);my $v=length $a ? $a : 'none';
die "Updates from: a Repositories add-on’s address, such as https://example.org/x/repos/.\n" unless $v eq 'none' || updates_address_ok($v);
system_request('updates_from','',random_id(),address=>$v);
redirect('/admin/?kind=system¬ice='.CGI::escape(length $a ? "Updates will come from $a. The server looks there within a minute." : 'Updates won’t be looked for. Upload releases instead.').'#updates-from');
}
if ($action eq 'system_rollback') {system_request('rollback');redirect('/admin/?kind=system¬ice='.CGI::escape('Rollback requested. The server puts the previous release back within a minute or two.'))}
if ($action eq 'system_backup') {system_request('backup');redirect('/admin/?kind=system¬ice='.CGI::escape('Backup requested. It appears under Backups when it’s ready.'))}
if ($action eq 'backup_plan') {
my $keep=param('backup_keep',3);
die "Keep between 1 and 30 nightly backups.\n" unless $keep =~ /\A\d+\z/ && $keep>=1 && $keep<=30;
setting_save(backup_nightly=>(param('backup_nightly',1) eq '1' ? '1' : '0'),backup_keep=>$keep);
redirect('/admin/?kind=system¬ice='.CGI::escape(param('backup_nightly',1) eq '1' ? "Saved: a backup every night, keeping the newest $keep." : 'Saved: nightly backups are off.').'#nightly');
}
if ($action eq 'backup_remove') {
my $name=param('name',80);die "That backup is no longer available.\n" unless grep {$_->{name} eq $name} @{system_backups()};
system_request('backup_remove',$name);redirect('/admin/?kind=system¬ice='.CGI::escape("Removing $name."));
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
my $state=system_state();my $pending=system_pending();my $results=system_results();
admin_page('System',section=>'system',notice=>$message,intro=>'Update the site, go back to the previous release, and make and download backups. The server carries these out within a minute.');
unless (system_ready()) {
window('not set up yet','<p>This server hasn’t been set up for the System screen. Update it once from the command line (<code>doas blowfishctl update …</code>); after that, updates can be made here.</p>');
end_page();return;
}
if ($state->{off}) {
window('turned off','<p>The System screen is turned off on this server, so updates and backups are made from the command line. <code>doas rm /etc/blowfishcms-no-system</code> on the server turns it back on.</p>');
end_page();return;
}
my $seen=$state->{checked} ? time-$state->{checked} : undef;
# While a request runs (an update takes many minutes), the runner holds its
# lock and the minute-by-minute check-ins stop; it's alive as long as the
# request's log or progress keeps changing.
$seen=undef if defined $seen && grep {my $id=$_->{id}//'';($_->{status}//'') eq 'running' && $id =~ /\A[a-f0-9]{32}\z/
&& grep {defined && time-$_ < 900} map {(stat(system_dir()."/results/$id.$_"))[9]} qw(log progress)} @{system_results()};
my $progress=update_progress();
print '<div data-refresh="'.($progress ? 5 : $pending ? 10 : 0).'"></div>';
print '<p class="panel-note admin-notice admin-notice--error" role="alert">The server hasn’t picked up requests '.(defined $seen ? 'for '.age_text($seen) =~ s/ ago\z//r : 'yet').'. Check root’s crontab has the BlowfishCMS lines (<code>doas blowfishctl httpd</code> puts them back).</p>' if defined $seen ? $seen>300 : !$state->{checked};
print '<p class="panel-note">Working on a request… this page refreshes by itself.</p>' if $pending && !$progress;
my $kept=$state->{kept}//[];
my $off=$pending ? ' disabled' : '';
# A running update: how far it's got, what it's doing and how long is left.
window('updating','<div class="system-progress" role="status" aria-live="polite">'
.'<progress max="100"'.(defined $progress->{percent} ? ' value="'.$progress->{percent}.'"' : '').' aria-label="Update progress">'.($progress->{percent}//0).'%</progress>'
.'<p class="system-progress__step">'.h($progress->{label}).'</p>'
.'<p class="media-label">'.join(' · ',grep {length}
(defined $progress->{percent} ? $progress->{percent}.'%' : ''),
($progress->{steps} ? "step $progress->{step} of $progress->{steps}" : ''),
(defined $progress->{percent} || $progress->{id} ? left_text($progress->{left}) : ''),
($progress->{elapsed} ? 'started '.age_text($progress->{elapsed}) : '')).'</p>'
.($progress->{id} ? '<p><a href="/admin/?kind=system&log='.h($progress->{id}).'">see the log</a></p>' : '').'</div>') if $progress;
# The release: what runs, an update to upload, and going back.
my $back=ref $state->{kept_versions} eq 'ARRAY' && length($state->{kept_versions}[0]//'') && $state->{kept_versions}[0] ne 'unknown' ? $state->{kept_versions}[0] : '';
my $l=release_newer();my $checked=releases_checked();
my $latest=$l ? '<div class="release-new"><p><strong>BlowfishCMS '.h($l->{version}).' is available.</strong> '
.(length($l->{page}//'') ? '<a href="'.h($l->{page}).'" target="_blank" rel="noopener">What’s new ↗</a>' : '').'</p>'
.'<form method="post" action="/admin/">'.fields('system_update_fetch','system').hidden(version=>$l->{version}).'<button class="buttonlike is-primary" type="submit"'.$off.'>update to '.h($l->{version}).'</button> '
.'<span class="optional">Fetched from where updates come from and checked against its published sha256, then installed like an upload: tests first, and the live release put back by itself if the site doesn’t come up.</span></form></div>'
: '<p class="media-label">'.(!length($state->{updates_from}//'') && !length($state->{releases_url}//'') ? 'New releases aren’t looked for: set where updates come from below, or upload them.'
: $checked ? 'This is the newest release (checked '.h(age_text(time-$checked)).').' : 'Not checked for new releases yet.').'</p>';
$latest.='<form method="post" action="/admin/" class="release-check">'.fields('system_releases_check','system').'<button class="text-button" type="submit"'.$off.'>check for updates</button></form>'
if length($state->{updates_from}//'') || length($state->{releases_url}//'');
# Where updates come from: one Repositories address (blowfishctl updates-from).
$latest.='<form method="post" action="/admin/" class="admin-form release-source" id="updates-from">'.fields('system_updates_from','system')
.'<label>Updates from<input name="address" type="url" maxlength="300" value="'.h($state->{updates_from}//'').'" placeholder="https://example.org/x/repos/">'
.'<span class="optional">A Repositories add-on’s address. New releases are its <code>blowfishcms</code> repository’s newest; add-ons and themes, its <code>blowfishcms-addons</code> and <code>blowfishcms-themes</code> archives. Leave it empty to only upload them.'
.(length($state->{releases_url}//'') ? ' This server’s <code>/etc/blowfishcms-releases-url</code> names where releases come from, before this.' : '').'</span></label>'
.'<button class="buttonlike" type="submit"'.$off.'>save</button></form>';
window('release','<p>This site runs BlowfishCMS <strong>'.h($BlowfishCMS::VERSION).'</strong>.</p>'.$latest
.'<form method="post" action="/admin/?kind=system&upload=release" enctype="multipart/form-data" class="admin-form">'.fields('system_update','system')
.'<label>Or upload a release<input type="file" name="release" accept=".gz,application/gzip" required><span class="optional"><code>blowfishcms.tar.gz</code>. Only install releases from a source you trust, such as the BlowfishCMS repository: an update runs with full control of the server. The tests run first, and a failed update puts the live release back by itself.</span></label>'
.'<button class="buttonlike is-primary" type="submit"'.$off.'>update</button></form>'
.'<form method="post" action="/admin/" class="system-rollback delete-form" data-confirm="Put back the previous release? The catalogue stays as it is.">'.fields('system_rollback','system')
.'<button class="buttonlike" type="submit"'.(@$kept ? $off : ' disabled').'>roll back'.(length $back ? ' to '.h($back) : '').'</button> <span class="optional">'.(@$kept ? 'Puts back the release from before the last update. Your pages, pictures and settings stay as they are.' : 'There’s no earlier release to go back to.').'</span></form>');
my $b=system_backups();
my $n=$state->{nightly}//{};my $on=setting('backup_nightly') ne '0';
my $last=!$n->{at} ? 'hasn’t run yet (it runs between 3 and 4 a.m., server time)'
: ($n->{status} eq 'done' ? 'made a backup ' : $n->{status} eq 'off' ? 'was off ' : 'failed ').age_text(time-$n->{at}).($n->{status} eq 'failed' && length $n->{message} ? ': '.h($n->{message}) : '');
# Backups: what the server keeps, the newest to download, back up now, and the nightly plan.
window('backups','<p>A backup holds the catalogue, media, settings, comments and code, as <code>blowfishctl backup</code> makes it (passwords and tokens aren’t included). The server makes one every night and keeps the newest of these; backups made with <b>back up now</b>, and the snapshots updates take, are never removed by it. Download them and keep them somewhere other than this server.</p>'
.'<dl class="system-facts"><dt>Last night</dt><dd class="'.(($n->{status}//'') eq 'failed' ? 'system-status--failed' : '').'">'.$last.'</dd>'
.'<dt>Nightly backups kept</dt><dd>'.($n->{count}//0).' ('.megabytes($n->{bytes}//0).')</dd>'
.(defined $state->{free} ? '<dt>Free space for backups</dt><dd>'.megabytes($state->{free}).'</dd>' : '').'</dl>'
.'<form method="post" action="/admin/" class="admin-form">'.fields('system_backup','system').'<button class="buttonlike" type="submit"'.$off.'>back up now</button></form>'
.admin_list([map {admin_row(title=>$_->{name},meta=>[megabytes($_->{bytes}),age_text(time-$_->{at})],
actions=>'<a class="buttonlike" href="/admin/?kind=system&download='.h($_->{name}).'" download>download</a>',
menu=>'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete $_->{name} from the server? This can't be undone.").'">'.fields('backup_remove','system').hidden(name=>$_->{name}).'<button class="text-button danger" type="submit">delete</button></form>')} @$b],empty=>'No backups to download yet.')
.'<form method="post" action="/admin/" class="admin-form system-backup-plan" id="nightly">'.fields('backup_plan','system')
.'<div class="system-backup-plan__row">'.switch_field('backup_nightly','Back up every night, keeping the newest',$on)
.'<input type="number" name="backup_keep" min="1" max="30" value="'.h(setting('backup_keep')).'" required aria-label="Nightly backups to keep">'
.'<button class="buttonlike" type="submit">save</button></div><p class="optional">Keep 1 to 30. Each is about the size of your media.</p></form>');
window('recent requests',@$results ? '<table class="system-requests"><thead><tr><th>When</th><th>What</th><th>By</th><th>Result</th><th></th></tr></thead><tbody>'
.join('',map {'<tr><td>'.h(strftime('%Y-%m-%d %H:%M',gmtime($_->{at}//0))).' UTC</td><td>'.h($_->{action}//'').'</td><td>'.h($_->{by}//'').'</td><td class="system-status system-status--'.h($_->{status}//'').'">'.h($_->{status}//'').'</td><td><a href="/admin/?kind=system&log='.h($_->{id}).'">log</a></td></tr>'} grep {($_->{id}//'') =~ /\A[a-f0-9]{32}\z/} @$results[0..($#$results<9?$#$results:9)]).'</tbody></table>' : '<p class="empty-media">Nothing yet.</p>');
end_page();
}
1;