BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
315 lines · 17.7 KB · download this file
package BlowfishCMS;
# The picture library: every picture the site shows (galleries, pages,
# articles) is one entry here, in a folder. Folders are real directories under
# the media folder's pictures/, so a backup is organised the same way:
#
# media/pictures/<folder>/<id>.webp the picture (up to 2560 px)
# media/pictures/<folder>/<id>-thumb.webp its thumbnail (800 px)
#
# A folder's path is made of address-safe segments ("travel/japan"); its name
# ("Japan") is kept in picture_folders. Pages and galleries refer to pictures
# by id, so moving a picture or renaming a folder never breaks them; article
# text holds the picture's address, which moves rewrite.
#
# In the catalogue pictures are uploads of kind 'photography', the name the
# first releases used.
use v5.36;
use utf8;
use File::Path qw(make_path);
use JSON::PP qw(encode_json decode_json);
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);
# The folder holding the picture library: media/pictures.
sub pictures_root { "$store/pictures" }
# Whether a folder path is one we allow: '' (the top level), or up to five
# levels of lowercase letters, digits and dashes ("travel/japan").
sub folder_ok ($path) { return defined $path && ($path eq '' || $path =~ m{\A[a-z0-9][a-z0-9-]{0,59}(?:/[a-z0-9][a-z0-9-]{0,59}){0,4}\z}) }
# The real folder on disk for a library folder path; dies on a bad path, so
# a path from a form can never point outside the library.
sub picture_dir ($folder) {
die "That folder name can't be used.\n" unless folder_ok($folder);
return pictures_root().(length $folder ? "/$folder" : '');
}
# A picture's public address: /media/pictures/FOLDER/FILE (or its thumbnail).
sub picture_url ($item, $thumb=0) {
my $file=$thumb && $item->{thumbnail} ? $item->{thumbnail} : $item->{filename};
return '/media/pictures/'.(length($item->{folder}//'') ? "$item->{folder}/" : '').$file;
}
# A picture's file on disk (or its thumbnail's), or undef if it has none.
sub picture_file ($item, $thumb=0) {
my $file=$thumb ? $item->{thumbnail} : $item->{filename};
return length($file//'') ? picture_dir($item->{folder}//'')."/$file" : undef;
}
# An address-safe folder segment from a name: "Trips 2024!" → "trips-2024".
# Folder names become address-safe path parts: accents removed (é -> e),
# lowercase, anything else between letters and digits becomes a dash.
sub folder_slug ($name) {
my $s=lc($name//'');
require Unicode::Normalize;$s=Unicode::Normalize::NFKD($s);$s =~ s/\p{Mn}//g;
$s =~ s/[^a-z0-9]+/-/g;$s =~ s/\A-+|-+\z//g;
return substr($s,0,60) =~ s/-+\z//r || 'folder';
}
# The folder a folder is in: "travel/japan" -> "travel".
sub folder_parent ($path) { return $path =~ m{\A(.*)/[^/]+\z} ? $1 : '' }
# Every folder (path and name), in path order.
sub picture_folders { return $db->selectall_arrayref('SELECT path,name FROM picture_folders ORDER BY path',{Slice=>{}}) }
# A folder's name as shown ("Japan"); the top level is "Pictures".
sub folder_name ($path) {
return 'Pictures' unless length $path;
return scalar($db->selectrow_array('SELECT name FROM picture_folders WHERE path=?',undef,$path)) // $path;
}
# "Pictures › Travel › Japan": each step with its path, for breadcrumbs.
sub folder_trail ($path) {
my @trail=(['',folder_name('')]);my $at='';
for my $part (grep {length} split m{/},$path) {$at=length $at ? "$at/$part" : $part;push @trail,[$at,folder_name($at)]}
return @trail;
}
# The folders directly inside a folder (not deeper).
sub folder_children ($path) {
my $prefix=length $path ? "$path/" : '';
return grep {substr($_->{path},0,length $prefix) eq $prefix && index(substr($_->{path},length $prefix),'/')<0} @{picture_folders()};
}
# Whether a folder exists in the catalogue ('' always does).
sub folder_exists ($path) { return $path eq '' || $db->selectrow_array('SELECT count(*) FROM picture_folders WHERE path=?',undef,$path) }
# Every folder as "Travel › Japan", for menus.
sub folder_options {
my %name=map {($_->{path}=>$_->{name})} @{picture_folders()};
return map {my $p=$_;my $at='';[$p,join(' › ',map {$at=length $at ? "$at/$_" : $_;$name{$at}//$_} split m{/},$p)]} sort keys %name;
}
# How many pictures each folder holds directly, {path => count}.
sub folder_counts {
my %n;$n{$_->[0]}=$_->[1] for @{$db->selectall_arrayref("SELECT folder,count(*) FROM uploads WHERE kind='photography' GROUP BY folder")};
return \%n;
}
# Makes a folder's directory on disk (and any missing parents), readable by
# httpd (0755).
sub folder_make_dir ($path) {
my $dir=picture_dir($path);
make_path($dir,{mode=>0755,error=>\my $err});
die "The folder could not be made on the server.\n" unless -d $dir;
chmod 0755,$dir;
}
# Makes a new folder inside $parent: its path comes from its name, it must
# be new, and at most five levels deep.
sub folder_create ($parent,$name) {
$name =~ s/\s+/ /g;$name =~ s/\A\s|\s\z//g;
die "Give the folder a name.\n" unless length $name;
die "Folder names can be up to 80 characters.\n" if length $name>80;
die "That folder no longer exists.\n" unless folder_exists($parent);
my $path=(length $parent ? "$parent/" : '').folder_slug($name);
die "Folders can be nested up to five deep.\n" unless folder_ok($path);
die "There's already a folder called “$name” here.\n" if folder_exists($path);
folder_make_dir($path);
$db->do('INSERT INTO picture_folders (path,name,created_at) VALUES (?,?,?)',undef,$path,$name,now());
return $path;
}
# Renaming changes the folder's directory too, so the backup matches what the
# admin shows; pictures, subfolders, article addresses and galleries follow.
# Renames a folder. Its path follows the new name, so its directory is
# renamed on disk and everything that refers to it is updated in one
# transaction: subfolders, pictures, picture addresses in articles, and
# galleries that show it. If the database part fails, the directory is
# renamed back.
sub folder_rename ($path,$name) {
$name =~ s/\s+/ /g;$name =~ s/\A\s|\s\z//g;
die "Give the folder a name.\n" unless length $name;
die "Folder names can be up to 80 characters.\n" if length $name>80;
die "That folder no longer exists.\n" unless length $path && folder_exists($path);
my $parent=folder_parent($path);my $new=(length $parent ? "$parent/" : '').folder_slug($name);
if ($new eq $path) {$db->do('UPDATE picture_folders SET name=? WHERE path=?',undef,$name,$path);return $path}
die "There's already a folder called “$name” here.\n" if folder_exists($new);
my ($from,$to)=(picture_dir($path),picture_dir($new));
die "The folder could not be renamed on the server.\n" if -e $to;
if (-d $from) {rename $from,$to or die "The folder could not be renamed on the server.\n"} else {folder_make_dir($new)}
my $ok=attempt {
$db->begin_work;
for my $f (@{$db->selectall_arrayref('SELECT path FROM picture_folders WHERE path=? OR path LIKE ?',undef,$path,"$path/%")}) {
my $moved=$new.substr($f->[0],length $path);
$db->do('UPDATE picture_folders SET path=? WHERE path=?',undef,$moved,$f->[0]);
}
$db->do('UPDATE picture_folders SET name=? WHERE path=?',undef,$name,$new);
$db->do("UPDATE uploads SET folder=?||substr(folder,?) WHERE kind='photography' AND (folder=? OR folder LIKE ?)",undef,$new,length($path)+1,$path,"$path/%");
rewrite_post_addresses("/media/pictures/$path/","/media/pictures/$new/");
gallery_folders_moved($path,$new);
$db->commit;1;
};
unless ($ok) {my $e=$@;attempt {$db->rollback};rename $to,$from;die $e}
return $new;
}
# Deletes a folder and its subfolders, but only when no picture is in them
# and no gallery shows them.
sub folder_delete ($path) {
die "That folder no longer exists.\n" unless length $path && folder_exists($path);
my $n=$db->selectrow_array("SELECT count(*) FROM uploads WHERE kind='photography' AND (folder=? OR folder LIKE ?)",undef,$path,"$path/%");
die "Move or delete the ".($n==1?'picture':"$n pictures")." in “".folder_name($path)."” first.\n" if $n;
my @used=gallery_pages_using_folder($path);
die "A gallery on ".join(', ',@used)." shows this folder. Choose another folder there first.\n" if @used;
for my $f (reverse @{$db->selectall_arrayref('SELECT path FROM picture_folders WHERE path=? OR path LIKE ? ORDER BY path',undef,$path,"$path/%")}) {
my $dir=picture_dir($f->[0]);
# Any picture files left in it are cleared too.
if (opendir my $dh,$dir) {for my $file (readdir $dh) {unlink "$dir/$file" if $file =~ /\A[a-f0-9]{32}(?:-thumb)?\.(?:webp|jpg|png)\z/} closedir $dh}
rmdir $dir;
$db->do('DELETE FROM picture_folders WHERE path=?',undef,$f->[0]);
}
}
# Replaces one picture address (or folder prefix) with another in every
# article that contains it, so articles keep showing pictures that moved.
sub rewrite_post_addresses ($old,$new) {
for my $post (@{$db->selectall_arrayref('SELECT id,body FROM posts WHERE instr(body,?)>0',{Slice=>{}},$old)}) {
(my $body=$post->{body}) =~ s{\Q$old\E}{$new}g;
$db->do('UPDATE posts SET body=? WHERE id=?',undef,$body,$post->{id});
}
}
# Galleries that show a folder follow it when it's renamed.
# Galleries that show a renamed folder (or one inside it) are updated to
# the new path.
sub gallery_folders_moved ($old,$new) {
for my $b (@{$db->selectall_arrayref("SELECT id,data FROM page_blocks WHERE type='gallery'",{Slice=>{}})}) {
my $d=attempt {JSON::PP->new->decode($b->{data})} or next;
my $f=$d->{folder}//'';
next unless length $f && ($f eq $old || index($f,"$old/")==0);
$d->{folder}=$new.substr($f,length $old);
$db->do('UPDATE page_blocks SET data=? WHERE id=?',undef,JSON::PP->new->canonical->encode($d),$b->{id});
}
}
# The titles of the pages whose galleries show a folder or one inside it.
sub gallery_pages_using_folder ($path) {
my %pages;
for my $b (@{$db->selectall_arrayref("SELECT page,data FROM page_blocks WHERE type='gallery'",{Slice=>{}})}) {
my $d=attempt {JSON::PP->new->decode($b->{data})} or next;
my $f=$d->{folder}//'';
$pages{$b->{page}}=1 if ($d->{source}//'folder') eq 'folder' && length $f && ($f eq $path || index($f,"$path/")==0);
}
my $reg=page_registry();
return map {$reg->{$_} ? $reg->{$_}{title} : $_} sort keys %pages;
}
# Moves pictures to another folder: their files, then the catalogue, then any
# article that shows them.
# Moves pictures into another folder: their files on disk first (put back if
# one fails), then the catalogue, then the addresses in articles. Returns
# how many moved.
sub pictures_move ($folder,@items) {
die "That folder no longer exists.\n" unless folder_exists($folder);
folder_make_dir($folder);
my $n=0;
for my $item (@items) {
next if ($item->{folder}//'') eq $folder;
my @files=grep {length} @$item{qw(filename thumbnail)};
my $to=picture_dir($folder);my @done;
for my $file (@files) {
my $from=picture_dir($item->{folder}//'')."/$file";
next unless -e $from;
unless (rename $from,"$to/$file") {rename "$to/$_",picture_dir($item->{folder}//'')."/$_" for @done;die "“$item->{title}” could not be moved on the server.\n"}
push @done,$file;
}
$db->do('UPDATE uploads SET folder=? WHERE id=?',undef,$folder,$item->{id});
rewrite_post_addresses(picture_url($item,$_),picture_url({%$item,folder=>$folder},$_)) for 0,1;
$n++;
}
return $n;
}
# Stores an uploaded picture in a folder of the library and returns its id.
# Stores an uploaded picture in a library folder (resized and re-encoded by
# save_image), adds it at the top of the library, and returns its id. If the
# catalogue entry can't be added, the stored files are removed.
sub picture_add ($fh,$original,$folder,$description='',$title='') {
die "That folder no longer exists.\n" unless folder_exists($folder);
folder_make_dir($folder);
my $item=save_image($fh,length $folder ? "pictures/$folder" : 'pictures');
my $id=random_id();
attempt {
$db->do("INSERT INTO uploads (id,kind,title,description,collection,folder,filename,thumbnail,mime,bytes,width,height,created_at,sort_order) VALUES (?,'photography',?,?,'',?,?,?,?,?,?,?,?,(SELECT COALESCE(MIN(sort_order),0)-1 FROM uploads WHERE kind='photography'))",
undef,$id,length $title ? substr($title,0,300) : upload_title($original),$description,$folder,@$item{qw(filename thumbnail mime bytes width height)},now());
1;
} or do {my $e=$@;unlink picture_dir($folder)."/$_" for grep {length} @$item{qw(filename thumbnail)};die $e};
return $id;
}
# One picture by its id, or undef.
sub picture_by_id ($id) {
return undef unless defined $id && $id =~ /\A[a-f0-9]{32}\z/;
return $db->selectrow_hashref("SELECT * FROM uploads WHERE id=? AND kind='photography'",undef,$id);
}
# Where a picture is shown: page titles and article titles, for the warning
# before it's deleted.
sub picture_uses ($item) {
my @uses;
my $url=picture_url($item);
push @uses,map {"the article “$_->[0]”"} @{$db->selectall_arrayref('SELECT title FROM posts WHERE instr(body,?)>0',undef,$url)};
my %pages;
for my $b (@{$db->selectall_arrayref('SELECT page,data FROM page_blocks WHERE instr(data,?)>0',{Slice=>{}},$item->{id})}) {$pages{$b->{page}}=1}
my $reg=page_registry();
push @uses,map {'the '.($reg->{$_} ? $reg->{$_}{title} : $_).' page'} sort keys %pages;
my %s=map {($_->[0]=>$_->[1])} @{$db->selectall_arrayref('SELECT key,value FROM site_settings')};
push @uses,"the site's $_->[1]" for grep {($s{$_->[0]}//'') eq $item->{id}} [logo_picture=>'logo'],[share_picture=>'share picture'];
return @uses;
}
# The "Articles" folder, where pictures dropped into an article go; made when first needed.
# The "Articles" folder, made the first time an article needs it.
sub articles_folder {
unless (folder_exists('articles')) {
folder_make_dir('articles');
$db->do("INSERT OR IGNORE INTO picture_folders (path,name,created_at) VALUES ('articles','Articles',?)",undef,now());
}
return 'articles';
}
# What the picture chooser (admin.js) needs about one picture.
sub picture_json ($item) {
return {id=>$item->{id},title=>$item->{title},description=>$item->{description}//'',folder=>$item->{folder}//'',
url=>picture_url($item),thumb=>picture_url($item,1),width=>0+($item->{width}//0),height=>0+($item->{height}//0)};
}
# The chooser's view of one folder: where it is, its subfolders and pictures.
# What the picture chooser (admin.js) shows for one folder: the trail of
# folders above it, the folders inside it with their picture counts, and its
# pictures.
sub picker_json ($folder) {
$folder='' unless folder_ok($folder) && folder_exists($folder);
my $counts=folder_counts();
return {ok=>JSON::PP::true,folder=>$folder,
trail=>[map {{path=>$_->[0],name=>$_->[1]}} folder_trail($folder)],
folders=>[map {my $p=$_->{path};my $n=0;$n+=$counts->{$_} for grep {$_ eq $p || index($_,"$p/")==0} keys %$counts;{path=>$p,name=>$_->{name},count=>$n}} folder_children($folder)],
pictures=>[map {picture_json($_)} grep {($_->{folder}//'') eq $folder} @{items('photography')}]};
}
# ---- The library's tables ---------------------------------------------------
# Creates the picture_folders table and the library's directory; a new site
# also gets the Site folder (pictures_version is only unset on a new site).
sub ensure_picture_tables {
$db->do("CREATE TABLE IF NOT EXISTS picture_folders (path TEXT PRIMARY KEY, name TEXT NOT NULL, created_at TEXT NOT NULL, hidden INTEGER NOT NULL DEFAULT 0)");
folder_make_dir('') if defined $store;
# A new site: the Site folder, kept out of galleries.
site_pictures_folder() unless $db->selectrow_array("SELECT value FROM site_settings WHERE key='pictures_version'");
}
# The Site folder, kept out of galleries, for the logo, favicon, a portrait
# and other pictures that aren't for show.
sub site_pictures_folder {
unless (folder_exists('site')) {folder_make_dir('site') if defined $store;$db->do("INSERT OR IGNORE INTO picture_folders (path,name,created_at) VALUES ('site','Site',?)",undef,now())}
$db->do("UPDATE picture_folders SET hidden=1 WHERE path='site'");
$db->do("INSERT OR REPLACE INTO site_settings (key,value) VALUES ('pictures_version','4')");
}
# Folders kept out of galleries (their subfolders with them).
# The folders kept out of galleries.
sub hidden_folders { return @{(attempt {$db->selectcol_arrayref('SELECT path FROM picture_folders WHERE hidden=1')}) // []} }
# Whether a folder is kept out of galleries, by itself or by a folder above it.
sub folder_hidden ($path) { return scalar grep {$path eq $_ || index($path,"$_/")==0} hidden_folders() }
# A form's picture: the file uploaded in FIELD or, when none was, the library
# picture chosen with "choose from Pictures" (its id in the `picture` field).
# Either way the caller gets a file handle and makes its own copy, so deleting
# the picture from the library later doesn't break what was made from it.
sub upload_or_picture ($field) {
my $fh=$q->upload($field);return $fh if $fh;
my $id=param('picture',32);return undef unless length $id;
my $item=picture_by_id($id) or die "That picture is no longer in the library.\n";
my $path=picture_file($item) or die "That picture is no longer in the library.\n";
open my $in,'<:raw',$path or die "That picture's file is missing.\n";
return $in;
}
# The button next to a file field that fills `picture` from the library and sends the form.
sub choose_picture_button ($title='Choose a picture') {
return '<button class="text-button" type="button" data-choose-into hidden data-title="'.h($title).'">or choose from Pictures</button><input type="hidden" name="picture" value="">';
}
1;