repository

BlowfishCMS

A small content management system for OpenBSD

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

245 lines · 18.7 KB · download this file

package BlowfishCMS::Addon::Forms;
# Forms: forms the owner builds (the questions they choose), placed on any
# page with a block; answers are kept and emailed to the owner.
#
# Where each part runs:
#   admin service   the Forms screen (/admin/?kind=x-forms): the forms and
#                   their questions, in the catalogue (forms_forms).
#   public service  the Form block on pages.
#   forms service   (its own account, _bfxforms) /x/forms/send, which checks
#                   and keeps answers in its own database and queues the
#                   email, and the Answers screen (/admin/x/forms/) with its
#                   CSV download. Only it can read the answers.
#
# A form's questions (forms_forms.fields, JSON): [{id, label, type, options,
# required}], type one of text, long, email, number, date, choice, choices,
# check. Answers keep each question's label as it was when answered.
use v5.36;
use utf8;
use Encode qw(encode);
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 fetch_request json_response switch_field admin_row admin_list row_menu move_buttons) }

sub db { $BlowfishCMS::db }
# The questions themselves (their kinds, fields, editor and checks) are the
# core's Questions.pm since 1.1.0, shared with the Services add-on.
sub migrate ($db) {
    $db->do("CREATE TABLE IF NOT EXISTS forms_forms (id TEXT PRIMARY KEY, title TEXT NOT NULL, intro TEXT NOT NULL DEFAULT '', fields TEXT NOT NULL DEFAULT '[]', button TEXT NOT NULL DEFAULT 'Send', thanks TEXT NOT NULL DEFAULT '', notify INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)");
}
sub all_forms { return (attempt {db()->selectall_arrayref('SELECT * FROM forms_forms ORDER BY title',{Slice=>{}})}) // [] }
sub form ($id) {
    return undef unless ($id//'') =~ /\A[a-f0-9]{16}\z/;
    my $f=(attempt {db()->selectrow_hashref('SELECT * FROM forms_forms WHERE id=?',undef,$id)}) or return undef;
    $f->{questions}=(attempt {JSON::PP->new->decode($f->{fields})}) // [];
    $f->{questions}=[] unless ref $f->{questions} eq 'ARRAY';
    return $f;
}
sub options_of ($q) { return BlowfishCMS::question_options($q) }

# ---- The block ----------------------------------------------------------------------
sub blocks {
    my @choices=(map {[$_->{id},$_->{title}]} @{all_forms()});
    @choices=(['','(make a form on the Forms tab first)']) unless @choices;
    return {forms_form=>{label=>'Form',order=>46,group=>'content',about=>'One of your forms from the Forms add-on.',
        fields=>[[title=>'Panel title','text',120],[subtitle=>'Panel subtitle','text',160,'optional'],[form=>'Form','select',\@choices]],
        defaults=>{title=>'form'},manage=>['x-forms','manage forms'],render=>\&render_block}};
}
sub render_block ($b,%o) {
    my $d=$b->{data};my $f=form($d->{form});
    my $html;
    if (!$f) {$html='<p class="empty-media">This form isn’t available.</p>'}
    elsif (($BlowfishCMS::q->param('form_sent')//'') eq $f->{id}) {
        $html='<div class="forms-thanks" role="status">'.(length $f->{thanks} ? render_markdown($f->{thanks}) : '<p>Thank you. Your answers were sent.</p>').'</div>';
    }
    else {
        my $back=($BlowfishCMS::route//'/') =~ m{\A/[a-z0-9/-]*\z} ? $BlowfishCMS::route : '/';
        $html=(length $f->{intro} ? '<div class="forms-intro">'.render_markdown($f->{intro}).'</div>' : '')
            .'<form class="forms-form" id="form-'.h($f->{id}).'" method="post" action="/x/forms/send">'
            .'<input type="hidden" name="form" value="'.h($f->{id}).'"><input type="hidden" name="back" value="'.h($back).'"><input type="hidden" name="t" value="'.time().'">'
            .'<label class="forms-trap" aria-hidden="true">Leave this empty<input name="website" tabindex="-1" autocomplete="off"></label>'
            .join('',map {BlowfishCMS::question_html($_,id=>"form-$f->{id}")} @{$f->{questions}})
            .'<p><button class="buttonlike" type="submit">'.h(length $f->{button} ? $f->{button} : 'Send').'</button></p></form>';
    }
    return window_html($d->{title},$d->{subtitle},$html,%o);
}

# ---- The Forms screen (admin service) ---------------------------------------------------------
sub admin {
    my $message=param('notice',2000);my $f=form(param('edit',16) || param('id',16));
    my $back=sub ($n,$id='') {redirect('/admin/?kind=x-forms&notice='.CGI::escape(encode('UTF-8',$n)).(length $id ? "&edit=$id" : ''))};
    if ($BlowfishCMS::method eq 'POST') {
        my $fetch=fetch_request();
        attempt {
            my $action=param('action',30);
            if ($action eq 'form_new') {
                my $title=param('title',120);die "Give the form a name.\n" unless length $title;
                my $id=substr(random_id(),0,16);
                my $start=[{id=>'q1',label=>'Name',type=>'text',required=>1,options=>''},{id=>'q2',label=>'Email',type=>'email',required=>1,options=>''},{id=>'q3',label=>'Message',type=>'long',required=>0,options=>''}];
                db()->do('INSERT INTO forms_forms (id,title,fields,button,thanks,notify,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)',undef,$id,$title,JSON::PP->new->canonical->encode($start),'Send','Thank you. Your answers were sent.',1,now(),now());
                $back->("Made $title. Change its questions below.",$id);
            }
            if ($action eq 'form_save') {
                $f or die "That form no longer exists.\n";
                my %v=(title=>param('title',120),intro=>param('intro',3000),button=>param('button',40),thanks=>param('thanks',3000),notify=>param('notify',1) eq '1' ? 1 : 0);
                s/\r\n?/\n/g for $v{intro},$v{thanks};
                die "Give the form a name.\n" unless length $v{title};
                die "Give the button some text.\n" unless length $v{button};
                # A question keeps its id while its words stay the same, so answers line up.
                my @qs=@{BlowfishCMS::questions_from_form($f->{id},$f->{questions},max=>40)};
                die "Ask at least one question.\n" unless @qs;
                db()->do('UPDATE forms_forms SET title=?,intro=?,fields=?,button=?,thanks=?,notify=?,updated_at=? WHERE id=?',undef,$v{title},$v{intro},JSON::PP->new->canonical->encode(\@qs),$v{button},$v{thanks},$v{notify},now(),$f->{id});
                json_response({ok=>JSON::PP::true,message=>'Saved.'}) if $fetch;
                $back->("Saved $v{title}.",$f->{id});
            }
            if ($action eq 'form_delete') {
                $f or die "That form no longer exists.\n";
                db()->do('DELETE FROM forms_forms WHERE id=?',undef,$f->{id});
                $back->("Deleted $f->{title}. Its answers stay on the Answers screen.");
            }
            die "Choose an action.\n";
        } or do {$message=failed_action($@);json_response({ok=>JSON::PP::false,message=>$message},400) if $fetch};
    }
    if ($f) {
        admin_page('Forms',section=>'x-forms',notice=>$message,save=>['save','All changes saved'],
            intro=>'<a href="/admin/?kind=x-forms">All forms</a> · Put it on a page with a <strong>Form</strong> block. Answers arrive on the Answers screen'.($f->{notify} ? ', and by email' : '').'.');
        print '<form id="bulk-edit" method="post" action="/admin/" class="admin-form">'.fields('form_save','x-forms',$f->{id}).'</form>';
        my $in=sub ($n,$l,$v,$max,$hint='') {'<label>'.h($l).'<input name="'.$n.'" value="'.h($v).'" maxlength="'.$max.'" form="bulk-edit">'.($hint ? '<span class="optional">'.h($hint).'</span>' : '').'</label>'};
        window('the form','<div class="admin-form block-card__fields">'.$in->('title','Name',$f->{title},120,'for you; also the subject of the emails')
            .'<label class="block-wide">Introduction<textarea name="intro" rows="3" maxlength="3000" form="bulk-edit" data-markdown>'.h($f->{intro}).'</textarea><span class="optional">Optional, shown above the questions (Markdown).</span></label></div>');
        window('questions','<div class="admin-form block-card__fields">'.BlowfishCMS::questions_editor_html($f->{id},$f->{questions}).'</div>');
        window('after sending','<div class="admin-form block-card__fields">'.$in->('button','Button',$f->{button},40)
            .'<label class="block-wide">Thank-you message<textarea name="thanks" rows="2" maxlength="3000" form="bulk-edit" data-markdown>'.h($f->{thanks}).'</textarea><span class="optional">Shown in place of the form once it’s sent (Markdown).</span></label>'
            .switch_field('notify','Email me each set of answers',$f->{notify},form=>'bulk-edit')
            .'<p class="media-label">Emails go through the site’s Postmark connection (Settings → Mail), to the update alerts address or else where contact messages go. When the form asks for an email address, replying answers the sender.</p></div>'.BlowfishCMS::markdown_help_html());
        window('delete','<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete the $f->{title} form? Its answers stay on the Answers screen.").'">'.fields('form_delete','x-forms',$f->{id}).'<button class="buttonlike danger">delete this form</button></form>');
        end_page();return 1;
    }
    admin_page('Forms',section=>'x-forms',notice=>$message,intro=>'Forms with your own questions: put one on any page with a <strong>Form</strong> block. Answers are on the Answers screen.');
    my $list=all_forms();
    window('forms',admin_list([map {my $f=$_;my $q=(attempt {JSON::PP->new->decode($f->{fields})}) // [];
        admin_row(title=>$f->{title},meta=>[scalar(@$q).' '.(@$q==1 ? 'question' : 'questions'),($f->{notify} ? 'answers emailed' : ())],
            actions=>'<a class="buttonlike" href="/admin/?kind=x-forms&amp;edit='.h($f->{id}).'">edit</a>',
            menu=>'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete the $f->{title} form? Its answers stay on the Answers screen.").'">'.fields('form_delete','x-forms',$f->{id}).'<button class="text-button danger">delete</button></form>')} @$list],
        empty=>'No forms yet. Add the first one below.'));
    window('new form','<form method="post" action="/admin/" class="admin-form inline-form">'.fields('form_new','x-forms').'<label>Name<input name="title" maxlength="120" required placeholder="Workshop sign-up"></label><button class="buttonlike is-primary" type="submit">add form</button></form><p class="media-label">It starts with a name, an email address and a message; change them as you like.</p>');
    end_page();
    return 1;
}

# ---- Answers (the forms service) ------------------------------------------------------------
sub answers_db {
    state %open;my $file=BlowfishCMS::addon_data_dir('forms').'/answers.sqlite';
    return $open{$file} if $open{$file} && $open{$file}->ping;
    my $a=DBI->connect("dbi:SQLite:dbname=$file",'','',{RaiseError=>1,PrintError=>0,AutoCommit=>1,sqlite_unicode=>1});
    $a->do('PRAGMA busy_timeout=5000');
    $a->do("CREATE TABLE IF NOT EXISTS answers (id TEXT PRIMARY KEY, form TEXT NOT NULL, form_title TEXT NOT NULL, answers TEXT NOT NULL, email TEXT NOT NULL DEFAULT '', visitor TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL)");
    $a->do('CREATE INDEX IF NOT EXISTS answers_form ON answers(form,created_at)');
    return $open{$file}=$a;
}
sub message_page ($title,$text,$status=200) {
    start_page($title,'/x/forms/',$status,{noindex=>1});
    BlowfishCMS::window(lc $title,'<h1>'.h($title).'</h1>'.$text);
    BlowfishCMS::end_page();
}
sub send_answers {
    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 $fail=sub ($text,$status=400) {message_page('Not sent','<p>'.h($text).'</p><p><a href="javascript:history.back()">Go back</a> and try again; what you typed is still there.</p>',$status);BlowfishCMS::finish()};
    my $f=form(param('form',16)) or $fail->('That form isn’t available any more.',404);
    my $back=param('back',200);$back='/' unless $back =~ m{\A/[a-z0-9/-]*\z};
    my $done=sub {redirect("$back?form_sent=$f->{id}#form-$f->{id}")};
    # Robots: the hidden field filled in, or sent faster than a person could.
    my $t=param('t',12);
    $done->() if length(param('website',200)) || ($t =~ /\A\d+\z/ && time-$t<2);
    my $visitor=sha256_hex(($ENV{REMOTE_ADDR}//'').'|'.int(time/3600).'|forms');
    my $a=answers_db();
    my $since=BlowfishCMS::strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-3600));
    $fail->('Too many forms sent from here in the last hour. Try again later.',429) if $a->selectrow_array('SELECT count(*) FROM answers WHERE visitor=? AND created_at>?',undef,$visitor,$since)>=10;
    # The answers, checked by the core (Questions.pm).
    my ($answers,$problem,$email)=BlowfishCMS::question_answers($f->{questions});
    $fail->($problem) if length $problem;
    my @got=@$answers;
    $fail->('Answer at least one question.') unless grep {length $_->{value}} @got;
    my $id=random_id();
    $a->do('INSERT INTO answers (id,form,form_title,answers,email,visitor,created_at) VALUES (?,?,?,?,?,?,?)',undef,$id,$f->{id},$f->{title},JSON::PP->new->canonical->encode(\@got),$email//'',$visitor,now());
    if ($f->{notify}) {
        my $text="New answers to $f->{title}:\n\n".join('',map {"$_->{label}:\n".(length $_->{value} ? $_->{value} =~ s/^/  /gmr : '  (no answer)')."\n\n"} @got)
            ."All answers: ".site_url()."/admin/x/forms/?form=$f->{id}\n";
        attempt {mail_queue('forms',to=>'owner',subject=>"$f->{title}: new answers",text=>$text,tag=>'forms',(defined $email ? (reply_to=>$email) : ()))};
    }
    $done->();
}
sub route ($rest) {
    if ($rest eq 'send') {send_answers();return 1}
    return 0;
}
sub robots { return ['/x/forms/'] }

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 $a=answers_db();
    my $fid=param('form',16);$fid='' unless $fid =~ /\A[a-f0-9]{16}\z/;
    if ($rest eq 'answers.csv' && length $fid) {
        my $rows=$a->selectall_arrayref('SELECT * FROM answers WHERE form=? ORDER BY created_at',{Slice=>{}},$fid);
        my $f=form($fid);
        # Columns: the form's questions now, then any only older answers had.
        my (@cols,%seen);
        push @cols,[$_->{id},$_->{label}] for $f ? @{$f->{questions}} : ();
        $seen{$_->[0]}=1 for @cols;
        for my $r (@$rows) {for (@{JSON::PP->new->decode($r->{answers})}) {push @cols,[$_->{id},$_->{label}] unless $seen{$_->{id}}++}}
        my $out=join(',',map {csv_cell($_)} 'Sent',map {$_->[1]} @cols)."\r\n";
        for my $r (@$rows) {
            my %v=map {($_->{id}=>$_->{value})} @{JSON::PP->new->decode($r->{answers})};
            $out.=join(',',map {csv_cell($_)} ($r->{created_at} =~ s/T/ /r =~ s/Z\z/ UTC/r),map {$v{$_->[0]}} @cols)."\r\n";
        }
        my $name=lc(($f ? $f->{title} : $rows->[0]{form_title}//'answers') =~ s/[^A-Za-z0-9]+/-/gr =~ s/\A-|-\z//gr) || 'answers';
        header(200,'text/csv; charset=utf-8',"Content-Disposition: attachment; filename=\"$name.csv\"\r\n");
        print "\x{FEFF}$out";
        return 1;
    }
    return 0 unless $rest eq '';
    my $message=param('notice',2000);
    if ($BlowfishCMS::method eq 'POST') {
        attempt {
            my $action=param('action',30);
            if ($action eq 'answer_delete') {
                my $n=$a->do('DELETE FROM answers WHERE id=?',undef,param('id',32));
                die "Those answers were already deleted.\n" unless $n>0;
                redirect("/admin/x/forms/?form=$fid&notice=Deleted.");
            }
            if ($action eq 'answers_delete') {
                $a->do('DELETE FROM answers WHERE form=?',undef,$fid);
                redirect('/admin/x/forms/?notice='.CGI::escape('Deleted all its answers.'));
            }
            die "Choose an action.\n";
        } or $message=failed_action($@);
    }
    my $css='<link rel="stylesheet" href="/addons/forms/forms.css?v=1">';
    my %count=map {($_->[0]=>[$_->[1],$_->[2],$_->[3]])} @{$a->selectall_arrayref('SELECT form,count(*),max(created_at),max(form_title) FROM answers GROUP BY form')};
    my %forms=map {($_->{id}=>$_)} @{all_forms()};
    if (length $fid) {
        my $f=$forms{$fid};my $title=$f ? $f->{title} : ($count{$fid}//[])->[2] // 'Answers';
        admin_page('Answers',section=>'x-forms-service',notice=>$message,intro=>'<a href="/admin/x/forms/">All forms</a> · Answers to '.h($title).', newest first.',
            actions=>'<a class="buttonlike" href="/admin/x/forms/answers.csv?form='.h($fid).'">download (CSV)</a>');
        print $css;
        my $rows=$a->selectall_arrayref('SELECT * FROM answers WHERE form=? ORDER BY created_at DESC LIMIT 500',{Slice=>{}},$fid);
        window(lc($title).' · '.scalar(@$rows),@$rows ? join('',map {my $r=$_;
            '<article class="forms-answer" id="answer-'.h($r->{id}).'"><p class="media-label">'.h($r->{created_at} =~ s/T/ /r =~ s/:\d\dZ\z/ UTC/r).'</p><dl>'
            .join('',map {'<dt>'.h($_->{label}).'</dt><dd>'.(length $_->{value} ? h($_->{value}) =~ s/\n/<br>/gr : '<span class="media-label">no answer</span>').'</dd>'} @{JSON::PP->new->decode($r->{answers})}).'</dl>'
            .'<form method="post" action="/admin/x/forms/" class="delete-form" data-confirm="Delete these answers?">'.fields('answer_delete','x-forms',$r->{id}).hidden(form=>$fid).'<button class="text-button danger">delete</button></form></article>'} @$rows) : '<p class="empty-media">No answers yet.</p>');
        window('delete them all','<form method="post" action="/admin/x/forms/" class="delete-form" data-confirm="'.h("Delete every answer to $title? This can’t be undone.").'">'.fields('answers_delete','x-forms').hidden(form=>$fid).'<button class="buttonlike danger">delete all its answers</button></form>') if @$rows;
        end_page();return 1;
    }
    admin_page('Answers',section=>'x-forms-service',notice=>$message,intro=>'What visitors sent with your forms. They’re kept here, on your server, until you delete them.');
    my @ids=sort {($count{$b}//[0,''])->[1] cmp ($count{$a}//[0,''])->[1] || ($forms{$a}{title}//'') cmp ($forms{$b}{title}//'')} keys %{{map {($_=>1)} keys %forms,keys %count}};
    window('forms',admin_list([map {my $c=$count{$_}//[0,''];my $t=$forms{$_} ? $forms{$_}{title} : ($c->[2]//'').' (form deleted)';
        admin_row(title=>$t,meta=>[$c->[0].' '.($c->[0]==1 ? 'set of answers' : 'sets of answers').($c->[1] ? ', the latest '.h(substr($c->[1],0,10)) : '')],
            actions=>'<a class="buttonlike" href="/admin/x/forms/?form='.h($_).'">answers</a>')} @ids],
        empty=>'No forms yet. Make one on the Forms screen.'));
    end_page();
    return 1;
}

1;