BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
235 lines · 15.7 KB · download this file
package BlowfishCMS;
# Notifications: newer releases of BlowfishCMS, and of the add-ons and themes
# installed, found by the server's nightly check (or "check now"). Owners see
# them in the admin (a count in the sidebar, a pop-up the first time, and the
# Notifications screen) and, when an alerts address is set on the Mail
# screen, by email.
# Every BlowfishCMS/*.pm file adds subs to the one BlowfishCMS package.
use v5.36;
use utf8;
use JSON::PP qw(encode_json decode_json);
use Encode qw(decode encode);
our ($db,$method,$csrf);
# admin_notices: per owner, each notice they've seen (the pop-up shows once)
# or dismissed. notices_emailed: the notices already emailed to the alerts
# address.
sub ensure_notice_tables {
# What each owner has seen (the pop-up shows once) or dismissed.
$db->do('CREATE TABLE IF NOT EXISTS admin_notices (user TEXT NOT NULL, key TEXT NOT NULL, state TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY(user,key))');
# Which notices the alerts address has been sent.
$db->do('CREATE TABLE IF NOT EXISTS notices_emailed (key TEXT PRIMARY KEY, at TEXT NOT NULL)');
}
# The newest BlowfishCMS release where updates come from, as the server last found it.
sub releases_latest {
my $r=read_json_file(system_dir().'/results/releases.json');
return ref $r eq 'HASH' && ref $r->{latest} eq 'HASH' && ($r->{latest}{version}//'') =~ /\A\d+\.\d+\.\d+\z/ ? $r->{latest} : undef;
}
# When the server last looked for a new release.
sub releases_checked { my $r=read_json_file(system_dir().'/results/releases.json');return ref $r eq 'HASH' ? $r->{fetched} : undef }
# The newest release, if it's newer than this one.
sub release_newer { my $l=releases_latest();return $l && version_cmp($l->{version},$BlowfishCMS::VERSION)>0 ? $l : undef }
# Installed add-ons and themes with a newer version in their list:
# {type (addon|theme), name, label, from, to, needs (the BlowfishCMS release it
# needs, when this one is older)}. The notices, the Add-ons and Themes screens'
# "update all" and `site.pl --updates` (for the server's runner) all use it.
sub pending_updates {
my @u;
my %addons=map {($_->{name}=>$_)} grep {ref eq 'HASH'} @{(addons_catalog()//{})->{addons}//[]};
my $installed=(attempt {addons_available()}) // {};
for my $name (sort keys %$installed) {
my $m=$installed->{$name};my $o=$addons{$name} or next;
next unless version_cmp($o->{version}//'0',$m->{version}//'0')>0;
push @u,{type=>'addon',name=>$name,label=>$m->{label}//$name,from=>$m->{version},to=>$o->{version},needs=>(version_cmp($BlowfishCMS::VERSION,$o->{blowfishcms}//'0')<0 ? $o->{blowfishcms} : undef)};
}
my %themes=map {($_->{name}=>$_)} @{themes_catalog()};
my $packages=(attempt {theme_packages()}) // {};
for my $name (sort keys %$packages) {
my $m=$packages->{$name};next if $m->{core};my $o=$themes{$name} or next;
next unless version_cmp($o->{version}//'0',$m->{version}//'0')>0;
push @u,{type=>'theme',name=>$name,label=>$m->{label}//$name,from=>$m->{version},to=>$o->{version},needs=>(version_cmp($BlowfishCMS::VERSION,$o->{blowfishcms}//'0')<0 ? $o->{blowfishcms} : undef)};
}
return @u;
}
# ---- Updating all of them in one request -------------------------------------------------
# One request names each add-on or theme and the version shown, so the runner
# installs what the owner saw (one published since is skipped and named).
# $type: addon, theme or all; the request's action says which screen sent it.
my %update_all_action=(addon=>'addons_update_all',theme=>'themes_update_all',all=>'updates_all');
# The updates that can be installed now (not needing a newer BlowfishCMS).
sub updates_ready ($type) { return grep {!$_->{needs} && ($type eq 'all' || $_->{type} eq $type)} pending_updates() }
# Files one request to update several add-ons and/or themes. It "pins" each
# one to the version shown (TYPE:NAME:VERSION), so the runner installs what
# the owner saw: one published since is skipped rather than installed
# unseen.
sub updates_all_request ($type) {
my @u=updates_ready($type);
die "There's nothing to update.\n" unless @u;
system_request($update_all_action{$type},'',random_id(),pins=>[map {"$_->{type}:$_->{name}:$_->{to}"} @u]);
return 'Updating '.(@u==1 ? $u[0]{label} : scalar(@u).' '.($type eq 'addon' ? 'add-ons' : $type eq 'theme' ? 'themes' : 'add-ons and themes')).'. The server does them one at a time, within a few minutes.';
}
# The button, when there are at least $min to update (2 on the Add-ons and
# Themes screens, beside each one's own; 1 on Notifications).
# The "update all" button, when there are at least $min updates and the
# System runner is available.
sub update_all_button_html ($type,$kind,$min=2,$short=0) {
my @u=updates_ready($type);
return '' unless @u>=$min && system_ready() && !system_state()->{off};
my $what=$type eq 'addon' ? 'add-ons' : $type eq 'theme' ? 'themes' : 'add-ons and themes';
return '<form method="post" action="/admin/" class="update-all">'.fields($update_all_action{$type},$kind)
.'<button class="buttonlike is-primary" type="submit"'.(system_pending() ? ' disabled' : '').'>update all '.($short ? '' : $what.' ').'('.scalar(@u).')</button>'
.'<span class="optional">'.h(join ', ',map {"$_->{label} $_->{to}"} @u).'</span></form>';
}
# While one runs: "Updating 3 of 7: Music". For a day after: what it did.
# What the last "update all" did, read from its log: "Updating 3 of 7: Music"
# while it runs, then its summary for a day.
sub updates_all_status_html ($re) {
my ($r)=grep {($_->{action}//'') =~ $re} @{system_results()};
return '' unless $r && ($r->{id}//'') =~ /\A([a-f0-9]{32})\z/;
my $id=$1;my $status=$r->{status}//'';
return '' if $status ne 'running' && time-($r->{at}//0)>86400;
open my $fh,'<:encoding(UTF-8)',system_dir()."/results/$id.log" or return '';
my ($step,$summary,$error);while (<$fh>) {$step=$1 if /\bupdating (\d+ of \d+: .+?)\s*\z/;$summary=$1 if /\bsummary: (.+?)\s*\z/;$error=$1 if /\berror: (.+?)\s*\z/}
close $fh;
# Stopped before updating anything (the lists couldn't be read).
$summary="nothing was updated ($error)" if !defined $summary && $status eq 'failed' && defined $error;
return '<p class="panel-note" role="status">Updating '.h($step//'…').'</p>' if $status eq 'running';
return '' unless defined $summary;
my $class=$status eq 'failed' ? ' admin-notice admin-notice--error' : '';
return '<p class="panel-note'.$class.'" role="status">The last update all: '.h($summary).' <a href="/admin/?kind=system&log='.$id.'">its log</a></p>';
}
# Everything owners should know about now, newest release first, as
# {key, title, text, href}. A key names the version (core:0.40.0,
# addon:store:1.3.0), so a newer version is a new notice, even after the
# last one was dismissed.
sub notices_all {
my @n;
if (my $l=release_newer()) {
push @n,{key=>"core:$l->{version}",title=>"BlowfishCMS $l->{version} is available",text=>"This site runs $BlowfishCMS::VERSION. Update it from the System screen.",href=>'/admin/?kind=system#release'};
}
for my $u (grep {!$_->{needs}} pending_updates()) {
push @n,$u->{type} eq 'addon'
? {key=>"addon:$u->{name}:$u->{to}",title=>"$u->{label} $u->{to} is available",text=>'The add-on is at '.($u->{from}//'an unknown version').'. Update it on the Add-ons screen.',href=>'/admin/?kind=addons'}
: {key=>"theme:$u->{name}:$u->{to}",title=>"The theme $u->{label} $u->{to} is available",text=>'It is at '.($u->{from}//'an unknown version').'. Update it on the Themes tab.',href=>'/admin/?kind=themes'};
}
return @n;
}
# Whose notice states to use: the signed-in owner.
sub notice_user { return signed_in_admin() // 'admin' }
# This owner's states, {key => seen|dismissed}.
sub notice_states {
my $rows=(attempt {$db->selectall_arrayref('SELECT key,state FROM admin_notices WHERE user=?',undef,notice_user())}) // [];
return map {($_->[0]=>$_->[1])} @$rows;
}
# The notices this owner hasn't dismissed (editors have none: updates are for owners).
# The notices an owner hasn't dismissed. Editors get none.
sub notices_open {
return () unless is_owner();
my %state=notice_states();
return grep {($state{$_->{key}}//'') ne 'dismissed'} notices_all();
}
# Records that an owner has seen or dismissed a notice. "seen" never
# overwrites "dismissed". Returns undef where the catalogue can't be written
# (services other than the admin).
sub notice_mark ($key,$state) {
return attempt {$db->do('INSERT INTO admin_notices (user,key,state,at) VALUES (?,?,?,?) ON CONFLICT(user,key) DO UPDATE SET state=excluded.state,at=excluded.at'
.($state eq 'seen' ? " WHERE admin_notices.state<>'dismissed'" : ''),undef,notice_user(),$key,$state,now())};
}
# The pop-ups for this page: notices this owner hasn't seen yet, shown once.
# The pop-ups ("toasts") for this admin page: notices this owner hasn't seen
# yet, each shown once. They're only shown where "seen" could be recorded,
# so they never repeat. Several add-on and theme updates at once become one
# pop-up with "update all".
sub notice_toasts {
my %state=notice_states();
my @new=grep {!exists $state{$_->{key}}} notices_open();
# Only where "seen" can be saved (the admin service), so a pop-up never repeats.
@new=grep {defined notice_mark($_->{key},'seen')} @new;
return '' unless @new;
my $close='<button class="toast__close" type="button" data-toast-close aria-label="Close">×</button>';
my @one=grep {$_->{key} =~ /\Acore:/} @new;my @parts=grep {$_->{key} !~ /\Acore:/} @new;
# Several add-on and theme updates at once are one pop-up, with "update all".
my $parts=@parts>=2 && update_all_button_html('all','notices',2,1);
@one=@new unless $parts;
return '<div class="toasts" role="status" aria-live="polite">'.join('',map {'<div class="toast" data-toast><p><strong>'.h($_->{title}).'</strong> '.h($_->{text}).'</p>'
.'<p class="toast__actions"><a class="buttonlike is-primary" href="'.h($_->{href}).'">open</a> <a class="text-button" href="/admin/?kind=notices">all notifications</a></p>'.$close.'</div>'} @one)
.($parts ? '<div class="toast" data-toast><p><strong>'.scalar(@parts).' updates for add-ons and themes</strong></p><div class="toast__actions">'.$parts
.' <a class="text-button" href="/admin/?kind=notices">see them</a></div>'.$close.'</div>' : '').'</div>';
}
# The Notifications screen.
# The Notifications screen: every notice with open and dismiss, "update all",
# what the last "update all" did, and "check now" (a request for the runner).
sub notices_admin {
my $message=param('notice',2000);
if ($method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'notice_dismiss') {
my $key=param('key',100);die "Choose a notification.\n" unless $key =~ /\A[a-z]+:[a-z0-9.:-]+\z/;
notice_mark($key,'dismissed');redirect('/admin/?kind=notices¬ice=Dismissed.');
}
if ($action eq 'updates_all') {redirect('/admin/?kind=notices¬ice='.CGI::escape(encode('UTF-8',updates_all_request('all'))))}
if ($action eq 'updates_check') {
system_request('updates_check');
redirect('/admin/?kind=notices¬ice='.CGI::escape('Checking for updates. This page shows what the server finds within a minute or two.'));
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
my $ready=system_ready() && !system_state()->{off};my $pending=$ready && system_pending();
admin_page('Notifications',section=>'notices',notice=>$message,intro=>'Updates for BlowfishCMS and for the add-ons and themes installed here. The server checks every night; an alerts address on the Mail screen gets them by email too.');
print '<div data-refresh="'.($pending ? 10 : 0).'"></div>';
print updates_all_status_html(qr/update_all\z|\Aupdates_all\z/),update_all_button_html('all','notices',1);
my %state=notice_states();my @all=notices_all();
my $list=join '',map {my $n=$_;my $done=($state{$n->{key}}//'') eq 'dismissed';
admin_row(title=>$n->{title},off=>$done,text=>h($n->{text}),meta=>[$done ? 'dismissed' : ()],
actions=>'<a class="buttonlike is-primary" href="'.h($n->{href}).'">open</a>'
.($done ? '' : '<form method="post" action="/admin/">'.fields('notice_dismiss','notices').hidden(key=>$n->{key}).'<button class="buttonlike" type="submit">dismiss</button></form>'))} @all;
my $checked=releases_checked();
window('notifications',admin_list($list,empty=>'Everything is up to date.')
.'<div class="box-part"><p class="media-label">'.($checked ? 'Last checked '.h(age_text(time-$checked)).'.' : 'Not checked yet.').'</p>'
.($ready ? '<form method="post" action="/admin/">'.fields('updates_check','notices').'<button class="buttonlike" type="submit"'.($pending ? ' disabled' : '').'>check now</button></form>'
: '<p>On this server, run <code>doas blowfishctl check-updates</code>.</p>').'</div>');
end_page();
}
# For blowfishctl: the notices the alerts address hasn't been sent yet, as one
# JSON line for --alert-mail (nothing when there are none).
# For blowfishctl's nightly check (as the admin's account): the notices not
# emailed yet, as one JSON line for --alert-mail.
sub notices_pending_json {
my %sent=map {($_=>1)} @{(attempt {$db->selectcol_arrayref('SELECT key FROM notices_emailed')}) // []};
my @new=grep {!$sent{$_->{key}}} notices_all();
return @new ? JSON::PP->new->utf8->canonical->encode({site=>setting('site_title'),domain=>$BlowfishCMS::instance{domain},notices=>\@new}) : '';
}
# Records every current notice as emailed. Returns how many were new.
sub notices_mark_emailed {
my $n=0;
for my $x (notices_all()) {$n+=$db->do('INSERT OR IGNORE INTO notices_emailed (key,at) VALUES (?,?)',undef,$x->{key},now())>0 ? 1 : 0}
return $n;
}
# Run as the contact form's account (it holds the Postmark token): emails the
# notices read from standard input to the alerts address. Exit 0 when sent, 3
# when there's no alerts address or token yet (they wait), 1 when it failed.
# site.pl --alert-mail, run as the contact service's account (the only one
# with the Postmark token): reads the notices from standard input and emails
# them to the alerts address. The three steps (pending, send, mark sent) run
# as different accounts because no single account may do all three.
sub alert_mail_cli {
my $raw=do {local $/;<STDIN>}//'';
my $in=attempt {JSON::PP->new->utf8->decode($raw)};
return 0 unless ref $in eq 'HASH' && ref $in->{notices} eq 'ARRAY' && @{$in->{notices}};
my $to=mail_config()->{alerts}//'';
unless (mail_address_ok($to)) {say 'No alerts address is set on the Mail screen; nothing sent.';return 3}
my $token=mail_token();
unless (length $token) {say 'No Postmark token is saved; nothing sent.';return 3}
my $site='https://'.($in->{domain}//$BlowfishCMS::instance{domain});
my @n=grep {ref eq 'HASH'} @{$in->{notices}};
my $body="Updates are available for ".($in->{site}//$site).":\n\n".join('',map {"- $_->{title}. $_->{text}\n $site$_->{href}\n"} @n)
."\nNothing is installed until an owner presses update. These alerts go to $to; change or remove the address on the Mail screen ($site/admin/mail/).\n";
my ($status,$reply)=postmark_send($token,To=>$to,Subject=>'['.($in->{domain}//$BlowfishCMS::instance{domain}).'] '.(@n==1 ? $n[0]{title} : scalar(@n).' updates are available'),TextBody=>$body);
if ($status==200 && defined $reply->{ErrorCode} && $reply->{ErrorCode}==0) {contact_log('Update alert accepted '.($reply->{MessageID}//''));say "Sent to $to.";return 0}
contact_log('Update alert failed; HTTP='.$status.' errorCode='.($reply->{ErrorCode}//-1));
print STDERR postmark_problem($reply->{ErrorCode}//0,$status),"\n";return 1;
}
1;