repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

300 lines · 19.8 KB · download this file

package BlowfishCMS;
# Media: the image pipeline (reading, resizing and re-encoding pictures),
# storing and deleting uploads, music lists and the picture viewer.
# 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);

# Reads a JPEG's width and height from its bytes without decoding the
# picture. A JPEG is a series of segments, each starting with the byte 0xFF
# and a marker byte; the "start of frame" segments (markers C0-CF, except
# C4, C8 and CC, which are other things) hold the size. Used to refuse
# oversized pictures before GD spends memory on them.
sub jpeg_dimensions ($bytes) {
    my $offset=2;
    while ($offset+4 < length($bytes)) {
        $offset++ while $offset<length($bytes) && substr($bytes,$offset,1) ne "\xff";
        $offset++ while $offset<length($bytes) && substr($bytes,$offset,1) eq "\xff";
        my $marker=ord(substr($bytes,$offset++,1));
        next if $marker==0 || $marker==0xd8;
        last if $marker==0xd9 || $marker==0xda;
        my $len=unpack('n',substr($bytes,$offset,2)); last if $len<2;
        if ($marker>=0xc0 && $marker<=0xcf && !grep {$_==$marker} (0xc4,0xc8,0xcc)) {
            my ($height,$width)=unpack('nn',substr($bytes,$offset+3,4)); return ($width,$height);
        }
        $offset += $len;
    }
    die "Invalid JPEG image.\n";
}
# A phone photo is often stored sideways with an EXIF note saying how to turn
# it. This finds that note (tag 0x112, "Orientation") in the EXIF data, in
# either byte order (II = little-endian, MM = big-endian). Returns 1-8
# (1 = upright). It's the only metadata used; everything else (location,
# camera) is thrown away when the picture is re-encoded.
sub orientation ($bytes) {
    # EXIF TIFF orientation is the only metadata retained, as a pixel transform.
    my $pos=index($bytes,"Exif\0\0"); return 1 if $pos<0;
    my $t=substr($bytes,$pos+6); return 1 if length($t)<8;
    my $le=substr($t,0,2) eq 'II'; return 1 unless $le || substr($t,0,2) eq 'MM';
    my $short=sub($o){return 0 if $o+2>length($t);unpack($le?'v':'n',substr($t,$o,2))};
    my $long=sub($o){return 0 if $o+4>length($t);unpack($le?'V':'N',substr($t,$o,4))};
    my $off=$long->(4); my $count=$short->($off); return 1 if $count>1024;
    for my $i (0..$count-1) {my $o=$off+2+$i*12; return $short->($o+8) if $short->($o)==0x112 && $short->($o+2)==3 && $long->($o+4)==1}
    return 1;
}
# GD can't read WebP here, so the bytes are written to a temporary file,
# converted to PNG with libwebp's dwebp program, and the PNG is read. The
# temporary files are in the admin's own folder and deleted afterwards.
sub decode_webp ($bytes) {
    my @dir=-w "$data/admin/tmp" ? (DIR=>"$data/admin/tmp") : ();
    my ($in,$path)=tempfile(@dir,UNLINK=>1);binmode $in;print {$in} $bytes;close $in;
    my ($out,$dest)=tempfile(@dir,UNLINK=>1);close $out;
    my $dwebp=(grep {-x} '/usr/local/bin/dwebp','/usr/bin/dwebp')[0] or die "Cannot decode WebP.\n";
    system($dwebp,'-quiet',$path,'-o',$dest)==0 or die "Cannot decode WebP.\n";
    return GD::Image->newFromPng($dest,1);
}
# Web-size storage: nothing larger than this is kept on the server, and every
# image is re-encoded as WebP (JPEG if the libwebp encoder is missing).
# The largest width or height kept for each media folder: 2560 px for
# pictures, 1600 for album artwork, 1920 for video posters.
sub max_edge ($folder) { return 2560 if $folder =~ m{\Apictures(?:/|\z)}; return {photography=>2560,blog=>2560,artwork=>1600,video=>1920}->{$folder} // 2560 }
# Where libwebp's encoder (cwebp) is installed, or '' if it isn't.
sub cwebp_path { state $path=(grep {-x} '/usr/local/bin/cwebp','/usr/bin/cwebp')[0] // ''; return $path }
# Shrinks a picture so neither side is larger than $max, keeping its shape
# (copyResampled gives a smooth result) and any transparency. Pictures that
# already fit are returned as they are.
sub fit_image ($image, $max) {
    need_gd();
    my ($w,$h)=$image->getBounds;
    return $image if $w<=$max && $h<=$max;
    my $ratio=$max/($w>$h?$w:$h);my ($nw,$nh)=(int($w*$ratio+.5)||1,int($h*$ratio+.5)||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);
    return $out;
}
# Encodes a picture for the web: WebP with cwebp (quality $quality, no
# metadata), or JPEG if cwebp isn't installed, painted onto white first
# because JPEG has no transparency. Returns (bytes, extension).
sub encode_web ($image, $quality) {
    need_gd();
    if (my $cwebp=cwebp_path()) {
        my $tmp=-d "$data/admin/tmp" ? "$data/admin/tmp" : undef;
        $tmp=undef unless $tmp && -w $tmp;
        my ($in,$src)=tempfile(($tmp?(DIR=>$tmp):()),SUFFIX=>'.png',UNLINK=>1);binmode $in;print {$in} $image->png(1);close $in;
        my ($out,$dst)=tempfile(($tmp?(DIR=>$tmp):()),SUFFIX=>'.webp',UNLINK=>1);close $out;
        system($cwebp,'-quiet','-q',$quality,'-m','5','-metadata','none',$src,'-o',$dst)==0 or die "Cannot encode image.\n";
        open my $fh,'<:raw',$dst or die "Cannot encode image.\n";local $/;my $bytes=<$fh>;close $fh;unlink $src,$dst;
        die "Cannot encode image.\n" unless length $bytes;
        return ($bytes,'webp');
    }
    my ($w,$h)=$image->getBounds;my $flat=GD::Image->newTrueColor($w,$h);
    $flat->filledRectangle(0,0,$w,$h,$flat->colorAllocate(255,255,255));$flat->alphaBlending(1);
    $flat->copy($image,0,0,0,0,$w,$h);
    return ($flat->jpeg($quality+3),'jpg');
}
# Reads an uploaded picture (up to 30 MB) and stores it in a media folder,
# resized and re-encoded. Returns what store_web_image returns.
sub save_image ($fh, $folder) {
    die "Choose a JPEG, PNG or WebP image.\n" unless $fh;
    binmode $fh; seek($fh,0,0); my $bytes='';
    while (read($fh,my $part,65536)) { $bytes.=$part; die "Images must be 30 MB or smaller.\n" if length($bytes)>30*1048576 }
    return store_web_image(decode_image($bytes),$folder);
}
# Decode JPEG/PNG/WebP bytes into a GD image, applying JPEG orientation.
# Turns picture bytes into a GD image. It recognises the format from its
# first bytes (its "magic number"), reads the size from the header and
# refuses anything larger than 16000 px a side or 40 megapixels before
# decoding, so a small file claiming to be huge can't exhaust memory. JPEGs
# are turned upright according to their orientation note.
sub decode_image ($bytes) {
    need_gd();
    my ($w,$height,$image,$type);
    if (substr($bytes,0,8) eq "\x89PNG\r\n\x1a\n") { ($w,$height)=unpack('NN',substr($bytes,16,8));$type='png' }
    elsif (substr($bytes,0,2) eq "\xff\xd8") { ($w,$height)=jpeg_dimensions($bytes);$type='jpg' }
    elsif (substr($bytes,0,4) eq 'RIFF' && substr($bytes,8,4) eq 'WEBP') {
        $type='webp'; my $chunk=substr($bytes,12,4);
        if ($chunk eq 'VP8X') { $w=1+unpack('V',substr($bytes,24,3)."\0"); $height=1+unpack('V',substr($bytes,27,3)."\0") }
        elsif ($chunk eq 'VP8L' && substr($bytes,20,1) eq "\x2f") {my $v=unpack('V',substr($bytes,21,4));$w=1+($v&0x3fff);$height=1+(($v>>14)&0x3fff)}
        elsif ($chunk eq 'VP8 ' && substr($bytes,23,3) eq "\x9d\x01\x2a") {($w,$height)=unpack('vv',substr($bytes,26,4));$w &= 0x3fff;$height &= 0x3fff}
    }
    die "Use JPEG, PNG or WebP, up to 40 megapixels.\n" unless $w && $height && $w<=16000 && $height<=16000 && $w*$height<=40000000;
    $image = $type eq 'jpg' ? GD::Image->newFromJpegData($bytes,1) : $type eq 'png' ? GD::Image->newFromPngData($bytes,1) : decode_webp($bytes);
    die "This image cannot be decoded.\n" unless $image;
    if ($type eq 'jpg') {
        my $o=orientation($bytes);
        $image->flipHorizontal if $o==2 || $o==4 || $o==5 || $o==7;
        $image=$image->copyRotate180 if $o==3 || $o==4;
        $image=$image->copyRotate90 if $o==5 || $o==6;
        $image=$image->copyRotate270 if $o==7 || $o==8;
    }
    $image->saveAlpha(1);
    return $image;
}
# Resize and encode a decoded image into $store/$folder; returns its record.
# Saves a decoded picture into $store/$folder: resized to the folder's
# maximum and encoded (quality 82), plus an 800 px thumbnail (quality 75) for
# the picture library. The file name is a new random id. If writing any file
# fails, the ones already written are removed. Returns the details to store
# in the catalogue (file names, size in pixels and bytes, type).
sub store_web_image ($image, $folder) {
    $image=fit_image($image,max_edge($folder));my ($w,$height)=$image->getBounds;
    my $id=random_id();my ($main,$type)=encode_web($image,82);my $name="$id.$type";my $thumb='';
    my @outputs=([$name,$main]);
    if ($folder eq 'photography' || $folder =~ m{\Apictures(?:/|\z)}) {my ($small,$ext)=encode_web(fit_image($image,800),75);$thumb="$id-thumb.$ext";push @outputs,[$thumb,$small]}
    my @made;
    attempt {
        for my $entry (@outputs) {
            my $path="$store/$folder/$entry->[0]"; push @made,$path;
            open my $out,'>:raw',$path or die "Cannot store image.\n"; print {$out} $entry->[1] or die "Cannot store image.\n";close $out or die "Cannot store image.\n";chmod 0644,$path;
        } 1;
    } or do {my $e=$@;unlink @made;die $e};
    return {filename=>$name,thumbnail=>$thumb,width=>$w,height=>$height,mime=>'image/'.($type eq 'jpg'?'jpeg':$type),bytes=>-s "$store/$folder/$name"};
}
# Deletes a stored picture and its thumbnail (any format), but only names
# that look like ours (32 hex characters), so nothing else can be deleted.
sub remove_image ($folder,$name) {
    return unless $name && $name =~ /\A([a-f0-9]{32})\.(?:jpg|png|webp)\z/;
    unlink "$store/$folder/$name", map {"$store/$folder/$1-thumb.$_"} qw(webp png jpg);
}
# Deletes a piece of album artwork, unless a track still uses it.
sub remove_art ($name) {return unless $name; return if $db->selectrow_array('SELECT count(*) FROM uploads WHERE artwork=?',undef,$name);remove_image('artwork',$name)}
# A title from an uploaded file's name: "Lesson_01-intro.mp4" → "Lesson 01 intro".
sub upload_title ($name) {my $title=basename($name);$title =~ s/\.[^.]+$//;$title =~ s/[_-]+/ /g;$title =~ s/^\s+|\s+$//g;return substr($title,0,300)||'Untitled'}
# Stores one photo or track and adds it to the top of its library; $artwork is
# the file name of album artwork already stored (music), or ''.
# Stores one uploaded picture or audio track and adds it at the top of its
# library (sort_order one lower than the current lowest). Pictures go
# through picture_add (Pictures.pm). Audio is kept exactly as uploaded:
# its format is recognised from its first bytes (WAV, FLAC, Ogg, M4A, MP3
# with an ID3 tag, or a raw AAC/MP3 frame header), and it's copied in 64 KB
# pieces up to 250 MB. If adding the catalogue entry fails, the file is
# removed again.
sub save_upload ($fh,$original,$kind,$collection,$description,$artwork='') {
    my $id=random_id(); my $item; my $path;
    # Pictures go to the library's folder ($collection is the folder's path).
    return picture_add($fh,$original,$collection,$description) if $kind eq 'photography';
    {
        binmode $fh; read($fh,my $magic,16); seek($fh,0,0);
        my $ext = substr($magic,0,4) eq 'RIFF' && substr($magic,8,4) eq 'WAVE' ? 'wav' : substr($magic,0,4) eq 'fLaC' ? 'flac' : substr($magic,0,4) eq 'OggS' ? 'ogg' : substr($magic,4,4) eq 'ftyp' ? 'm4a' : substr($magic,0,3) eq 'ID3' ? 'mp3' : length($magic)>1 && ord(substr($magic,0,1))==255 && (ord(substr($magic,1,1))&246)==240 ? 'aac' : length($magic)>1 && ord(substr($magic,0,1))==255 && (ord(substr($magic,1,1))&224)==224 ? 'mp3' : '';
        die "Use MP3, WAV, FLAC, Ogg, M4A or AAC audio.\n" unless $ext;
        my %mime=(mp3=>'audio/mpeg',wav=>'audio/wav',flac=>'audio/flac',ogg=>'audio/ogg',m4a=>'audio/mp4',aac=>'audio/aac');
        $path="$store/music/$id.$ext";
        attempt {
            open my $out,'>:raw',$path or die "Cannot store audio.\n";my $size=0;
            while (read($fh,my $buf,65536)) {$size+=length($buf);die "Audio must be 250 MB or smaller.\n" if $size>250*1048576;print {$out} $buf or die "Cannot store audio.\n"}
            close $out or die "Cannot store audio.\n";chmod 0644,$path;
            $item={filename=>"$id.$ext",thumbnail=>'',mime=>$mime{$ext},bytes=>$size};1;
        } or do {my $e=$@;unlink $path;die $e};
    }
    attempt {
        $db->do('INSERT INTO uploads (id,kind,title,description,collection,filename,thumbnail,mime,bytes,width,height,created_at,artwork,sort_order) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,(SELECT COALESCE(MIN(sort_order),0)-1 FROM uploads WHERE kind=?))',undef,$id,$kind,upload_title($original),$description,$collection,@$item{qw(filename thumbnail mime bytes width height)},now(),$kind eq 'music' ? $artwork : '',$kind);
        1;
    } or do {my $e=$@;$kind eq 'photography'?remove_image($kind,$item->{filename}):unlink($path);die $e};
    return $id;
}
# Removes an upload: its catalogue entry, its file(s) and any artwork no
# other track uses.
# Removes a library item: its catalogue entry, its tags, its file(s) by kind
# (picture and thumbnail, video and poster, the Files library's folder, or
# the audio file), and its album artwork if no other track uses it.
sub delete_upload ($item) {
    $db->do('DELETE FROM uploads WHERE id=?',undef,$item->{id});
    attempt {item_tags_set($item->{kind},$item->{id},'')};
    my ($kind,$file)=@$item{qw(kind filename)};
    if ($kind eq 'photography') {unlink grep {defined} map {picture_file($item,$_)} 0,1;remove_image($kind,$file)}
    elsif ($kind eq 'video') {unlink video_dir()."/$file" if $file =~ /\A[a-f0-9]{32}\.mp4\z/;remove_image('video',$item->{thumbnail}) if $item->{thumbnail}}
    elsif ($kind eq 'file') {file_remove($item)}
    elsif ($file =~ /\A[a-f0-9]{32}\.(?:mp3|wav|flac|ogg|m4a|aac)\z/) {unlink "$store/music/$file"}
    remove_art($item->{artwork});
}
# Photo, music and video actions besides the shared library ones (Library.pm):
# the plain form upload (used without JavaScript), artwork, posters, delete.
# The picture, music and video library actions that aren't shared with the
# other libraries (those are in Library.pm):
#   upload   the plain form upload of up to 20 files (videos and files must
#            use the uploader in pieces, which needs JavaScript)
#   artwork  set or remove a track's album artwork
#   poster   set a video's poster picture (Video.pm)
#   delete   remove an item
# Returns the message to show.
sub media_action ($kind) {
    my $action=param('action',30);my $id=param('id',32);
    if ($action eq 'upload') {
        die ucfirst(library_spec($kind)->{many})." are sent in pieces by the page's uploader, which needs JavaScript.\n" if $kind eq 'video' || $kind eq 'file';
        my @files=$q->upload('media');my @names=$q->multi_param('media');
        die "Choose up to 20 files.\n" unless @files && @files<=20;
        my $collection=$kind eq 'photography' ? param('folder',300) : param('collection',160);my $description=param('description',2000);
        die "That folder no longer exists. Reload the page.\n" if $kind eq 'photography' && !(folder_ok($collection) && folder_exists($collection));
        my $count=0;my @errors;
        my $art=$kind eq 'music' && $q->upload('artwork') ? save_image($q->upload('artwork'),'artwork')->{filename} : '';
        for my $i (0..$#files) {
            attempt {my $name=decode('UTF-8',"$names[$i]");save_upload($files[$i],$name,$kind,$collection,$description,$art);$count++;1} or push @errors,clean_error($@);
        }
        remove_art($art);
        return join ' ',"$count upload".($count==1?'':'s').' published.',@errors;
    }
    my $item=$db->selectrow_hashref('SELECT * FROM uploads WHERE id=? AND kind=?',undef,$id,$kind);
    die "Upload no longer exists.\n" unless $item;
    if ($action eq 'artwork' && $kind eq 'music') {
        my $cover=param('remove_artwork',1) eq '1'?undef:save_image($q->upload('artwork'),'artwork');
        attempt {$db->do('UPDATE uploads SET artwork=? WHERE id=?',undef,$cover?$cover->{filename}:'',$id);1} or do {my $e=$@;remove_image('artwork',$cover->{filename}) if $cover;die $e};
        remove_art($item->{artwork});return 'Artwork updated.';
    }
    return video_poster($item) if $action eq 'poster' && $kind eq 'video';
    if ($action eq 'delete') {delete_upload($item);return '“'.$item->{title}.'” deleted.'}
    die "Choose an action.\n";
}

# Gallery and music lists for the gallery and music blocks (Blocks.pm).
# A music list. %o page: link each to its item page with its likes and
# comments (1 by default; 0 on that page itself); tag_buttons: visitors can
# show one tag.
# Draws a list of tracks: artwork, title (linked to the track's own page),
# likes and comments count, collection, a player and a download link. The
# download's file name is the title with unusual characters removed.
sub music_list_html ($list,$show_filter=1,%o) {
    my $pages=$o{page}//1;my ($likes,$talk)=$pages ? talk_counts('music') : ({},{});my $stats=$pages && talk_library_on('music') && comments_enabled();
    return '<p class="empty-media">Nothing published yet. Check back soon.</p>' unless @$list;
    my $tmap=$o{tag_buttons} ? item_tags_map('music') : undef;
    my $html=($show_filter ? collection_filter_html($list) : '').tag_buttons_html($tmap,$list).'<div class="music-list">';
    for my $item (@$list) {
        my $title=h($item->{title});my $url=h(media_url($item));
        my ($ext)=$item->{filename}=~/\.([^.]+)$/;my $download=$item->{title};$download =~ s/[^\pL\pN _.-]//g;
        $html.='<article class="music-card" data-collection="'.h($item->{collection}).'"'.tags_data_attr($tmap,$item->{id}).'>';
        $html.='<img class="album-art" src="/media/artwork/'.h($item->{artwork}).'" alt="Artwork for '.$title.'" loading="lazy">' if $item->{artwork};
        my $link=$pages ? '<a href="/track/'.$item->{id}.'/">'.$title.'</a>' : $title;
        $html.='<div class="music-heading"><div><h2>'.$link.'</h2>'.($stats && !$item->{talk_off} ? talk_stats_html($likes->{$item->{id}},$talk->{$item->{id}}) : '').'<p class="media-label">'.h($item->{collection}).'</p></div><span class="badge">'.uc($ext).'</span></div><p>'.h($item->{description}).'</p>'.track_player_html($item).'<div class="track-download"><a class="buttonlike" href="'.$url.'" download="'.h("$download.$ext").'">download '.uc($ext).' ↓</a><span>'.megabytes($item->{bytes}).'</span></div></article>';
    }
    return $html.'</div>';
}
# A track's player alone (the browser's own controls; nothing loads until
# play). The Audio block's cards have it, and a text embedding a track shows
# only this.
sub track_player_html ($item) {
    return '<audio controls preload="none" aria-label="Listen to '.h($item->{title}).'"><source src="'.h(media_url($item)).'" type="'.h($item->{mime}).'"></audio>';
}
# The collection picker above a list, when its items have collections.
# The "collection" menu above a list, when its items belong to collections.
# It starts hidden; site.js shows it and filters the list.
sub collection_filter_html ($list) {
    my %c;$c{$_->{collection}}=1 for grep {length($_->{collection}//'')} @$list;
    return '' unless %c;
    return '<label class="collection-filter" hidden>collection <select class="collection-select"><option value="">All collections</option>'
        .join('',map {'<option value="'.h($_).'">'.h($_).'</option>'} sort keys %c).'</select></label>';
}
# The <dialog> that shows a picture larger. It's empty here; site.js fills
# in the picture and title when one is clicked.
sub photo_viewer_html {
    return '<dialog id="photo-viewer" aria-label="Photograph"><div class="viewer-tools"><p id="viewer-title"></p><a id="viewer-page" class="text-button" hidden>its page, likes and comments →</a><button type="button" id="viewer-close" aria-label="Close photograph">close ×</button></div><img id="viewer-image" alt="" draggable="false"></dialog>';
}

1;