BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
509 lines · 42.6 KB · download this file
package BlowfishCMS;
# Library: the admin screen shared by the Pictures, Music, Videos and Files
# libraries, and the actions they have in common.
#
# - Items show as a grid (photos, videos) or a list (music). Each item's
# edit panel is rendered with the page and opened at #edit-ID: by CSS
# :target without JavaScript, by admin.js (which also saves as you type).
# - Shared actions: item_save, move (one item to a position), reorder (the
# whole order, after dragging), bulk (several items: collection, tags or delete).
# - Uploads go up in pieces (upload_start, upload_chunk, upload_status,
# upload_finish, upload_cancel), so a large file needs no single long
# request and an interrupted upload resumes from the last piece. A plain
# form upload (Media.pm, action "upload") still works without JavaScript.
# 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);
# The libraries that use this shared screen (the admin's ?kind= values).
# "photography" is the picture library's internal name.
sub library_kinds { qw(photography music video file) }
# What differs between the libraries: their names (one/many), whether items
# show as a grid or a list, the file types accepted (by extension and by the
# browser's file picker), the largest file, the labels of their fields and
# the line describing the limits. `state` builds it once per worker.
sub library_spec ($kind) {
state $specs={
photography=>{title=>'Pictures',one=>'picture',many=>'pictures',layout=>'grid',exts=>[qw(jpg jpeg png webp)],refuse=>'Use JPEG, PNG or WebP images.',
accept=>'image/jpeg,image/png,image/webp',max=>30*1048576,describe=>'Description <span class="optional">caption, and what screen readers say</span>',
limits=>'JPEG, PNG or WebP, up to 30 MB and 40 megapixels each. Stored web-size: 2560 px on the long edge, metadata removed.'},
music=>{title=>'Music',one=>'track',many=>'tracks',layout=>'list',exts=>[qw(mp3 wav flac ogg m4a aac)],refuse=>'Use MP3, WAV, FLAC, Ogg, M4A or AAC audio.',
accept=>'.mp3,.wav,.flac,.ogg,.m4a,.aac',max=>250*1048576,describe=>'Notes',collection=>'Album / collection',
limits=>'MP3, WAV, FLAC, Ogg, M4A or AAC, up to 250 MB each, stored unchanged.'},
video=>{title=>'Videos',one=>'video',many=>'videos',layout=>'grid',exts=>[qw(mp4 m4v)],refuse=>'Choose an MP4 video file.',
accept=>'video/mp4,.mp4,.m4v',max=>video_max_bytes(),describe=>'Description',
limits=>'Up to '.(video_max_bytes()/1024**3).' GB each.'},
file=>{title=>'Files',one=>'file',many=>'files',layout=>'list',exts=>[],refuse=>'',accept=>'',max=>video_max_bytes(),describe=>'Description',
limits=>'Any kind of file, up to '.(video_max_bytes()/1024**3).' GB each, stored unchanged. Visitors download it; it never opens as a page of the site.'},
};
return $specs->{$kind};
}
sub library_items ($kind) { return items($kind) }
# One item of a library by its id, or undef (also for an id that isn't 32
# hex characters, so nothing odd reaches the database).
sub library_item ($kind,$id) {
return undef unless ($id//'') =~ /\A[a-f0-9]{32}\z/;
return $db->selectrow_hashref('SELECT * FROM uploads WHERE id=? AND kind=?',undef,$id,$kind);
}
# Saves a library's order: each item's sort_order becomes its position.
sub library_set_order ($kind,@ids) {
my $sth=$db->prepare('UPDATE uploads SET sort_order=? WHERE id=? AND kind=?');
$sth->execute($_,$ids[$_],$kind) for 0..$#ids;
}
# True when the request was sent by the admin's script (admin.js adds the
# X-Requested-With: fetch header), which wants a JSON answer, not a page.
sub fetch_request { return ($ENV{HTTP_X_REQUESTED_WITH}//'') eq 'fetch' }
# Answers an action: JSON for admin.js, otherwise back to the library with the
# message, reopening the item's panel when the item is still there.
# Ends a successful library action: JSON for the script, or a redirect back
# to the library (to the same picture folder) with the message, reopening the
# item's edit panel (#edit-ID) when the item still exists.
sub library_done ($kind,$message,%json) {
json_response({ok=>JSON::PP::true,message=>$message,%json}) if fetch_request();
my $id=param('id',32);
my $action=param('action',30);
# After adding a link the form stays open for the next one.
my $hash=$action !~ /delete/ && library_item($kind,$id) ? "#edit-$id" : '';
my $folder=$kind eq 'photography' ? param('folder',300) : '';
redirect('/admin/?kind='.$kind.(length $folder && folder_ok($folder) ? '&folder='.CGI::escape($folder) : '').'¬ice='.CGI::escape(encode('UTF-8',$message)).$hash);
}
# ---- Shared actions -------------------------------------------------------------
# The actions every library shares. Returns undef for ones it doesn't know,
# so media_action (Media.pm) gets them. In order:
# upload_* the uploader in pieces (upload_action, below)
# picture_upload one picture from the picture chooser (pages, articles)
# folder_create / folder_rename / folder_delete / folder_hide (pictures)
# picture_gallery keep one picture out of galleries, or show it again
# talk_switch likes and comments on or off for the whole library
# item_save an item's title, description, folder or collection,
# version (files), tags and likes/comments switch
# move / reorder one item to a new position, or the whole order after
# dragging (pictures are ordered within their folder)
# bulk several selected items at once: delete, move to a
# folder, set a collection or add tags
sub library_action ($kind) {
my $action=param('action',30);
return upload_action($kind,$action) if $action =~ /\Aupload_/;
# The picture chooser uploads one picture per request and gets it back.
if ($kind eq 'photography' && $action eq 'picture_upload') {
my $folder=param('folder',300);die "That folder no longer exists.\n" unless folder_ok($folder) && folder_exists($folder);
my $name=param('picture',300)||'Picture';
json_response({ok=>JSON::PP::true,picture=>picture_json(picture_by_id(picture_add($q->upload('picture'),$name,$folder)))});
}
if ($kind eq 'photography' && $action =~ /\Afolder_(create|rename|delete|hide)\z/) {
my $folder=param('folder',300);die "That folder no longer exists.\n" unless folder_ok($folder);
if ($1 eq 'hide') {
die "That folder no longer exists.\n" unless length $folder && folder_exists($folder);
my $on=param('hidden',1) eq '1' ? 1 : 0;
$db->do('UPDATE picture_folders SET hidden=? WHERE path=?',undef,$on,$folder);
redirect('/admin/?kind=photography&folder='.CGI::escape($folder).'¬ice='.CGI::escape(encode('UTF-8','“'.folder_name($folder).'” '.($on ? 'is kept out of galleries (its pictures can still be used on pages).' : 'shows in galleries again.'))));
}
if ($1 eq 'create') {my $path=folder_create($folder,param('name',80));redirect('/admin/?kind=photography&folder='.CGI::escape($path).'¬ice='.CGI::escape(encode('UTF-8','Folder “'.folder_name($path).'” made.')))}
if ($1 eq 'rename') {my $path=folder_rename($folder,param('name',80));redirect('/admin/?kind=photography&folder='.CGI::escape($path).'¬ice='.CGI::escape(encode('UTF-8','Folder renamed to “'.folder_name($path).'”.')))}
my ($parent,$name)=(folder_parent($folder),folder_name($folder));folder_delete($folder);
redirect('/admin/?kind=photography&folder='.CGI::escape($parent).'¬ice='.CGI::escape(encode('UTF-8',"Folder “$name” deleted.")));
}
# A picture's eye: shown in galleries or kept out of them.
if ($kind eq 'photography' && $action eq 'picture_gallery') {
my $item=library_item($kind,param('id',32)) or die "That picture no longer exists. Reload the page.\n";
my $hide=param('hidden',1) eq '1' ? 1 : 0;
$db->do('UPDATE uploads SET gallery_hidden=? WHERE id=?',undef,$hide,$item->{id});
redirect('/admin/?kind=photography&folder='.CGI::escape($item->{folder}//'').'¬ice='.CGI::escape(encode('UTF-8','“'.$item->{title}.'” '.($hide ? 'is kept out of galleries (it can still be used on pages).' : 'shows in galleries again.'))).'#edit-'.$item->{id});
}
if ($action eq 'talk_switch') {library_done($kind,talk_switch_save($kind))}
if ($action eq 'item_save') {
my $item=library_item($kind,param('id',32)) or die "That ".library_spec($kind)->{one}." no longer exists. Reload the page.\n";
my $title=param('title',300);die "Give it a title.\n" unless length $title;
if ($kind eq 'photography') {
my ($description,$folder)=(param('description',2000),param('folder',300));
die "That folder no longer exists. Reload the page.\n" unless folder_ok($folder) && folder_exists($folder);
$db->do('UPDATE uploads SET title=?,description=? WHERE id=?',undef,$title,$description,$item->{id});
item_extras_save($kind,$item->{id});
pictures_move($folder,$item);
library_done($kind,($item->{folder}//'') eq $folder ? 'Saved.' : 'Moved to “'.folder_name($folder).'”.',item=>{title=>$title,description=>$description,folder=>$folder});
}
my ($collection,$description)=(param('collection',160),param('description',2000));
$db->do('UPDATE uploads SET title=?,collection=?,description=? WHERE id=?',undef,$title,$collection,$description,$item->{id});
$db->do('UPDATE uploads SET version=? WHERE id=?',undef,param('version',40),$item->{id}) if $kind eq 'file' && defined $q->param('version');
item_extras_save($kind,$item->{id});
library_done($kind,'Saved.',item=>{title=>$title,collection=>$collection,description=>$description});
}
if ($action eq 'move' || $action eq 'reorder') {
# BEGIN IMMEDIATE takes the write lock at once, so two people reordering at
# the same time can't interleave their changes. A full new order is only
# accepted if it holds exactly the items the library has now.
$db->do('BEGIN IMMEDIATE');
attempt {
my @all=@{library_items($kind)};
# Pictures are arranged within their folder.
if ($kind eq 'photography') {
my $first=library_item($kind,$action eq 'reorder' ? ($q->multi_param('ids'))[0] : param('id',32));
my $folder=$first ? $first->{folder}//'' : '';@all=grep {($_->{folder}//'') eq $folder} @all;
}
my @ids=map {$_->{id}} @all;
if ($action eq 'reorder') {
my @new=$q->multi_param('ids');
die "The library changed while you were arranging it. Reload the page and try again.\n"
unless @new==@ids && join(',',sort @new) eq join(',',sort @ids);
@ids=@new;
} else {
my $id=param('id',32);my ($from)=grep {$ids[$_] eq $id} 0..$#ids;
die "That ".library_spec($kind)->{one}." no longer exists.\n" unless defined $from;
my $dir=param('direction',20);my $to=$dir eq 'up'?$from-1:$dir eq 'down'?$from+1:int(param('position',10)||1)-1;
$to=0 if $to<0;$to=$#ids if $to>$#ids;
splice @ids,$from,1;splice @ids,$to,0,$id;
}
library_set_order($kind,@ids);
$db->do('COMMIT');1;
} or do {my $e=$@;$db->do('ROLLBACK');die $e};
library_done($kind,'Order saved.');
}
if ($action eq 'bulk') {
my @items=map {library_item($kind,$_) // ()} $q->multi_param('ids');
die "Select at least one ".library_spec($kind)->{one}.".\n" unless @items;
my $op=param('op',20);my $n=@items;my $noun=$n==1 ? library_spec($kind)->{one} : library_spec($kind)->{many};
if ($op eq 'delete') {
# One at a time: an upload's files go with its entry.
delete_upload($_) for @items;
library_done($kind,"Deleted $n $noun.");
}
if ($op eq 'folder' && $kind eq 'photography') {
my $folder=param('folder',300);
die "Choose a folder.\n" unless folder_ok($folder) && folder_exists($folder);
pictures_move($folder,@items);
library_done($kind,"Moved $n $noun to “".folder_name($folder).'”.');
}
if ($op eq 'collection' && $kind ne 'photography') {
my $collection=param('collection',160);
$db->begin_work;
attempt {$db->do('UPDATE uploads SET collection=? WHERE id=?',undef,$collection,$_->{id}) for @items;$db->commit;1} or do {my $e=$@;$db->rollback;die $e};
library_done($kind,length $collection ? "Moved $n $noun to “$collection”." : "Took $n $noun out of their collection.");
}
if ($op eq 'tags' && item_kinds()->{$kind}) {
my @add=tags_parse(param('tags',400));die "Type the tags to add, such as #travel.\n" unless @add;
$db->begin_work;
attempt {item_tags_set($kind,$_->{id},join ' ',item_tags($kind,$_->{id}),@add) for @items;$db->commit;1} or do {my $e=$@;$db->rollback;die $e};
library_done($kind,'Tagged '.$n.' '.$noun.' '.join(' ',map {"#$_"} @add).'.');
}
die "Choose what to do with the selection.\n";
}
return undef;
}
# ---- Uploads in pieces ------------------------------------------------------------
# Large files go up in 8 MB pieces. While a file arrives it's kept in the
# admin's tmp/ folder as upload-ID.part, with upload-ID.json describing it.
sub upload_chunk_bytes { 8*1024*1024 }
sub upload_part ($id) { "$data/admin/tmp/upload-$id.part" } # the file being received
sub upload_meta ($id) { "$data/admin/tmp/upload-$id.json" } # its kind, name, size and details
# A size for messages: "1.5 GB", or whole megabytes rounded up ("12 MB").
sub size_text ($bytes) { return $bytes>=1024**3 ? sprintf('%.1f GB',$bytes/1024**3) =~ s/\.0 / /r : sprintf('%d MB',($bytes+1048575)/1048576) }
# The uploader in pieces (admin.js drives it):
# upload_start checks the file's type and size and that the server has
# room (its size plus 512 MB to spare), clears uploads
# abandoned for two days, and returns a new upload id
# upload_status how much has arrived (to resume after a dropped connection)
# upload_cancel forget an upload
# upload_chunk appends one piece; it must start exactly where the file
# ends so far, so pieces can't arrive out of order
# upload_finish once every byte is there, stores the file in its library
# (videos and files have their own steps); the pieces are
# removed whether that worked or not
# Only the page's script uses these (fetch_request).
sub upload_action ($kind,$action) {
die "Uploads need the page's own uploader; reload the page and try again.\n" unless fetch_request();
my $spec=library_spec($kind);
if ($action eq 'upload_start') {
die "The video folder isn't set up yet. Run the server setup again, then try again.\n" if $kind eq 'video' && !(-d video_dir() && -w video_dir());
my $name=param('name',300);my $size=param('size',20);
my ($ext)=lc($name) =~ /\.([a-z0-9]+)\z/;
die "$spec->{refuse}\n" if @{$spec->{exts}} && !($ext && grep {$_ eq $ext} @{$spec->{exts}});
die "The file has no name.\n" unless length basename($name);
die "The files folder isn't set up yet. Run the server setup again (blowfishctl httpd), then try again.\n" if $kind eq 'file' && !(-d file_dir() && -w file_dir());
die "This file is empty.\n" unless $size =~ /\A\d+\z/ && $size>0;
die ucfirst($spec->{many}).' must be '.size_text($spec->{max}).' or smaller; '.basename($name).' is '.size_text($size).".\n" if $size>$spec->{max};
# Abandoned uploads are removed after two days.
for my $file (glob("$data/admin/tmp/{upload,video}-*.{part,json}")) {unlink $file if -M $file > 2}
for my $dir ($kind eq 'video' ? video_dir() : $kind eq 'file' ? file_dir() : "$store/$kind","$data/admin/tmp") {
my $free=free_bytes($dir);
die 'Not enough free space on the server for '.basename($name).' ('.size_text($free).' free; it needs '.size_text($size)." plus room to spare).\n"
if defined $free && $free<$size+512*1048576;
}
my $id=random_id();
# Pictures are uploaded into a folder of the library; the others into a collection.
my $collection=$kind eq 'photography' ? param('folder',300) : param('collection',160);
die "That folder no longer exists. Reload the page.\n" if $kind eq 'photography' && !(folder_ok($collection) && folder_exists($collection));
my %meta=(kind=>$kind,name=>$name,size=>0+$size,collection=>$collection,description=>param('description',2000),started=>now());
open my $m,'>:raw',upload_meta($id) or die "The upload could not be started.\n";print {$m} encode_json(\%meta);close $m;
open my $p,'>:raw',upload_part($id) or die "The upload could not be started.\n";close $p;
json_response({ok=>JSON::PP::true,upload=>$id,chunk=>upload_chunk_bytes(),received=>0});
}
my $id=param('upload',40);
die "That upload isn't known any more. Start it again.\n" unless $id =~ /\A[a-f0-9]{32}\z/ && -f upload_meta($id);
my $meta=do {open my $fh,'<:raw',upload_meta($id) or die "That upload isn't known any more. Start it again.\n";local $/;decode_json(<$fh>)};
die "That upload belongs to another library.\n" unless ($meta->{kind}//'') eq $kind;
my $part=upload_part($id);my $forget=sub {unlink $part,upload_meta($id)};
if ($action eq 'upload_status') {json_response({ok=>JSON::PP::true,upload=>$id,chunk=>upload_chunk_bytes(),received=>(-s $part)//0,size=>$meta->{size}})}
if ($action eq 'upload_cancel') {$forget->();json_response({ok=>JSON::PP::true})}
if ($action eq 'upload_chunk') {
my $offset=param('offset',20);my $have=(-s $part)//0;
die "Pieces arrived out of order; the upload will resume from the last good piece.\n" unless $offset =~ /\A\d+\z/ && $offset==$have;
my $fh=$q->upload('chunk') or die "A piece of the upload was empty.\n";
binmode $fh;my $piece='';read($fh,$piece,upload_chunk_bytes()+1);
die "A piece of the upload was the wrong size.\n" if !length($piece) || length($piece)>upload_chunk_bytes() || $have+length($piece)>$meta->{size};
open my $out,'>>:raw',$part or die "The upload could not be saved.\n";
print {$out} $piece or die "The upload could not be saved (is the server's disk full?).\n";
close $out or die "The upload could not be saved (is the server's disk full?).\n";
json_response({ok=>JSON::PP::true,received=>-s $part});
}
if ($action eq 'upload_finish') {
die "The upload isn't complete yet.\n" unless ((-s $part)//0)==$meta->{size};
# A refused file can't be resumed, so its pieces go either way.
my ($message,%extra);
attempt {
if ($kind eq 'video') {$message=video_publish($part,$meta)}
elsif ($kind eq 'file') {$message=file_publish($part,$meta)}
else {
# Album artwork goes up with a batch's first track; the rest reuse it.
# (Several tracks uploaded together share one album artwork: the first sends
# the picture, the server answers with its stored name, and the others send
# that name, which is checked to be a stored artwork file.)
my $art=param('artwork_name',60);
$art='' unless $kind eq 'music' && $art =~ /\A[a-f0-9]{32}\.(?:webp|jpg|png)\z/ && -f "$store/artwork/$art";
$art=save_image($q->upload('artwork'),'artwork')->{filename} if $kind eq 'music' && !$art && $q->upload('artwork');
open my $fh,'<:raw',$part or die "The upload could not be read.\n";
my $new=attempt {save_upload($fh,$meta->{name},$kind,$meta->{collection},$meta->{description},$art)};
close $fh;
unless ($new) {my $e=$@;remove_art($art);die $e}
$message='“'.upload_title($meta->{name}).'” published.';
$extra{artwork}=$art if $art;
}
1;
} or do {my $e=$@;$forget->();die $e};
$forget->();
json_response({ok=>JSON::PP::true,message=>$message,%extra});
}
die "Choose an action.\n";
}
# ---- The library screen -------------------------------------------------------------
# A library's admin screen. For the picture chooser (?picker=1) it answers
# with JSON instead. Otherwise: the intro, the upload form (open when the
# library is empty), for pictures the folder trail and subfolders, the search
# and filter tools and the bulk-action bar (both shown by admin.js), one card
# per item, then one hidden edit panel per item, and the library's likes and
# comments switch.
sub library_admin ($kind,$message='') {
json_response(picker_json(param('folder',300))) if $kind eq 'photography' && param('picker',1) eq '1';
my $spec=library_spec($kind);my @list=@{library_items($kind)};
# Files show how often each was downloaded (counted by the comments service).
# (`local our` makes the download counts available to library_card and
# library_panel during this screen only.)
local our $downloads_seen=$kind eq 'file' ? download_counts() : {};
# Pictures are shown one folder at a time.
my $folder='';
if ($kind eq 'photography') {
$folder=param('folder',300);$folder='' unless folder_ok($folder) && folder_exists($folder);
@list=grep {($_->{folder}//'') eq $folder} @list;
}
my %collections;$collections{$_->{collection}}++ for grep {length($_->{collection}//'')} @list;
my @collections=sort {lc $a cmp lc $b} keys %collections;
my $intros={photography=>'Every picture on the site lives here. Folders are folders on the server too, so a backup keeps the same order. Click a picture to edit it; drag to set the order galleries show.',
music=>'Click a track to edit it; changes save as you type. Drag to set the order visitors see.',
video=>'Click a video to edit it; changes save as you type. Drag to set the order visitors see.',
file=>'Files for visitors to download: releases, documents, anything. Each has a page, and a <strong>Download</strong> block puts one or a list on any page. Click a file to edit it; drag to set the order lists show.'};
my $add='upload';
admin_page($spec->{title},section=>$kind,notice=>$message,intro=>$intros->{$kind},
actions=>library_page_action($kind).($kind eq 'photography' ? folder_actions($folder) : '<a class="buttonlike is-primary" href="#upload" data-open-upload>'.$add.'</a>'));
if ($kind eq 'video') {
print '<p class="panel-note">Videos appear on any page with a <strong>Video gallery</strong> block; add one from <a href="/admin/?kind=pages">Pages</a>.</p>';
}
print '<datalist id="collections">'.join('',map {'<option value="'.h($_).'">'} @collections).'</datalist>' if $kind ne 'photography';
print folder_bar($folder) if $kind eq 'photography';
print '<details class="lib-upload'.($kind eq 'photography' ? ' lib-upload--quiet' : '').'" id="upload"'.(@list && !($method eq 'POST' && param('action',30) eq 'upload') ? '' : ' open').'><summary>Upload '.$spec->{many}.($kind eq 'photography' ? ' to “'.h(folder_name($folder)).'”' : '').'</summary><div class="lib-upload__body">'.library_upload_form($kind).'</div></details>';
my $layout=$spec->{layout};
print '<section class="lib lib--'.$layout.'" id="library" data-kind="'.$kind.'" data-one="'.$spec->{one}.'" data-many="'.$spec->{many}.'"'.($kind eq 'photography' ? ' data-folder="'.h($folder).'"' : '').'>';
if (!@list) {print '<p class="empty-media">'.($kind eq 'photography' && length $folder ? 'No pictures in this folder yet. Upload some above, or drop files anywhere on this page.' : 'Nothing here yet. Upload '.$spec->{many}.' above, or drop files anywhere on this page.').'</p></section>';end_page();return}
print '<div class="lib-tools" hidden><input type="search" class="lib-search" placeholder="Search '.$spec->{many}.'" aria-label="Search '.$spec->{many}.'">';
print '<select class="lib-filter" aria-label="Collection"><option value="">All collections</option>'.join('',map {'<option value="'.h($_).'">'.h($_).' ('.$collections{$_}.')</option>'} @collections).'<option value=":none">Not in a collection</option></select>' if @collections;
print '<span class="lib-count" role="status">'.@list.' '.(@list==1?$spec->{one}:$spec->{many}).'</span></div>';
print '<div class="lib-bulk" hidden><strong class="lib-bulk__count"></strong>';
print '<input class="lib-bulk__collection" list="collections" maxlength="160" placeholder="Collection" aria-label="Collection for the selection"><button type="button" class="buttonlike" data-bulk="collection">set collection</button>' if $kind ne 'photography';
print '<select class="lib-bulk__folder" aria-label="Folder for the selection">'.folder_select_options($folder).'</select><button type="button" class="buttonlike" data-bulk="folder">move to folder</button>' if $kind eq 'photography';
print '<input class="lib-bulk__tags" maxlength="400" placeholder="#tags" aria-label="Tags to add to the selection" autocapitalize="none"><button type="button" class="buttonlike" data-bulk="tags">add tags</button>' if item_kinds()->{$kind};
print '<button type="button" class="buttonlike danger-button" data-bulk="delete">delete</button><button type="button" class="text-button" data-bulk="clear">clear selection</button></div>';
print '<ol class="lib-items">';
print library_card($kind,$_) for @list;
print '</ol><p class="empty-media lib-none" hidden>Nothing matches.</p>';
my $n=0;
print library_panel($kind,$_,++$n,scalar @list) for @list;
print '</section>';
print talk_switch_html($kind);
end_page();
}
# The upload form. It works as an ordinary form; admin.js takes it over to
# send files in pieces with a progress list, pause and resume. data-max and
# data-exts let the script refuse a wrong file before sending anything.
sub library_upload_form ($kind) {
my $spec=library_spec($kind);
my $html='<form method="post" action="/admin/" enctype="multipart/form-data" class="admin-form" id="upload-form" data-kind="'.$kind.'" data-max="'.$spec->{max}.'" data-exts="'.join(' ',@{$spec->{exts}}).'">'.fields('upload',$kind);
$html.='<p class="panel-note video-requirements"><strong>Export settings:</strong> MP4 file · <strong>H.264</strong> video · <strong>AAC</strong> audio. Any frame rate (24, 30, 60 fps…) and any size up to 4K; up to '.(video_max_bytes()/1024**3).' GB per video. Turn on “fast start” / “web optimised” if your editor offers it.</p>' if $kind eq 'video';
$html.='<label class="upload-picker">Choose '.$spec->{many}.' or drop them anywhere on this page<input type="file" name="media" multiple required accept="'.$spec->{accept}.'"><span>'.h($spec->{limits}).' Each file goes up in pieces: if the connection drops or you pause, choose the same files again to continue where they stopped.</span></label>';
$html.='<label>Album artwork <span class="optional">optional · for every track in this upload</span><input type="file" name="artwork" accept="image/jpeg,image/png,image/webp"></label>' if $kind eq 'music';
$html.='<label>Poster image <span class="optional">optional · shown before the video plays (first frame otherwise); for a single video</span><input type="file" name="poster" accept="image/jpeg,image/png,image/webp"></label>' if $kind eq 'video';
$html.=$kind eq 'photography'
? hidden(folder=>param('folder',300)).'<label>'.$spec->{describe}.' <span class="optional">for every file in this upload</span><textarea name="description" maxlength="2000" rows="2"></textarea></label>'
: '<div class="theme-editor__grid"><label>'.($spec->{collection}//'Collection').'<input name="collection" maxlength="160" list="collections"></label><label>'.$spec->{describe}.' <span class="optional">for every file in this upload</span><textarea name="description" maxlength="2000" rows="2"></textarea></label></div>';
$html.='<div class="upload-actions"><button class="buttonlike is-primary" type="submit">upload & publish</button><button class="text-button" type="button" id="upload-pause" hidden>pause</button><p id="upload-status" role="status"></p></div><ol class="upload-queue" id="upload-queue" hidden></ol></form>';
return $html;
}
# One entry in the grid or list. The checkbox (for bulk actions) and dragging
# are switched on by admin.js.
# One item in the library's grid or list: a tick box for bulk actions, a
# thumbnail (or a symbol), the title and a line of facts. Clicking it opens
# its edit panel (#edit-ID). data-text holds the item's words for the search
# box.
sub library_card ($kind,$item) {
my $id=$item->{id};my $title=h($item->{title});
my ($thumb,$meta,$extra)=('','','');
if ($kind eq 'photography') {
$thumb='<img src="'.h(media_url($item,1)).'" alt="" loading="lazy" decoding="async" draggable="false">';$meta=$item->{width} ? "$item->{width}×$item->{height}" : '';
$thumb.='<span class="lib-thumb__hidden" title="Kept out of galleries">'.admin_icon('eye-off').'<span class="sr-only">Kept out of galleries</span></span>' if $item->{gallery_hidden};
}
elsif ($kind eq 'video') {
$thumb=$item->{thumbnail} ? '<img src="'.h(media_url($item,1)).'" alt="" loading="lazy" draggable="false">' : '<span class="lib-thumb__blank" aria-hidden="true">▶</span>';
$thumb.='<span class="lib-thumb__badge">'.h(duration_text($item->{duration})).'</span>' if $item->{duration};
$meta=$item->{collection};
}
elsif ($kind eq 'music') {
$thumb=$item->{artwork} ? '<img src="/media/artwork/'.h($item->{artwork}).'" alt="" loading="lazy" draggable="false">' : '<span class="lib-thumb__blank" aria-hidden="true">♪</span>';
my ($ext)=$item->{filename} =~ /\.([^.]+)\z/;
$extra=join ' · ',uc($ext//''),megabytes($item->{bytes});
$meta=join ' · ',grep {length} $item->{collection},$extra;
}
elsif ($kind eq 'file') {
our $downloads_seen;my $n=($downloads_seen//{})->{$id}//0;
$thumb='<span class="lib-thumb__blank" aria-hidden="true">⇩</span>';
$extra=file_facts($item);
$meta=join ' · ',grep {length} $item->{collection},$extra,$n.' '.($n==1 ? 'download' : 'downloads');
}
my $text=lc join ' ',grep {defined} @$item{qw(title collection description)};
return '<li class="lib-item" id="item-'.$id.'" data-id="'.$id.'" data-collection="'.h($item->{collection}//'').'"'.(length $extra ? ' data-extra="'.h($extra).'"' : '').' data-text="'.h($text).'">'
.'<label class="lib-check"><input type="checkbox" value="'.$id.'" aria-label="Select '.$title.'"></label>'
.'<a class="lib-item__open" href="#edit-'.$id.'">'.($thumb ? '<span class="lib-thumb">'.$thumb.'</span>' : '')
.'<span class="lib-item__text"><span class="lib-item__title">'.$title.'</span><span class="lib-item__meta">'.h($meta).'</span></span></a></li>';
}
# The edit panel for one item.
# An item's edit panel: a preview, its facts and address, the edit form,
# artwork or poster forms for tracks and videos, the position form and
# delete. For a picture that's used somewhere, delete first asks, naming
# where it's used.
sub library_panel ($kind,$item,$n,$count) {
my $spec=library_spec($kind);my $id=$item->{id};my $title=h($item->{title});
my $eye='';
if ($kind eq 'photography') {
my $by_folder=folder_hidden($item->{folder}//'');my $off=$item->{gallery_hidden};
$eye=$by_folder && !$off ? '<span class="icon-button is-off" title="Kept out of galleries, because its folder is" role="img" aria-label="Kept out of galleries, because its folder is">'.admin_icon('eye-off').'</span>'
: do {my $tip=$off ? 'Kept out of galleries: click to show it in galleries' : 'Shown in galleries: click to keep it out of them';
'<form method="post" action="/admin/" class="icon-form">'.fields('picture_gallery','photography',$id).hidden(hidden=>$off ? 0 : 1).'<button class="icon-button'.($off ? ' is-off' : '').'" type="submit" title="'.$tip.'" aria-label="'.$tip.'">'.admin_icon($off ? 'eye-off' : 'eye').'</button></form>'};
}
my $html='<aside class="lib-panel" id="edit-'.$id.'" aria-label="Edit '.$title.'"><div class="lib-panel__head"><h2>Edit '.$spec->{one}.'</h2>'.$eye.'<a class="lib-panel__close" href="#library" aria-label="Close">×</a></div><div class="lib-panel__body">';
my $url=media_url($item);
if ($kind eq 'photography') {$html.='<img class="lib-preview" src="'.h($url).'" alt="'.h($item->{description}||$item->{title}).'" loading="lazy">'}
elsif ($kind eq 'video') {$html.='<video class="lib-preview" controls preload="none" src="'.h($url).'"'.($item->{thumbnail}?' poster="'.h(media_url($item,1)).'"':'').'></video>'}
elsif ($kind eq 'music') {
$html.='<img class="lib-preview lib-preview--art" src="/media/artwork/'.h($item->{artwork}).'" alt="Album artwork" loading="lazy">' if $item->{artwork};
$html.='<audio controls preload="none" src="'.h($url).'"></audio>';
}
my @facts=(substr($item->{created_at},0,10),
$kind eq 'photography' && $item->{width} ? "$item->{width}×$item->{height}" : (),$kind eq 'video' ? video_summary($item) : (),megabytes($item->{bytes}));
if ($kind eq 'file') {our $downloads_seen;my $n=($downloads_seen//{})->{$id}//0;push @facts,$n.' '.($n==1 ? 'download' : 'downloads');$url="/file/$id/"}
$html.='<p class="media-label">'.join(' · ',(map {h($_)} grep {length} @facts),'<a href="'.h($url).'" target="_blank" rel="noopener">open ↗</a>').'</p>';
$html.='<p class="media-label file-sha">sha256 <code>'.h($item->{sha256}).'</code></p>' if $kind eq 'file' && length($item->{sha256}//'');
$html.='<form method="post" action="/admin/" class="admin-form lib-edit">'.fields('item_save',$kind,$id);
$html.=$kind eq 'photography'
? '<label>Title<input name="title" maxlength="300" required value="'.$title.'"></label><label>Folder<select name="folder">'.folder_select_options($item->{folder}//'').'</select></label><label>'.$spec->{describe}.'<textarea name="description" maxlength="2000" rows="4">'.h($item->{description}).'</textarea></label>'
: '<label>Title<input name="title" maxlength="300" required value="'.$title.'"></label><label>'.($spec->{collection}//'Collection').'<input name="collection" maxlength="160" list="collections" value="'.h($item->{collection}).'"></label><label>'.$spec->{describe}.'<textarea name="description" maxlength="2000" rows="4">'.h($item->{description}).'</textarea></label>';
$html.='<label>Version <span class="optional">shown with the download, such as 1.2.0</span><input name="version" maxlength="40" value="'.h($item->{version}//'').'"></label>' if $kind eq 'file';
$html.=tags_input_html($kind,$id).talk_off_input_html($item);
$html.='<div class="lib-edit__foot"><button class="buttonlike lib-save" type="submit">save</button><span class="lib-edit__status" role="status"></span></div></form>';
if ($kind eq 'music' || $kind eq 'video') {
my ($field,$what,$has)=$kind eq 'music' ? ('artwork','album artwork',$item->{artwork}) : ('poster','poster image',$item->{thumbnail});
$html.='<form method="post" action="/admin/" enctype="multipart/form-data" class="admin-form lib-file">'.fields($field,$kind,$id).'<label>'.($has?'Replace':'Add').' '.$what.'<input type="file" name="'.$field.'" accept="image/jpeg,image/png,image/webp" required></label><div class="editor-actions"><button class="buttonlike" type="submit">save '.$field.'</button></div></form>';
$html.='<form method="post" action="/admin/" class="lib-file">'.fields($field,$kind,$id).hidden("remove_$field"=>1).'<button class="text-button">remove '.$what.'</button></form>' if $has;
}
$html.='<form method="post" action="/admin/" class="lib-move">'.fields('move',$kind,$id).($kind eq 'photography' ? hidden(folder=>$item->{folder}//'') : '').'<span class="media-label">Position</span><button class="buttonlike" name="direction" value="up" aria-label="Move up"'.($n==1?' disabled':'').'>↑</button><button class="buttonlike" name="direction" value="down" aria-label="Move down"'.($n==$count?' disabled':'').'>↓</button><input name="position" type="number" min="1" max="'.$count.'" value="'.$n.'" aria-label="Position"><span class="media-label">of '.$count.'</span><button class="buttonlike" name="direction" value="position">move</button></form>';
my @uses=$kind eq 'photography' ? picture_uses($item) : ();
$html.='<form method="post" action="/admin/" class="delete-form"'.(@uses ? ' data-confirm="'.h('This picture is shown on '.join(', ',@uses).'. Delete it anyway? Those places will show nothing instead.').'"' : '').'>'.fields('delete',$kind,$id).($kind eq 'photography' ? hidden(folder=>$item->{folder}//'') : '').'<button class="text-button danger">delete '.$spec->{one}.'</button></form>';
return $html.'</div></aside>';
}
1;
# ---- Picture folders ------------------------------------------------------------
# The <option>s of a folder menu: the top level, then every folder by its
# full name ("Travel › Japan"), the current one selected.
sub folder_select_options ($current) {
return join '',map {'<option value="'.h($_->[0]).'"'.($_->[0] eq $current ? ' selected' : '').'>'.h($_->[1]).'</option>'} ['','Pictures (top level)'],folder_options();
}
# Small line icons for the admin (drawn inline, coloured by the text).
# Small line icons for the admin as inline SVG drawings. They use
# currentColor, so they take the colour of the text around them.
sub admin_icon ($name) {
my %d=(eye=>'<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>',
'eye-off'=>'<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/><path d="M3 3l18 18"/>',
'folder-plus'=>'<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M12 10.5v6M9 13.5h6"/>',
'image-plus'=>'<path d="M14 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M19 15l-4-4-9 9"/><path d="M19 2v6M16 5h6"/>',
more=>'<circle cx="5" cy="12" r="1.2"/><circle cx="12" cy="12" r="1.2"/><circle cx="19" cy="12" r="1.2"/>');
return '<svg class="icon" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">'.$d{$name}.'</svg>';
}
# The Pictures screen's top-right buttons: whether this folder shows in
# galleries, a new folder, new pictures, and the folder's other options.
sub folder_actions ($folder) {
my $html='';
if (length $folder) {
my $own=$db->selectrow_array('SELECT hidden FROM picture_folders WHERE path=?',undef,$folder);
if (!$own && folder_hidden($folder)) {
$html.='<span class="icon-button is-off" title="Kept out of galleries, because a folder above it is" role="img" aria-label="Kept out of galleries, because a folder above it is">'.admin_icon('eye-off').'</span>';
} else {
my $tip=$own ? 'Kept out of galleries: click to show this folder in galleries' : 'Shown in galleries: click to keep this folder out of them';
$html.='<form method="post" action="/admin/" class="icon-form">'.fields('folder_hide','photography').hidden(folder=>$folder,hidden=>$own ? 0 : 1)
.'<button class="icon-button'.($own ? ' is-off' : '').'" type="submit" title="'.$tip.'" aria-label="'.$tip.'">'.admin_icon($own ? 'eye-off' : 'eye').'</button></form>';
}
}
$html.='<details class="icon-menu"><summary class="buttonlike with-icon" title="New folder in “'.h(folder_name($folder)).'”">'.admin_icon('folder-plus').'new folder</summary><div class="icon-menu__panel">'
.'<form method="post" action="/admin/" class="folder-form">'.fields('folder_create','photography').hidden(folder=>$folder).'<label>New folder in “'.h(folder_name($folder)).'”<input name="name" maxlength="80" required placeholder="Folder name"></label><button class="buttonlike is-primary" type="submit">add folder</button></form></div></details>';
$html.='<label class="buttonlike is-primary with-icon" title="Upload pictures to “'.h(folder_name($folder)).'”"><input type="file" multiple accept="'.library_spec('photography')->{accept}.'" data-upload-input hidden>'.admin_icon('image-plus').'upload pictures</label>';
if (length $folder) {
$html.='<details class="icon-menu"><summary class="icon-button" title="Rename or delete this folder" aria-label="Folder options">'.admin_icon('more').'</summary><div class="icon-menu__panel">'
.'<form method="post" action="/admin/" class="folder-form">'.fields('folder_rename','photography').hidden(folder=>$folder).'<label>Rename this folder<input name="name" maxlength="80" required value="'.h(folder_name($folder)).'"></label><button class="buttonlike" type="submit">rename</button></form>'
.'<form method="post" action="/admin/" class="folder-form delete-form" data-confirm="'.h('Delete the folder “'.folder_name($folder).'”? It has to be empty.').'">'.fields('folder_delete','photography').hidden(folder=>$folder).'<button class="buttonlike danger" type="submit">delete this folder</button></form></div></details>';
}
return $html;
}
# Above the Pictures screen: the folder trail (breadcrumbs back up to the top)
# and a tile for each folder inside this one, with its picture count
# (including its subfolders' pictures).
sub folder_bar ($folder) {
my @trail=folder_trail($folder);my $counts=folder_counts();
my $html='<nav class="folder-trail" aria-label="Folder">'.join('<span aria-hidden="true">›</span>',map {
$_->[0] eq $folder ? '<strong aria-current="page">'.h($_->[1]).'</strong>' : '<a href="/admin/?kind=photography&folder='.h(CGI::escape($_->[0])).'">'.h($_->[1]).'</a>'} @trail).'</nav>';
my @children=folder_children($folder);
if (@children) {
$html.='<ul class="folder-grid">'.join('',map {
my $n=0;my $p=$_->{path};$n+=$counts->{$_}//0 for grep {$_ eq $p || index($_,"$p/")==0} keys %$counts;
'<li><a class="folder-tile" href="/admin/?kind=photography&folder='.h(CGI::escape($p)).'"><span class="folder-tile__icon" aria-hidden="true"></span><span class="folder-tile__name">'.h($_->{name}).'</span><span class="folder-tile__count">'.($n==1 ? '1 picture' : "$n pictures").'</span></a></li>'} @children).'</ul>';
}
return $html;
}