repository

BlowfishCMS

A small content management system for OpenBSD

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

127 lines · 7.7 KB · download this file

package BlowfishCMS;
# The Files library: anything to download (a release, a PDF, a font…).
#
#   storing    uploads in pieces (Library.pm), then file_publish: the file
#              keeps its own (cleaned) name in a folder of its own,
#              media/file/ID/NAME, with its size and sha256.
#   serving    httpd serves /media/file/ straight from disk, as downloads
#              only (Content-Disposition: attachment, and a sandbox policy),
#              so an uploaded HTML file can never run as the site.
#   counting   links go to /download/ID/ (the comments service), which
#              counts the download, unless it's a robot, and sends the
#              browser on to the file. Counts are kept per day in the
#              comments database (`downloads`), nothing about the visitor.
#   showing    each file has a page (/file/ID/) like every library item,
#              and the Download block shows one file or a list.
use v5.36;
use utf8;
use Digest::SHA;
use File::Basename qw(basename);
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);

# Where the Files library keeps its files: media/file/ID/NAME, one folder
# per file so it can keep its own name.
sub file_dir { "$store/file" }

# A name that is safe on disk and in an address: letters, digits, dot,
# dash and underscore; spaces become dashes; no leading dot.
sub file_safe_name ($name) {
    my $n=basename($name//'');$n =~ s/\s+/-/g;$n =~ s/[^A-Za-z0-9._-]+//g;$n =~ s/\A[.-]+//;$n =~ s/\.{2,}/./g;
    $n=substr($n,-120) if length $n>120;
    return length $n ? $n : 'download';
}
# A title from the file's name: .tar.gz and the like count as one extension.
sub file_title ($name) { my $n=basename($name//'');$n =~ s/\.tar(?=\.[A-Za-z0-9]{1,4}\z)//i;return upload_title($n) }
# The file's SHA-256 checksum (read in binary), shown with each download so
# visitors can check the file they got.
sub file_sha256 ($path) { my $s=Digest::SHA->new(256);$s->addfile($path,'b');return $s->hexdigest }

# Moves a finished upload into the library.
# Turns a finished upload into a library file: works out a safe name,
# computes its checksum and size, makes its folder, moves the file in, and
# adds the catalogue entry at the top of the library. If the entry can't be
# added, the file and folder are removed again.
sub file_publish ($part,$meta) {
    die "The files folder isn't set up yet. Run the server setup again (blowfishctl httpd), then try again.\n" unless -d file_dir() && -w file_dir();
    my $id=random_id();my $name=file_safe_name($meta->{name});my $dir=file_dir()."/$id";
    my $sha=file_sha256($part);my $bytes=-s $part;
    mkdir $dir,0755 or die "The file could not be stored.\n";
    attempt {
        rename($part,"$dir/$name") or die "The file could not be stored.\n";
        chmod 0644,"$dir/$name";chmod 0755,$dir;
        $db->do('INSERT INTO uploads (id,kind,title,description,collection,filename,thumbnail,mime,bytes,width,height,created_at,artwork,sort_order,sha256) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,(SELECT COALESCE(MIN(sort_order),0)-1 FROM uploads WHERE kind=?),?)',
            undef,$id,'file',file_title($meta->{name}),$meta->{description}//'',$meta->{collection}//'',"$id/$name",'','application/octet-stream',$bytes,undef,undef,now(),'','file',$sha);
        1;
    } or do {my $e=$@;unlink "$dir/$name";rmdir $dir;die $e};
    return '“'.file_title($meta->{name}).'” published.';
}
# Deletes a library file and its folder (only a path of the shape we make,
# ID/NAME, so nothing else can be deleted).
sub file_remove ($item) {
    my ($dir,$name)=($item->{filename}//'') =~ m{\A([a-f0-9]{32})/([A-Za-z0-9._-]+)\z} or return;
    unlink file_dir()."/$dir/$name";rmdir file_dir()."/$dir";
}
# The file's own name (the part after ID/).
sub file_name ($item) { return ($item->{filename}//'') =~ m{/([^/]+)\z} ? $1 : '' }

# ---- Downloads -------------------------------------------------------------------------
# Download links go through /download/ID/ so they can be counted.
sub download_path ($item) { return "/download/$item->{id}/" }
# /download/ID/ (comments service): count, then on to the file.
# /download/ID/, handled by the comments service (which owns the download
# counts): adds one to today's count for the file (unless it's a robot, or a
# HEAD request that doesn't download), then redirects to the file itself,
# which httpd serves directly. Only the file and the day are kept, nothing
# about who downloaded it.
sub download_route ($path) {
    my ($id)=$path =~ m{\A/download/([a-f0-9]{32})/?\z} or do {header(404,'text/plain; charset=UTF-8');print 'Not found';return};
    my $item=item_find('file',$id) or do {header(404,'text/plain; charset=UTF-8');print 'Not found';return};
    unless (analytics_bot($ENV{HTTP_USER_AGENT}//'') || ($method ne 'GET')) {
        attempt {
            my $c=comments_db(1) or return 1;
            $c->do('INSERT INTO downloads (item,day,n) VALUES (?,?,1) ON CONFLICT(item,day) DO UPDATE SET n=n+1',undef,$id,substr(now(),0,10));
            1;
        } or warn $@;
    }
    redirect(media_url($item->{row}));
}
# Downloads of every file: {id => total}, or of the last $days days.
# Downloads per file, {id => count}: in total, or over the last $days days.
# Empty when the comments database can't be read.
sub download_counts ($days=0) {
    my $c=comments_enabled() ? (attempt {comments_db()}) : undef or return {};
    my $rows=(attempt {$c->selectall_arrayref('SELECT item,sum(n) FROM downloads'.($days ? " WHERE day>=date('now','-$days days')" : '').' GROUP BY item')}) // [];
    return {map {($_->[0]=>$_->[1])} @$rows};
}

# ---- On the site -------------------------------------------------------------------------
# "version 1.2 · ZIP · 3.4 MB" for a file.
sub file_facts ($u) {
    my $ext=(file_name($u) =~ /\.([A-Za-z0-9]{1,8})\z/) ? uc $1 : '';
    return join ' · ',grep {length} (length($u->{version}//'') ? 'version '.$u->{version} : ''),$ext,megabytes($u->{bytes}//0);
}
# One file: its name, a download button, and its size, version and sha256.
# One file as visitors see it: its title (linked to its page), description,
# facts, checksum and a download button. %o: tmap (tags, for tag buttons),
# page (link to its page), brief (leave out the description), stats (likes
# and comments HTML).
sub file_card_html ($u,%o) {
    my $attr=$o{tmap} ? tags_data_attr($o{tmap},$u->{id}) : '';
    my $pages=$o{page}//1;my $title=h($u->{title});
    my $html='<article class="file-card" data-collection="'.h($u->{collection}//'').'"'.$attr.'><div class="file-card__text"><h2>'.($pages ? '<a href="/file/'.$u->{id}.'/">'.$title.'</a>' : $title).'</h2>'
        .(length($u->{description}//'') && !$o{brief} ? '<p>'.h($u->{description}).'</p>' : '')
        .'<p class="file-card__facts">'.h(file_facts($u)).($o{stats} // '').'</p>'
        .(length($u->{sha256}//'') ? '<p class="file-card__sha"><span class="media-label">sha256</span> <code>'.h($u->{sha256}).'</code></p>' : '')
        .'</div><a class="cta cta--theme form-submit file-card__get" href="'.download_path($u).'" download="'.h(file_name($u)).'">download</a></article>';
    return $html;
}
# A list of files for the Download block, with optional tag buttons and each
# file's likes and comments count.
sub file_list_html ($list,%o) {
    return '<p class="empty-media">No files yet.</p>' unless @$list;
    my $pages=$o{page}//1;my ($likes,$talk)=$pages ? talk_counts('file') : ({},{});my $stats=$pages && talk_library_on('file') && comments_enabled();
    my $tmap=$o{tag_buttons} ? item_tags_map('file') : undef;
    return tag_buttons_html($tmap,$list).'<div class="file-list">'.join('',map {file_card_html($_,%o,tmap=>$tmap,stats=>($stats && !$_->{talk_off} ? ' '.talk_stats_html($likes->{$_->{id}},$talk->{$_->{id}}) : ''))} @$list).'</div>';
}

1;