BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
257 lines · 21.4 KB · download this file
package BlowfishCMS::Addon::Newsletter;
# Newsletter: a sign-up block, subscribers who confirm by email, and issues
# written and sent from the admin.
#
# Where each part runs:
# public service the sign-up block on pages.
# newsletter service (its own account, _bfxnewsletter) /x/newsletter/
# subscribe, confirm and unsubscribe, and the
# Newsletter screen (/admin/x/newsletter/), on its own
# database: subscribers' addresses are only there.
# Mail goes through BlowfishCMS's mail queue (the site's Postmark
# connection): one message per subscriber, with List-Unsubscribe headers, on
# the Postmark message stream chosen in its settings.
use v5.36;
use utf8;
use Encode qw(encode decode);
use Digest::SHA qw(sha256_hex);
use JSON::PP ();
BEGIN { no strict 'refs'; *{$_}=\&{"BlowfishCMS::$_"} for qw(h param redirect admin_page window end_page fields hidden failed_action random_id now attempt window_html render_markdown header site_url own_origin start_page mail_queue mail_address_ok setting) }
# ---- The block ----------------------------------------------------------------------
sub blocks {
return {newsletter_signup=>{label=>'Newsletter sign-up',order=>47,group=>'content',about=>'A form to get your newsletter by email (visitors confirm from their inbox).',
fields=>[[title=>'Panel title','text',120],[subtitle=>'Panel subtitle','text',160,'optional'],[intro=>'Text','markdown',1000,'optional; what they’ll get'],[button=>'Button','text',40]],
defaults=>{title=>'newsletter',button=>'Subscribe'},render=>\&render_block}};
}
sub render_block ($b,%o) {
my $d=$b->{data};my $state=$BlowfishCMS::q->param('newsletter')//'';
my $back=($BlowfishCMS::route//'/') =~ m{\A/[a-z0-9/-]*\z} ? $BlowfishCMS::route : '/';
my $html=length($d->{intro}//'') ? render_markdown($d->{intro}) : '';
if ($state eq 'check') {$html.='<p class="newsletter-done" id="newsletter" role="status">Nearly done: check your email and press the link in it to confirm.</p>'}
else {
$html.='<form class="newsletter-form" id="newsletter" method="post" action="/x/newsletter/subscribe">'
.'<input type="hidden" name="back" value="'.h($back).'"><input type="hidden" name="t" value="'.time().'">'
.'<label class="newsletter-trap" aria-hidden="true">Leave this empty<input name="website" tabindex="-1" autocomplete="off"></label>'
.'<label>Your email address<input type="email" name="email" maxlength="254" autocomplete="email" required></label>'
.'<button class="buttonlike" type="submit">'.h(length($d->{button}//'') ? $d->{button} : 'Subscribe').'</button></form>'
.'<p class="newsletter-note">We’ll email you a link to confirm. Every issue has a link to unsubscribe.</p>';
}
return window_html($d->{title},$d->{subtitle},$html,%o);
}
# ---- The newsletter service: subscribers and issues ------------------------------------------
sub db {
state %open;my $file=BlowfishCMS::addon_data_dir('newsletter').'/newsletter.sqlite';
return $open{$file} if $open{$file} && $open{$file}->ping;
my $n=DBI->connect("dbi:SQLite:dbname=$file",'','',{RaiseError=>1,PrintError=>0,AutoCommit=>1,sqlite_unicode=>1});
$n->do('PRAGMA busy_timeout=5000');
$n->do("CREATE TABLE IF NOT EXISTS subscribers (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE COLLATE NOCASE, status TEXT NOT NULL, token TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, confirmed_at TEXT, left_at TEXT, mailed_at TEXT, visitor TEXT NOT NULL DEFAULT '', source TEXT NOT NULL DEFAULT 'form')");
$n->do("CREATE TABLE IF NOT EXISTS issues (id TEXT PRIMARY KEY, subject TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft', recipients INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, sent_at TEXT)");
$n->do('CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
return $open{$file}=$n;
}
sub conf ($key,$default='') { return (attempt {db()->selectrow_array('SELECT value FROM settings WHERE key=?',undef,$key)}) // $default }
sub conf_save (%v) { db()->do('INSERT INTO settings (key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',undef,$_,$v{$_}) for keys %v }
sub sender_name { my $n=conf('from_name','');return length $n ? $n : setting('site_title') }
sub message_page ($title,$html,$status=200) {
start_page($title,'/x/newsletter/',$status,{noindex=>1});
BlowfishCMS::window(lc $title,'<h1>'.h($title).'</h1>'.$html);
BlowfishCMS::end_page();
}
sub link_for ($what,$token) { return site_url()."/x/newsletter/$what?t=$token" }
sub subscriber_by_token ($t) { return ($t//'') =~ /\A[a-f0-9]{32}\z/ ? db()->selectrow_hashref('SELECT * FROM subscribers WHERE token=?',undef,$t) : undef }
sub send_confirmation ($s) {
my $name=sender_name();
mail_queue('newsletter',to=>$s->{email},from_name=>$name,tag=>'newsletter-confirm',
subject=>"Confirm your subscription to $name",
text=>"Someone (we hope you) asked to get the $name newsletter at this address.\n\nTo confirm, open this link:\n".link_for('confirm',$s->{token})."\n\nIf it wasn’t you, ignore this email: nothing will be sent to you.\n\n$name\n".site_url()."\n");
db()->do('UPDATE subscribers SET mailed_at=? WHERE id=?',undef,now(),$s->{id});
}
sub subscribe {
if ($BlowfishCMS::method ne 'POST') {header(405,'text/plain; charset=UTF-8');print 'Method Not Allowed';return}
my $origin=$ENV{HTTP_ORIGIN}//'';
if (length $origin && !own_origin($origin)) {header(403,'text/plain; charset=UTF-8');print 'Forbidden';return}
my $back=param('back',200);$back='/' unless $back =~ m{\A/[a-z0-9/-]*\z};
# Whatever happens, the visitor is told the same (no one learns who's subscribed).
my $done=sub {redirect("$back?newsletter=check#newsletter")};
my $t=param('t',12);
$done->() if length(param('website',200)) || ($t =~ /\A\d+\z/ && time-$t<2);
my $email=lc param('email',254);
unless (mail_address_ok($email)) {message_page('Not subscribed','<p>That isn’t an email address. <a href="javascript:history.back()">Go back</a> and check it.</p>',400);return}
my $n=db();
my $visitor=sha256_hex(($ENV{REMOTE_ADDR}//'').'|'.int(time/3600).'|newsletter');
my $since=BlowfishCMS::strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-3600));
if ($n->selectrow_array('SELECT count(*) FROM subscribers WHERE visitor=? AND created_at>?',undef,$visitor,$since)>=5) {message_page('Not subscribed','<p>Too many sign-ups from here in the last hour. Try again later.</p>',429);return}
my $s=$n->selectrow_hashref('SELECT * FROM subscribers WHERE email=?',undef,$email);
if (!$s) {
my $id=random_id();
$n->do('INSERT INTO subscribers (id,email,status,token,created_at,visitor) VALUES (?,?,?,?,?,?)',undef,$id,$email,'pending',random_id(),now(),$visitor);
$s=$n->selectrow_hashref('SELECT * FROM subscribers WHERE id=?',undef,$id);
send_confirmation($s);
}
elsif ($s->{status} ne 'active') {
# Asked again: another confirmation, at most one an hour (and someone who left can come back).
if (!$s->{mailed_at} || $s->{mailed_at} lt $since) {
$n->do("UPDATE subscribers SET status='pending',token=?,visitor=? WHERE id=?",undef,random_id(),$visitor,$s->{id});
send_confirmation($n->selectrow_hashref('SELECT * FROM subscribers WHERE id=?',undef,$s->{id}));
}
}
$done->();
}
sub confirm {
my $s=subscriber_by_token(param('t',40));
unless ($s && $s->{status} ne 'left') {message_page('Link expired','<p>This link isn’t valid any more. Sign up again from the site to get a new one.</p><p><a href="/">Back to the site</a></p>',404);return}
db()->do("UPDATE subscribers SET status='active',confirmed_at=coalesce(confirmed_at,?) WHERE id=?",undef,now(),$s->{id}) if $s->{status} eq 'pending';
message_page('You’re subscribed','<p>Thank you. '.h(sender_name()).'’s newsletter will come to '.h($s->{email}).'. Each issue has a link to unsubscribe.</p><p><a href="/">Back to the site</a></p>');
}
# Unsubscribing: a page with a button (so a mail scanner opening links can't
# do it), and a one-click POST for mail apps (List-Unsubscribe-Post).
sub unsubscribe {
# A POST (the button, or a mail app's one click) carries the token in its address.
my $t=param('t',40);$t=scalar($BlowfishCMS::q->url_param('t'))//'' unless length $t;
my $s=subscriber_by_token($t);
unless ($s) {message_page('Link expired','<p>This link isn’t valid any more. If you still get the newsletter, use the link in the newest issue.</p>',404);return}
if ($BlowfishCMS::method eq 'POST') {
db()->do("UPDATE subscribers SET status='left',left_at=? WHERE id=? AND status<>'left'",undef,now(),$s->{id});
message_page('Unsubscribed','<p>'.h($s->{email}).' won’t get the newsletter any more.</p><p><a href="/">Back to the site</a></p>');
return;
}
if ($s->{status} eq 'left') {message_page('Unsubscribed','<p>'.h($s->{email}).' is already unsubscribed.</p>');return}
message_page('Unsubscribe','<p>Stop sending '.h(sender_name()).'’s newsletter to '.h($s->{email}).'?</p><form method="post" action="/x/newsletter/unsubscribe?t='.h($s->{token}).'"><button class="buttonlike" type="submit">unsubscribe</button></form>');
}
sub route ($rest) {
return subscribe() // 1 if $rest eq 'subscribe';
return confirm() // 1 if $rest eq 'confirm';
return unsubscribe() // 1 if $rest eq 'unsubscribe';
return 0;
}
sub robots { return ['/x/newsletter/'] }
# ---- An issue as an email ------------------------------------------------------------------
sub issue_text ($i,$token) {
my $name=sender_name();my $footer=conf('footer','');
return ($i->{body} =~ s/\r\n?/\n/gr)."\n\n--\n$name · ".site_url()."\n".(length $footer ? "$footer\n" : '')."Unsubscribe: ".link_for('unsubscribe',$token)."\n";
}
sub issue_html ($i,$token) {
my $name=sender_name();my $footer=conf('footer','');
return '<!doctype html><html><body style="margin:0;padding:24px;background:#f4f4f5"><div style="max-width:620px;margin:0 auto;padding:24px;background:#ffffff;border-radius:8px;font:16px/1.6 -apple-system,Segoe UI,Helvetica,Arial,sans-serif;color:#1f2933">'
.render_markdown($i->{body})
.'<hr style="border:0;border-top:1px solid #e4e7eb;margin:24px 0 12px"><p style="font-size:13px;color:#616e7c">'.h($name).' · <a href="'.h(site_url()).'">'.h(site_url() =~ s{\Ahttps?://}{}r).'</a>'
.(length $footer ? '<br>'.h($footer) : '').'<br><a href="'.h(link_for('unsubscribe',$token)).'">Unsubscribe</a></p></div></body></html>';
}
sub queue_issue ($i,$to,$token) {
mail_queue('newsletter',to=>$to,from_name=>sender_name(),tag=>'newsletter',subject=>$i->{subject},
text=>issue_text($i,$token),html=>issue_html($i,$token),stream=>conf('stream','broadcast'),
($token ne 'preview' ? (headers=>{'List-Unsubscribe'=>'<'.link_for('unsubscribe',$token).'>','List-Unsubscribe-Post'=>'List-Unsubscribe=One-Click'}) : ()));
}
# ---- The Newsletter screen (/admin/x/newsletter/) -------------------------------------------
sub issue ($id) { return ($id//'') =~ /\A[a-f0-9]{32}\z/ ? db()->selectrow_hashref('SELECT * FROM issues WHERE id=?',undef,$id) : undef }
sub csv_cell ($v) { $v//='';$v="'$v" if $v =~ /\A[=+\-@\t\r]/;return $v =~ /[",\n\r]/ ? '"'.($v =~ s/"/""/gr).'"' : $v }
sub service_admin ($rest) {
my $n=db();
if ($rest eq 'subscribers.csv') {
my $rows=$n->selectall_arrayref("SELECT email,confirmed_at FROM subscribers WHERE status='active' ORDER BY confirmed_at");
header(200,'text/csv; charset=utf-8',"Content-Disposition: attachment; filename=\"subscribers.csv\"\r\n");
print "\x{FEFF}Email,Subscribed\r\n".join('',map {csv_cell($_->[0]).','.csv_cell(($_->[1]//'') =~ s/T/ /r =~ s/Z\z/ UTC/r)."\r\n"} @$rows);
return 1;
}
return 0 unless $rest eq '';
my $message=param('notice',2000);my $edit=issue(param('edit',32) || param('id',32));
my $back=sub ($text,$extra='') {redirect('/admin/x/newsletter/?notice='.CGI::escape(encode('UTF-8',$text)).$extra)};
if ($BlowfishCMS::method eq 'POST') {
attempt {
my $action=param('action',30);
if ($action eq 'issue_save') {
# The buttons say what to do with it: save (the default), test or send.
my $do=param('do',10);
my ($subject,$body)=(param('subject',200),param('body',50000));$body =~ s/\r\n?/\n/g;
die "Give the issue a subject.\n" unless length $subject;
die "Write something in the issue.\n" unless $body =~ /\S/;
die "That issue was already sent; start a new one.\n" if $edit && $edit->{status} eq 'sent';
my $id=$edit ? $edit->{id} : random_id();
if ($edit) {$n->do('UPDATE issues SET subject=?,body=?,updated_at=? WHERE id=?',undef,$subject,$body,now(),$id)}
else {$n->do('INSERT INTO issues (id,subject,body,created_at,updated_at) VALUES (?,?,?,?,?)',undef,$id,$subject,$body,now(),now())}
my $i=issue($id);
if ($do eq 'test') {queue_issue($i,'owner','preview');$back->('A test of the issue is on its way to you.',"&edit=$id#issue")}
if ($do eq 'send') {
die "To send it, tick “Yes, send it now”.\n" unless param('sure',1) eq '1';
my $list=$n->selectall_arrayref("SELECT email,token FROM subscribers WHERE status='active' ORDER BY confirmed_at");
die "There’s no one to send it to yet.\n" unless @$list;
$n->do("UPDATE issues SET status='sending',updated_at=? WHERE id=? AND status='draft'",undef,now(),$id)>0 or die "That issue is already being sent.\n";
my $sent=0;
for (@$list) {attempt {queue_issue($i,$_->[0],$_->[1]);$sent++}}
$n->do("UPDATE issues SET status='sent',recipients=?,sent_at=? WHERE id=?",undef,$sent,now(),$id);
$back->("Sending “$subject” to $sent ".($sent==1 ? 'subscriber' : 'subscribers').'. It goes out over the next few minutes.');
}
$back->('Saved.',"&edit=$id#issue");
}
if ($action eq 'issue_delete') {
$edit or die "That issue no longer exists.\n";
$n->do('DELETE FROM issues WHERE id=?',undef,$edit->{id});
$back->('Deleted.');
}
if ($action eq 'subscriber_remove') {
my $k=$n->do("UPDATE subscribers SET status='left',left_at=? WHERE id=? AND status<>'left'",undef,now(),param('id',32));
die "That address was already removed.\n" unless $k>0;
$back->('Removed. Nothing more will be sent to that address.','#subscribers');
}
if ($action eq 'subscriber_add') {
my $email=lc param('email',254);
die "That isn’t an email address.\n" unless mail_address_ok($email);
die "Tick “They asked to get it” to add someone yourself.\n" unless param('asked',1) eq '1';
my $s=$n->selectrow_hashref('SELECT * FROM subscribers WHERE email=?',undef,$email);
die "$email is already subscribed.\n" if $s && $s->{status} eq 'active';
if ($s) {$n->do("UPDATE subscribers SET status='active',confirmed_at=?,left_at=NULL,source='added' WHERE id=?",undef,now(),$s->{id})}
else {$n->do("INSERT INTO subscribers (id,email,status,token,created_at,confirmed_at,source) VALUES (?,?,'active',?,?,?,'added')",undef,random_id(),$email,random_id(),now(),now())}
$back->("Added $email.",'#subscribers');
}
if ($action eq 'settings_save') {
my $stream=param('stream',40);
die "Message stream: letters, numbers and dashes, such as broadcast.\n" unless $stream =~ /\A[a-z0-9-]{1,40}\z/;
conf_save(from_name=>param('from_name',80),footer=>param('footer',300),stream=>$stream);
$back->('Settings saved.','#settings');
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
my %count=map {@$_} @{$n->selectall_arrayref('SELECT status,count(*) FROM subscribers GROUP BY status')};
my $active=$count{active}//0;
admin_page('Newsletter',section=>'x-newsletter-service',notice=>$message,
intro=>"$active ".($active==1 ? 'subscriber' : 'subscribers').(($count{pending}//0) ? ", and $count{pending} still to confirm" : '').'. Put a <strong>Newsletter sign-up</strong> block on any page for visitors to subscribe.');
# Writing and sending an issue.
my $i=$edit // {subject=>'',body=>'',status=>'draft'};
my $f='<form method="post" action="/admin/x/newsletter/" class="admin-form" id="issue">'.fields('issue_save','x-newsletter',$edit ? $edit->{id} : '')
.'<label>Subject<input name="subject" value="'.h($i->{subject}).'" maxlength="200" required></label>'
.'<label>The issue<textarea name="body" rows="14" maxlength="50000" required data-markdown>'.h($i->{body}).'</textarea><span class="optional">Markdown: ## headings, **bold**, lists, [links](https://…). Your name, the site’s address and an unsubscribe link are added at the end.</span></label>'
.'<p class="inline-form"><button class="buttonlike" type="submit">save draft</button> <button class="buttonlike" type="submit" name="do" value="test">send a test to me</button></p>'
.'<div class="box-part"><h3>Send it</h3><label class="checkbox-label"><input type="checkbox" name="sure" value="1">Yes, send it now to '.$active.' '.($active==1 ? 'subscriber' : 'subscribers').'</label>'
.'<button class="buttonlike is-primary" type="submit" name="do" value="send"'.($active ? '' : ' disabled').'>send to subscribers</button></div></form>';
$f.='<form method="post" action="/admin/x/newsletter/" class="delete-form" data-confirm="Delete this draft?">'.fields('issue_delete','x-newsletter',$edit->{id}).'<button class="buttonlike danger">delete this draft</button></form>' if $edit;
$f.=BlowfishCMS::markdown_help_html(note=>'In the email, boxes, columns, buttons and fold-outs show without the site’s styles.');
window($edit ? 'issue: '.$edit->{subject} : 'write an issue',$f);
my $issues=$n->selectall_arrayref('SELECT * FROM issues ORDER BY coalesce(sent_at,updated_at) DESC LIMIT 100',{Slice=>{}});
window('issues',@$issues ? '<table class="seo-table"><thead><tr><th>Subject</th><th>Status</th><th></th></tr></thead><tbody>'.join('',map {
'<tr><td>'.h($_->{subject}).'</td><td>'.($_->{status} eq 'sent' ? 'sent '.h(substr($_->{sent_at},0,10)).' to '.$_->{recipients} : 'draft').'</td><td>'.($_->{status} eq 'draft' ? '<a href="/admin/x/newsletter/?edit='.h($_->{id}).'#issue">edit</a>' : '').'</td></tr>'} @$issues).'</tbody></table>'
: '<p class="empty-media">No issues yet.</p>');
# Subscribers.
my $subs=$n->selectall_arrayref("SELECT * FROM subscribers WHERE status IN ('active','pending') ORDER BY status, coalesce(confirmed_at,created_at) DESC LIMIT 500",{Slice=>{}});
my $s='<div id="subscribers">'.(@$subs ? '<table class="seo-table"><thead><tr><th>Address</th><th>Since</th><th></th></tr></thead><tbody>'.join('',map {
'<tr><td>'.h($_->{email}).($_->{status} eq 'pending' ? ' <span class="media-label">not confirmed yet</span>' : '').'</td><td>'.h(substr($_->{confirmed_at}//$_->{created_at},0,10)).'</td><td><form method="post" action="/admin/x/newsletter/" class="delete-form" data-confirm="'.h("Remove $_->{email}? Nothing more will be sent to it.").'">'.fields('subscriber_remove','x-newsletter',$_->{id}).'<button class="text-button danger">remove</button></form></td></tr>'} @$subs).'</tbody></table>'
: '<p class="empty-media">No subscribers yet.</p>')
.'<p><a class="buttonlike" href="/admin/x/newsletter/subscribers.csv">download the list (CSV)</a></p>'
.'<form method="post" action="/admin/x/newsletter/" class="admin-form">'.fields('subscriber_add','x-newsletter').'<div class="theme-editor__grid"><label>Add an address<input type="email" name="email" maxlength="254" required></label></div>'
.'<label class="checkbox-label"><input type="checkbox" name="asked" value="1" required>They asked to get it (only add people who did)</label><button class="buttonlike" type="submit">add</button></form></div>';
window('subscribers',$s);
window('settings','<form method="post" action="/admin/x/newsletter/" class="admin-form" id="settings">'.fields('settings_save','x-newsletter')
.'<div class="theme-editor__grid"><label>From<input name="from_name" value="'.h(conf('from_name','')).'" maxlength="80" placeholder="'.h(setting('site_title')).'"><span class="optional">The name issues come from (the site’s address is the sender).</span></label>'
.'<label>Postmark message stream<input name="stream" value="'.h(conf('stream','broadcast')).'" maxlength="40"><span class="optional">The ID of a <em>Broadcast</em> stream in Postmark (newsletters mustn’t use the transactional one).</span></label></div>'
.'<label>Footer<input name="footer" value="'.h(conf('footer','')).'" maxlength="300"><span class="optional">Optional, at the end of every issue, such as a postal address.</span></label>'
.'<button class="buttonlike" type="submit">save</button></form>'
.'<p class="media-label">In Postmark: your server → <strong>Message streams</strong> → <strong>Create message stream</strong> → <em>Broadcasts</em>, with the ID <code>broadcast</code>. Confirmation emails go on the usual stream.</p>');
end_page();
return 1;
}
1;