repository

BlowfishCMS

A small content management system for OpenBSD

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

279 lines · 21.7 KB · download this file

package BlowfishCMS;
# Blog: RSS feed, sitemap, the Articles admin and the public blog.
# 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);

# A stored date (2026-11-23T10:00:00Z) in the format RSS feeds use
# ("Mon, 23 Nov 2026 10:00:00 +0000"); '' if it isn't a date.
sub rfc822 ($iso) {
    my ($y,$mo,$d,$h,$mi,$s)=($iso//'') =~ /\A(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)/ or return '';
    require Time::Local;my $t=(attempt {Time::Local::timegm($s,$mi,$h,$d,$mo-1,$y)}) // return '';
    return POSIX::strftime('%a, %d %b %Y %H:%M:%S +0000',gmtime $t);
}
# The blog's RSS feed (/blog/feed.xml): the 20 newest published articles,
# each with its title, address, date, opening lines and full text. The text
# goes in a CDATA section (taken as-is by feed readers); a "]]>" inside it
# would end that section early, so it's split in two. The site's own
# addresses in it (links, pictures, embedded players and their posters)
# are made whole, as a feed reader has no page to read them from.
sub blog_feed {
    my $site=site_url();
    my $posts=$db->selectall_arrayref('SELECT id,title,body,published_at,updated_at FROM posts WHERE published_at IS NOT NULL ORDER BY published_at DESC LIMIT 20',{Slice=>{}});
    my $built=@$posts ? rfc822((sort {$b cmp $a} map {$_->{updated_at}||$_->{published_at}} @$posts)[0]) : rfc822(now());
    my $xml=qq{<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">\n<channel>\n};
    my $by=length setting('author') ? 'Writing by '.setting('author').'.' : 'Writing from '.setting('site_title').'.';
    $xml.='<title>'.h(setting('site_title')).' — blog</title>'."\n<link>$site/blog/</link>\n".'<description>'.h($by)."</description>\n<language>en</language>\n";
    $xml.=qq{<atom:link href="$site/blog/feed.xml" rel="self" type="application/rss+xml"/>\n<lastBuildDate>$built</lastBuildDate>\n};
    for my $post (@$posts) {
        my $url="$site/blog/?post=$post->{id}";
        # Feed readers show content away from the site, so site-relative links must be absolute.
        (my $html=render_markdown($post->{body})) =~ s{(\s(?:src|href|poster)=")/(?!/)}{$1$site/}g;
        $html =~ s/]]>/]]]]><![CDATA[>/g;
        $xml.="<item>\n<title>".h($post->{title})."</title>\n<link>".h($url)."</link>\n<guid isPermaLink=\"true\">".h($url)."</guid>\n";
        $xml.='<pubDate>'.rfc822($post->{published_at})."</pubDate>\n<description>".h(post_excerpt($post->{body}))."</description>\n";
        $xml.="<content:encoded><![CDATA[$html]]></content:encoded>\n</item>\n";
    }
    return $xml."</channel>\n</rss>\n";
}
# The <link> in every page's head that lets browsers and feed readers find
# the feed.
sub feed_link { return '<link rel="alternate" type="application/rss+xml" title="'.h(setting('site_title')).' — blog" href="/blog/feed.xml">' }
# /sitemap.xml: the pages shown in the navigation plus every published post.
# /sitemap.xml, the list of addresses search engines are invited to read:
# every page that's on and not hidden from search engines, every published
# article (while Blog is on) and anything add-ons add, each with the date it
# last changed.
sub sitemap_xml {
    my $site=site_url();my $pages=page_registry();
    my $xml=qq{<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n};
    my %by=map {($_->{slug}=>$_)} @{all_pages()};
    for my $item (grep {$_->{visible}} nav_items()) {
        my $p=$by{$item->{page}} or next;next if $p->{noindex};
        my $date=substr($p->{updated_at}//'',0,10);
        $xml.='  <url><loc>'.h($site.$p->{path}).'</loc>'.($date =~ /\A\d{4}-\d\d-\d\d\z/ ? "<lastmod>$date</lastmod>" : '')."</url>\n";
    }
    for my $post (page_enabled('blog') ? @{$db->selectall_arrayref('SELECT id,published_at,updated_at FROM posts WHERE published_at IS NOT NULL ORDER BY published_at DESC',{Slice=>{}})} : ()) {
        my $date=substr($post->{updated_at}||$post->{published_at},0,10);
        $xml.='  <url><loc>'.h("$site/blog/?post=$post->{id}").'</loc>'.($date =~ /\A\d{4}-\d\d-\d\d\z/ ? "<lastmod>$date</lastmod>" : '')."</url>\n";
    }
    for my $entry (addon_sitemap()) {
        my ($path,$date)=ref $entry eq 'ARRAY' ? @$entry : ($entry,'');
        next unless ($path//'') =~ m{\A/(?!/)\S*\z};
        $xml.='  <url><loc>'.h($site.$path).'</loc>'.(($date//'') =~ /\A\d{4}-\d\d-\d\d\z/ ? "<lastmod>$date</lastmod>" : '')."</url>\n";
    }
    return $xml."</urlset>\n";
}

# ---- Articles (admin) ----------------------------------------------------------------
# /admin/?kind=blog lists the articles; &new=1 or &id=ID opens the writing
# screen: Markdown on the left, the article as visitors will see it on the
# right. Drafts save as you type (autosave); a published article changes only
# when you press "update". Images dropped or pasted into the text are uploaded
# and their Markdown inserted where the cursor is. Without JavaScript the
# buttons still work as ordinary form posts (with a preview button).
# Stores an article: inserts it, or updates it if it already exists (an
# "upsert").
sub article_saved ($id,$title,$body,$published) {
    $db->do('INSERT INTO posts (id,title,body,published_at,created_at,updated_at) VALUES (?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET title=excluded.title,body=excluded.body,published_at=excluded.published_at,updated_at=excluded.updated_at',undef,$id,$title,$body,$published,now(),now());
}
# The Articles screen (/admin/?kind=blog). Without an id it lists articles;
# with &new=1 or &id=ID it's the writing screen. Its actions:
#   talk_switch   likes and comments on or off for all articles
#   delete_post   delete an article and its tags
#   image_upload  a picture dropped or pasted into the text (the script then
#                 inserts its Markdown at the cursor)
#   preview_html  the article as visitors would see it, for the live preview
#   autosave      saves a draft as you type (never a published article)
#   preview / save_draft / publish / blog_image   the buttons, which also work
#                 without JavaScript
# Publishing keeps the first publication date; "unpublish" (save_draft on a
# published article) makes it a draft again.
sub blog_admin {
    my $id=param('id',32);$id='' unless $id =~ /\A[a-f0-9]{32}\z/;
    my $post=$id ? $db->selectrow_hashref('SELECT * FROM posts WHERE id=?',undef,$id) : undef;
    if ($id && !$post && $method eq 'GET') {admin_page('Article not found',section=>'blog',status=>404,crumbs=>[['Articles','/admin/?kind=blog']]);window('not found','<p>This article no longer exists.</p>');end_page();return}
    my $fetch=fetch_request();
    my $title=$post?$post->{title}:'';my $body=$post?$post->{body}:'';my $preview=0;my $message='';
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',30);
            if ($action eq 'talk_switch') {redirect('/admin/?kind=blog&notice='.CGI::escape(encode('UTF-8',talk_switch_save('blog'))))}
            if ($action eq 'delete_post') {
                $db->do('DELETE FROM posts WHERE id=?',undef,$id);
                item_tags_set('blog',$id,'');
                redirect('/admin/?kind=blog&notice='.CGI::escape(encode('UTF-8','Deleted “'.($post?$post->{title}:'the article').'”.')));
            }
            if ($action eq 'image_upload') {
                # Upload only; the editor inserts the Markdown where the cursor is.
                # Dropped and pasted pictures join the library's Articles folder.
                my $name=param('image',300)||'Image';
                my $picture=picture_by_id(picture_add($q->upload('image'),$name,articles_folder()));
                my $alt=param('alt',300);$alt=$picture->{title} unless length $alt;$alt =~ s/[\r\n\[\]\\]/ /g;
                json_response({ok=>JSON::PP::true,markdown=>"![$alt](".picture_url($picture).')'});
            }
            $title=param('title',300);$body=param('body',100000);$body =~ s/\r\n?/\n/g;
            if ($action eq 'preview_html') {
                my $shown={id=>$id||'preview',title=>length $title ? $title : 'Untitled',body=>$body,published_at=>($post && $post->{published_at}) || now()};
                json_response({ok=>JSON::PP::true,html=>public_preview(sub {article_page($shown,preview=>1)})});
            }
            if ($action eq 'autosave') {
                die "Published articles change only when you press update.\n" if $post && $post->{published_at};
                die "Give your article a title.\n" unless length $title;
                $id ||= random_id();
                article_saved($id,$title,$body,undef);
                item_extras_save('blog',$id);
                json_response({ok=>JSON::PP::true,id=>$id,message=>'Draft saved.'});
            }
            die "Give your article a title.\n" unless length $title;
            if ($action eq 'preview') {$preview=1}
            elsif ($action eq 'save_draft' || $action eq 'publish' || $action eq 'blog_image') {
                $id ||= random_id();my $image;
                if ($action eq 'blog_image') {
                    $image=picture_by_id(picture_add($q->upload('image'),param('image',300)||'Image',articles_folder(),'',param('image_alt',300)));
                    my $alt=param('image_alt',300)||'Image';$alt =~ s/[\r\n\[\]\\]/ /g;
                    $body.="\n\n![$alt](".picture_url($image).")\n";
                }
                my $was=$post ? $post->{published_at} : undef;
                my $published=$action eq 'publish' ? ($was//now()) : $action eq 'save_draft' ? undef : $was;
                attempt {article_saved($id,$title,$body,$published);item_extras_save('blog',$id);1} or do {my $e=$@;delete_upload($image) if $image;die $e};
                my $done=$action eq 'publish' ? ($was ? 'Published article updated.' : 'Published.') : $action eq 'save_draft' ? ($was ? 'Unpublished; it is a draft again.' : 'Draft saved.') : 'Image added at the end.';
                json_response({ok=>JSON::PP::true,id=>$id,message=>$done}) if $fetch;
                redirect('/admin/?kind=blog&id='.$id.'&notice='.CGI::escape(encode('UTF-8',$done)));
            } else {die "Choose an action.\n"}
            1;
        } or do {$message=failed_action($@);json_response({ok=>JSON::PP::false,message=>$message},400) if $fetch};
    }
    $message ||= param('notice',2000);
    return articles_list($message) unless $id || param('new',1) eq '1' || ($method eq 'POST' && param('action',30) ne 'delete_post');

    articles_folder();  # where the chooser opens and new pictures go
    my $published=$post && $post->{published_at};
    my $state=$published ? 'Published '.substr($post->{published_at},0,10) : $post ? 'Draft' : 'New draft';
    my $actions='<span class="admin-top__status" id="article-status" role="status">'.h($state).'</span>';
    $actions.='<a class="buttonlike" href="/blog/?post='.h($id).'" target="_blank" rel="noopener">view ↗</a>' if $published;
    $actions.=$published
        ? '<button class="buttonlike" form="article-editor" name="action" value="save_draft">unpublish</button><button class="buttonlike is-primary" form="article-editor" name="action" value="publish">update</button>'
        : '<button class="buttonlike" form="article-editor" name="action" value="save_draft">save draft</button><button class="buttonlike is-primary" form="article-editor" name="action" value="publish">publish</button>';
    admin_page(length $title ? $title : 'New article',section=>'blog',crumbs=>[['Articles','/admin/?kind=blog']],notice=>$message,actions=>$actions);
    my $html='<form method="post" action="/admin/" enctype="multipart/form-data" class="admin-form article-editor" id="article-editor" data-published="'.($published?1:0).'">'.hidden(csrf=>$csrf,kind=>'blog',id=>$id)
        .'<input class="article-editor__title" name="title" maxlength="300" required placeholder="Title" aria-label="Title" value="'.h($title).'">'
        .'<div class="article-editor__panes"><div class="article-editor__write">'
        .'<div class="article-editor__tools"><label class="buttonlike article-editor__image">upload a picture<input type="file" name="image" accept="image/jpeg,image/png,image/webp"></label><span class="media-label">or drop / paste one into the text. New pictures go into the library’s Articles folder.</span>'.markdown_help_html(note=>'Picture addresses are public, even in drafts.').'</div>'
        .'<textarea name="body" rows="24" maxlength="100000" id="blog-body" aria-label="Article text (Markdown)" data-markdown="pictures" data-picture-folder="articles">'.h($body).'</textarea>'
        .'<div class="article-editor__extras">'.tags_input_html('blog',$id).talk_off_input_html($post//{}).'</div>'
        .'<fieldset class="inline-image no-js-only"><legend>Insert a picture</legend><p class="media-label">Uploading saves the article and adds the image’s Markdown at the end.</p><label>Image description<input name="image_alt" maxlength="300"></label><button class="buttonlike" name="action" value="blog_image">upload &amp; insert picture</button></fieldset>'
        .'<p class="no-js-only"><button class="buttonlike" name="action" value="preview">preview</button></p>'
        .'</div><div class="article-editor__preview" hidden><div class="preview-frame" data-preview></div></div></div></form>';
    print $html;
    window('preview · not saved',article_preview_html($title,$body),'blog-body') if $preview;
    print '<form method="post" action="/admin/" class="delete-form">'.fields('delete_post','blog',$id).'<button class="buttonlike danger">delete this article</button></form>' if $id;
    end_page();
}
# An article's title and text as HTML, for the preview without JavaScript.
sub article_preview_html ($title,$body) { return '<h1>'.h($title).'</h1>'.render_markdown($body) }
# The list of articles: title, published or draft, when last edited, its
# comment count (linking to its comments) and view and delete. The search box
# and status filter are shown and run by admin.js.
sub articles_list ($message) {
    admin_page('Articles',section=>'blog',notice=>$message,intro=>'Write in Markdown with inline images. Drafts stay private until you publish.',
        actions=>library_page_action('blog').'<a class="buttonlike is-primary" href="/admin/?kind=blog&amp;new=1">new article</a>');
    my $posts=$db->selectall_arrayref('SELECT id,title,published_at,created_at,updated_at FROM posts ORDER BY COALESCE(published_at,updated_at) DESC,id DESC',{Slice=>{}});
    unless (@$posts) {print '<p class="empty-media">No articles yet. <a href="/admin/?kind=blog&amp;new=1">Write the first one</a>.</p>';end_page();return}
    my $c=comments_enabled() ? (attempt {comments_db()}) : undef;my %talk=$c ? (map {@$_} @{$c->selectall_arrayref('SELECT post_id,count(*) FROM comments GROUP BY post_id')}) : ();
    my $drafts=grep {!$_->{published_at}} @$posts;
    print '<section class="lib" id="articles" data-one="article" data-many="articles"><div class="lib-tools" hidden><input type="search" class="lib-search" placeholder="Search articles" aria-label="Search articles">'
        .'<select class="lib-filter" aria-label="Status"><option value="">All ('.@$posts.')</option><option value="published">Published ('.(@$posts-$drafts).')</option><option value="draft">Drafts ('.$drafts.')</option></select><span class="lib-count" role="status"></span></div>';
    my @rows;
    for my $p (@$posts) {
        my $state=$p->{published_at} ? 'published' : 'draft';my $n=$talk{$p->{id}}//0;
        push @rows,admin_row(title=>$p->{title},href=>"/admin/?kind=blog&id=$p->{id}",class=>'lib-item',attrs=>' data-collection="'.$state.'" data-text="'.h(lc $p->{title}).'"',
            badges=>[$p->{published_at} ? ['Published','live'] : 'Draft'],
            meta=>[($p->{published_at} ? 'published '.h(substr($p->{published_at},0,10)) : ()),'edited '.h(substr($p->{updated_at}//$p->{created_at},0,16) =~ s/T/ /r),
                $n ? '<a href="/admin/comments/?item='.$p->{id}.'">'.$n.' '.($n==1 ? 'comment' : 'comments').'</a>' : 'no comments'],
            actions=>'<a class="buttonlike" href="/admin/?kind=blog&amp;id='.$p->{id}.'">edit</a>'.($p->{published_at} ? '<a class="buttonlike" href="/blog/?post='.$p->{id}.'" target="_blank" rel="noopener">view ↗</a>' : ''),
            menu=>'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete the article “$p->{title}”? This cannot be undone.").'">'.fields('delete_post','blog',$p->{id}).'<button class="text-button danger" aria-label="Delete '.h($p->{title}).'">delete</button></form>');
    }
    print admin_list(\@rows),'<p class="empty-media lib-none" hidden>Nothing matches.</p></section>';
    print talk_switch_html('blog');
    end_page();
}
# A single published post at /blog/?post=ID. The blog list itself is the
# posts block (Blocks.pm).
# /blog/?post=ID: one published article, or "not found".
sub blog_post ($id) {
    my $post=$db->selectrow_hashref('SELECT * FROM posts WHERE id=? AND published_at IS NOT NULL',undef,$id);
    unless ($post) {start_page('Post not found','/blog/',404);window('not found','<h1>Post not found</h1><p><a href="/blog/">All posts</a></p>');end_page();return}
    article_page($post);
}
# An article as visitors see it; the editor's preview leaves out sharing,
# likes and comments.
# Draws one article as visitors see it: its title and date, its text and
# tags, then sharing, likes and comments (left out in the editor's preview).
sub article_page ($post,%o) {
    # The share picture: the article's first picture from the library.
    my ($image)=grep {image_path($_)} ($post->{body}//'') =~ m{!\[[^\]]*\]\((/media/[^)\s]+)\)}g;
    start_page($post->{title},'/blog/?post='.$post->{id},200,{og=>1,talk=>1,article=>$post,description=>post_excerpt($post->{body})||(length setting('author') ? 'A post by '.setting('author').'.' : undef),image=>$image});
    window('blog','<h1>'.h($post->{title}).'</h1><p><time datetime="'.h($post->{published_at}).'">'.h(substr($post->{published_at},0,10)).'</time> · <a href="/blog/">all posts</a></p>','media-intro');
    window('post',render_markdown($post->{body}).tags_html(item_tags('blog',$post->{id})),'blog-body');
    item_engagement(item_find('blog',$post->{id})) unless $o{preview};
    end_page();
}
# Published articles, newest first: a list, or cards with each article's
# first picture; with or without the date and the opening lines.
# A list of published articles, newest first, as a plain list or as cards
# with each article's first picture; optionally with dates and opening
# lines, and with each article's likes and comments (counted in two queries
# for the whole list).
sub post_list_html ($posts,%o) {
    return '<p class="empty-media">No posts yet. Check back soon.</p>' unless @$posts;
    my $date=$o{date}//1;
    my $c=comments_enabled() ? (attempt {comments_db()}) : undef;my (%likes,%talk);
    if ($c) {%likes=map {@$_} @{$c->selectall_arrayref('SELECT post_id,count(*) FROM likes GROUP BY post_id')};%talk=map {@$_} @{$c->selectall_arrayref('SELECT post_id,count(*) FROM comments WHERE hidden=0 GROUP BY post_id')}}
    my $html='';
    for my $post (@$posts) {
        my ($l,$n)=($likes{$post->{id}}//0,$talk{$post->{id}}//0);
        my $stats=$c ? '<span class="post-stats">♥ '.$l.' · '.$n.' '.($n==1?'comment':'comments').'</span>' : '';
        my $when=$date ? '<time class="media-label" datetime="'.h($post->{published_at}).'">'.h(substr($post->{published_at},0,10)).'</time>' : '';
        my $link='/blog/?post='.$post->{id};
        my $lead=$o{excerpt} ? post_excerpt($post->{body}) : '';
        $lead='<p class="post-excerpt">'.h($lead).'</p>' if length $lead;
        if ($o{cards}) {
            my ($pic)=($post->{body}//'') =~ m{!\[[^\]]*\]\((/media/[^)\s]+)};
            $html.='<article class="card">'.($pic ? '<div class="card__picture"><a href="'.h($link).'" tabindex="-1" aria-hidden="true"><img src="'.h($pic).'" alt="" loading="lazy" decoding="async"></a></div>' : '')
                .'<div class="card__body">'.$when.'<h3><a href="'.h($link).'">'.h($post->{title}).'</a></h3>'.$lead.$stats.'</div></article>';
        } else {
            $html.='<article>'.$when.'<h2><a href="'.h($link).'">'.h($post->{title}).'</a></h2>'.$lead.$stats.'</article>';
        }
    }
    return $o{cards} ? '<div class="cards cards--3 shape-wide post-cards">'.$html.'</div>' : $html;
}
# An article's opening lines as plain text (Markdown, pictures and links taken out).
# An article's first paragraph as plain text: pictures, link addresses,
# heading and list marks and emphasis are taken out, and it's cut to about
# 220 characters at a word boundary.
sub post_excerpt ($body) {
    my $t=$body//'';
    $t =~ s/!\[[^\]]*\]\([^)]*\)//g;$t =~ s/\[([^\]]*)\]\([^)]*\)/$1/g;
    $t =~ s/^\s*(?:#+|[-*>]|\d+\.)\s*(?:\[[ xX]\]\s+)?//mg;$t =~ s/[*_`]|~~//g;
    # Footnotes, their marks, and headings' {#name} anchors.
    $t =~ s/^\s{0,3}\[\^[A-Za-z0-9_-]{1,30}\]:.*$//mg;$t =~ s/\[\^[A-Za-z0-9_-]{1,30}\]//g;$t =~ s/\s*\{#[a-z][a-z0-9-]*\}\s*$//mg;
    # The page tools' marks: ::: and +++ lines (a fold-out's title stays),
    # ||| between columns, [!NOTE], {.button}, ==, [[keys]] and ": " before a definition.
    $t =~ s/^\s{0,3}(?::{3,}.*|\|\|\|\s*|\+{3,}\s*)$//mg;$t =~ s/^\s{0,3}\+{3,}\s+//mg;$t =~ s/\[![A-Za-z]+\]\s*//g;
    $t =~ s/\{\.[a-z][^{}\n]*\}//g;$t =~ s/==|\[\[|\]\]//g;$t =~ s/^:\s+//mg;
    my ($first)=grep {/\S/} split /\n\s*\n/,$t;
    $first=($first//'') =~ s/\s+/ /gr =~ s/\A\s+|\s+\z//gr;
    return length $first>220 ? substr($first,0,217) =~ s/\s+\S*\z//r.'…' : $first;
}

1;