BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
262 lines · 17.0 KB · download this file
package BlowfishCMS;
# Site settings: the site's name, footer, favicon, author and the other values
# every page uses. Stored in the site_settings table (see setting() in
# BlowfishCMS.pm); the favicon's images live in the media folder under site/.
use v5.36;
use utf8;
use Encode qw(decode encode FB_CROAK);
our ($base,$data,$store,$db,$q,$method,$csrf,%instance);
# The fields on the settings screen: key, label, maximum length, kind, help.
sub settings_fields {
return (
[site_title=>'Site name',80,'text','Shown at the top of every page and in browser tabs.'],
[footer_text=>'Footer',600,'area','Shown at the bottom of every page. Links work as [text](https://example.org); {year} is this year and {site} the site name. Leave empty for no footer.'],
[author=>'Author',80,'text','Your name, or the organisation behind the site. Used in article bylines and for search engines.'],
[description=>'Site description',300,'area','The summary search engines and link previews use when a page has no description of its own.'],
);
}
# Saves settings (insert, or update if the key exists) and forgets the
# request's cached settings so the new values are read.
sub setting_save (%values) {
my $sth=$db->prepare('INSERT INTO site_settings(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value');
$sth->execute($_,$values{$_}) for sort keys %values;
undef $BlowfishCMS::settings_cache;
}
# The footer text as HTML: {year} and {site} filled in (the site name with
# Markdown's special characters escaped, so a name with * or _ shows as is),
# then Markdown, without the paragraph around it.
sub footer_html {
my $text=setting('footer_text');
return '' unless length $text;
# {year} and {site} keep a copyright line current.
$text =~ s/\{year\}/(gmtime)[5]+1900/ge;$text =~ s/\{site\}/setting('site_title') =~ s{[\\`*_\[\]]}{\\$&}gr/ge;
my $html=render_markdown($text);
$html =~ s{</?p>}{}g;$html =~ s/\s+\z//;
return $html;
}
# ---- Favicon ----------------------------------------------------------------
# An uploaded picture is cropped to a square and saved as PNGs in three sizes:
# 32 (browser tabs), 180 (phone home screens) and 512 (app installs, search).
sub favicon_sizes { return (32,180,512) }
# A favicon file's name for a size.
sub favicon_file ($id,$size) { return "icon-$id-$size.png" }
# Makes the favicon from an upload: cropped to a square from the middle and
# saved as PNGs at 32, 180 and 512 px (written to temporary files and renamed
# into place). If one fails, the others are removed. Returns the new id.
sub favicon_save ($fh) {
die "Choose a PNG, JPEG or WebP picture.\n" unless $fh;
binmode $fh;seek($fh,0,0);my $bytes='';
while (read($fh,my $part,65536)) {$bytes.=$part;die "The picture must be 10 MB or smaller.\n" if length($bytes)>10*1048576}
my $image=decode_image($bytes);
my ($w,$h)=$image->getBounds;my $side=$w<$h?$w:$h;
die "Use a picture at least 32 pixels on each side.\n" if $side<32;
my $dir="$store/site";
mkdir $dir,0755 unless -d $dir;
-d $dir && -w $dir or die "The media folder for site files can't be written.\n";
my $id=substr(random_id(),0,12);my @made;
attempt {
for my $size (favicon_sizes()) {
my $out=GD::Image->newTrueColor($size,$size);$out->alphaBlending(0);$out->saveAlpha(1);
$out->copyResampled($image,0,0,int(($w-$side)/2),int(($h-$side)/2),$size,$size,$side,$side);
my $path="$dir/".favicon_file($id,$size);push @made,$path;
open my $fh,'>:raw',"$path.tmp" or die "Cannot save the favicon.\n";print {$fh} $out->png(9);close $fh or die "Cannot save the favicon.\n";
rename "$path.tmp",$path or die "Cannot save the favicon.\n";chmod 0644,$path;
}
1;
} or do {my $e=$@;unlink @made,map {"$_.tmp"} @made;die $e};
return $id;
}
# Deletes a favicon's files.
sub favicon_remove ($id) {
return unless ($id//'') =~ /\A[a-f0-9]{12}\z/;
unlink map {"$store/site/".favicon_file($id,$_)} favicon_sizes();
}
# The <link> tags for the browser-tab icon and the phone home-screen icon:
# the uploaded favicon, or the built-in one.
sub icon_head {
my $id=setting('favicon');
if ($id =~ /\A[a-f0-9]{12}\z/) {
return '<link rel="icon" href="/media/site/'.favicon_file($id,32).'" type="image/png" sizes="32x32">'
.'<link rel="apple-touch-icon" href="/media/site/'.favicon_file($id,180).'">';
}
return '<link rel="icon" href="'.icon_url().'" type="image/svg+xml">';
}
# The largest favicon, for search engines' structured data (empty when unset).
sub favicon_large { my $id=setting('favicon');return $id =~ /\A[a-f0-9]{12}\z/ ? '/media/site/'.favicon_file($id,512) : '' }
# ---- Logo ------------------------------------------------------------------------
# Shown beside (or instead of) the site name at the top of every page. Kept as
# a PNG (transparency preserved) at up to 640 × 192, enough for sharp display
# at the largest size on high-density screens.
sub logo_sizes { return ([small=>'Small'],[medium=>'Medium'],[large=>'Large']) }
# The logo's address, if one is set.
sub logo_url { my $id=setting('logo');return $id =~ /\A[a-f0-9]{12}\z/ ? "/media/site/logo-$id.png" : '' }
# Saves a logo from an upload: shrunk to fit 640 × 192 if larger, kept as a
# PNG so transparency survives. Returns its id.
sub logo_save ($fh) {
die "Choose a PNG, JPEG or WebP picture.\n" unless $fh;
binmode $fh;seek($fh,0,0);my $bytes='';
while (read($fh,my $part,65536)) {$bytes.=$part;die "The logo must be 10 MB or smaller.\n" if length($bytes)>10*1048576}
my $image=decode_image($bytes);my ($w,$h)=$image->getBounds;
my $scale=1;$scale=640/$w if $w>640;$scale=192/$h if $h*$scale>192;
my ($nw,$nh)=(int($w*$scale+.5)||1,int($h*$scale+.5)||1);
if ($scale<1) {my $out=GD::Image->newTrueColor($nw,$nh);$out->alphaBlending(0);$out->saveAlpha(1);$out->copyResampled($image,0,0,0,0,$nw,$nh,$w,$h);$image=$out}
my $dir="$store/site";mkdir $dir,0755 unless -d $dir;
-d $dir && -w $dir or die "The media folder for site files can't be written.\n";
my $id=substr(random_id(),0,12);my $path="$dir/logo-$id.png";
open my $out,'>:raw',"$path.tmp" or die "Cannot save the logo.\n";print {$out} $image->png(9);close $out or do {unlink "$path.tmp";die "Cannot save the logo.\n"};
rename "$path.tmp",$path or die "Cannot save the logo.\n";chmod 0644,$path;
return $id;
}
# Deletes a logo file.
sub logo_remove ($id) { unlink "$store/site/logo-$id.png" if ($id//'') =~ /\A[a-f0-9]{12}\z/ }
# The site's name and/or logo at the top of every page, linking home.
# The site's name and/or logo at the top of every page, linking home. When
# only the logo shows, the name is its alt text and the link's label, so
# screen readers still say it.
sub site_brand {
my $site=setting('site_title');my $logo=logo_url();
return '<p class="site-nav__brand"><a href="/">'.h($site).'</a></p>' unless length $logo;
my $size=setting('logo_size');$size='medium' unless grep {$_->[0] eq $size} logo_sizes();
my $name=setting('show_site_name') ne '0';
return '<p class="site-nav__brand site-nav__brand--logo site-nav__brand--'.$size.'"><a href="/"'.($name ? '' : ' aria-label="'.h($site).'"').'>'
.'<img class="site-nav__logo" src="'.h($logo).'" alt="'.($name ? '' : h($site)).'">'.($name ? '<span>'.h($site).'</span>' : '').'</a></p>';
}
# ---- The settings screen (kind=settings) --------------------------------------
# Settings › Site (owners): the site's name, footer, author and description,
# saved together, and the setup walkthrough again. The pictures that stand
# for the site are under Look › Logo & icons (branding_admin, below).
sub settings_admin {
my $message=param('notice',2000);
if ($method eq 'POST') {
attempt {
my $action=param('action',30);
# (The pictures' forms used to post here; they still work from here.)
site_picture_action($action);
if ($action eq 'settings_save') {
my %v;
for my $f (settings_fields()) {
my $value=param($f->[0],$f->[2]);
$value =~ s/\r\n?/\n/g;
$v{$f->[0]}=$value;
}
die "Give the site a name.\n" unless length $v{site_title};
die "The site name can't contain line breaks.\n" if $v{site_title} =~ /\n/;
setting_save(%v);
json_response({ok=>JSON::PP::true}) if fetch_request();
redirect('/admin/?kind=settings¬ice=Settings%20saved.');
}
die "Choose an action.\n";
} or do {
$message=failed_action($@);
json_response({ok=>JSON::PP::false,message=>$message},400) if fetch_request();
};
}
admin_page('Settings',section=>'settings',notice=>$message,save=>['save','All changes saved'],
intro=>'Your site’s name, footer and description. The logo, favicon and share picture are under <a href="/admin/?kind=branding">Look</a>.');
my $failed=$BlowfishCMS::admin_failed && $method eq 'POST' && param('action',30) eq 'settings_save';
print '<form id="bulk-edit" method="post" action="/admin/">'.fields('settings_save','settings').'</form>';
my $form='<div class="admin-form">';
for my $f (settings_fields()) {
my ($key,$label,$max,$kind,$help)=@$f;
my $value=$failed ? param($key,$max) : setting($key);
$form.='<label>'.h($label);
$form.=$kind eq 'area'
? '<textarea form="bulk-edit" name="'.$key.'" maxlength="'.$max.'" rows="3">'.h($value).'</textarea>'
: '<input form="bulk-edit" name="'.$key.'" value="'.h($value).'" maxlength="'.$max.'"'.($kind eq 'email'?' type="email"':'').($key eq 'site_title'?' required':'').'>';
$form.='<span class="optional">'.h($help).'</span></label>';
}
# The setup questions again, as a link under the site's details.
window('site',$form.'</div><form method="post" action="/admin/" class="settings-setup">'.hidden(csrf=>$csrf,kind=>'setup',action=>'setup_restart')
.'<button class="text-button" type="submit">Run the setup questions again</button> <span class="optional">(name, starter pages, theme, search engines, mail and add-ons)</span></form>');
end_page();
}
# ---- Look › Logo & icons (kind=branding) ----------------------------------------
# The pictures that stand for the site: its logo, favicon and share picture,
# each uploaded or chosen from the picture library, and removable. A new
# picture is saved before the old one is deleted, so a failure never leaves
# the site without one. Each action ends by going back to this screen; it
# returns nothing when the action isn't one of these.
sub site_picture_action ($action) {
my $back='/admin/?kind=branding¬ice=';
if ($action eq 'favicon_upload') {
my $old=setting('favicon');my $id=favicon_save(upload_or_picture('favicon'));
attempt {setting_save(favicon=>$id);1} or do {my $e=$@;favicon_remove($id);die $e};
favicon_remove($old);
redirect($back.'Favicon%20saved.%20Browsers%20may%20show%20the%20old%20one%20until%20you%20reload.#favicon');
}
if ($action eq 'favicon_reset') {
my $old=setting('favicon');setting_save(favicon=>'');favicon_remove($old);
redirect($back.'Using%20the%20built-in%20favicon.#favicon');
}
if ($action eq 'logo_upload') {
my $old=setting('logo');my $id=logo_save(upload_or_picture('logo'));
attempt {setting_save(logo=>$id);1} or do {my $e=$@;logo_remove($id);die $e};
logo_remove($old);
redirect($back.'Logo%20saved.#logo');
}
if ($action eq 'logo_options') {
my $size=param('logo_size',10);die "Choose a logo size.\n" unless grep {$_->[0] eq $size} logo_sizes();
setting_save(logo_size=>$size,show_site_name=>(param('show_site_name',1) eq '1' ? '1' : '0'));
redirect($back.'Logo%20settings%20saved.#logo');
}
if ($action eq 'logo_remove') {
my $old=setting('logo');setting_save(logo=>'');logo_remove($old);
redirect($back.CGI::escape('Logo removed. The site name is shown on its own.').'#logo');
}
if ($action eq 'share_upload') {
my $old=setting('share_image');my $id=share_image_save(upload_or_picture('share_image'));
attempt {setting_save(share_image=>$id);1} or do {my $e=$@;share_image_remove($id);die $e};
share_image_remove($old);
redirect($back.'Share%20picture%20saved.#share');
}
if ($action eq 'share_reset') {
my $old=setting('share_image');setting_save(share_image=>'');share_image_remove($old);
redirect($back.'Share%20picture%20removed.#share');
}
return;
}
sub branding_admin {
my $message=param('notice',2000);
if ($method eq 'POST') {
attempt {site_picture_action(param('action',30));die "Choose an action.\n"} or $message=failed_action($@);
}
admin_page('Logo & icons',section=>'branding',notice=>$message,
intro=>'The pictures that stand for your site: its logo at the top of every page, the favicon in browser tabs, and the picture shown when a link to it is shared.');
my $logo=logo_url();
my $l='<section class="site-picture" id="logo"><h3>Logo</h3><div class="favicon-card">'.(length $logo ? '<img class="logo-card__preview" src="'.h($logo).'" alt="Current logo">' : '<p class="logo-card__empty">No logo</p>')
.'<div class="logo-card__forms"><form method="post" action="/admin/" enctype="multipart/form-data" class="admin-form">'.fields('logo_upload','branding')
.'<label>'.(length $logo ? 'Replace the logo' : 'Logo').'<input name="logo" type="file" accept="image/png,image/jpeg,image/webp" required></label>'.choose_picture_button('Choose the logo')
.'<span class="optional">Shown at the top of every page, beside the site name. A PNG with a transparent background works best on every theme. Wide logos are fine.</span>'
.'<button class="buttonlike" type="submit">save</button></form>';
if (length $logo) {
$l.='<form method="post" action="/admin/" class="admin-form">'.fields('logo_options','branding').'<div class="theme-editor__grid">'
.'<label>Size<select name="logo_size">'.join('',map {'<option value="'.$_->[0].'"'.($_->[0] eq setting('logo_size')?' selected':'').'>'.$_->[1].'</option>'} logo_sizes()).'</select></label></div>'
.switch_field('show_site_name','Show the site name next to the logo',setting('show_site_name') ne '0',hint=>'Without the name, the logo stands for it (screen readers and search engines still get the name).')
.'<button class="buttonlike" type="submit">save</button></form>'
.'<form method="post" action="/admin/" class="delete-form" data-confirm="Remove the logo?">'.fields('logo_remove','branding').'<button class="text-button danger" type="submit">remove the logo</button></form>';
}
my $id=setting('favicon');my $custom=$id =~ /\A[a-f0-9]{12}\z/;
my $icon=$custom ? '/media/site/'.favicon_file($id,180) : icon_url();
my $fav='<section class="site-picture" id="favicon"><h3>Favicon</h3><div class="favicon-card"><img class="favicon-card__preview" src="'.h($icon).'" alt="Current favicon" width="64" height="64">'
.'<form method="post" action="/admin/" enctype="multipart/form-data" class="admin-form">'.fields('favicon_upload','branding')
.'<label>New favicon<input name="favicon" type="file" accept="image/png,image/jpeg,image/webp" required></label>'.choose_picture_button('Choose the favicon')
.'<span class="optional">PNG, JPEG or WebP, ideally square and at least 512 pixels. Off-square pictures are cropped to the middle.</span>'
.'<button class="buttonlike" type="submit">save</button></form>';
$fav.='<form method="post" action="/admin/">'.fields('favicon_reset','branding').'<button class="text-button" type="submit">use the built-in favicon</button></form>' if $custom;
my $img=share_image_url();
my $sh='<section class="site-picture" id="share"><h3>Share picture</h3><div class="share-card">'.(length $img ? '<img class="share-card__preview" src="'.h($img).'" alt="Current share picture" width="300" height="158">' : '<p class="share-card__empty">No share picture</p>')
.'<form method="post" action="/admin/" enctype="multipart/form-data" class="admin-form">'.fields('share_upload','branding')
.'<label>'.(length $img ? 'Replace the share picture' : 'Share picture').'<input name="share_image" type="file" accept="image/png,image/jpeg,image/webp" required></label>'.choose_picture_button('Choose the share picture')
.'<span class="optional">Shown when a page is shared on social media or in chat apps, unless an article has its own picture. Cropped to 1200 × 630.</span>'
.'<button class="buttonlike" type="submit">save</button></form>';
$sh.='<form method="post" action="/admin/">'.fields('share_reset','branding').'<button class="text-button" type="submit">remove the share picture</button></form>' if length $img;
window('pictures','<div class="site-pictures">'.$l.'</div></div></section>'.$fav.'</div></section>'.$sh.'</div></section></div>');
end_page();
}
1;