repository

BlowfishCMS

A small content management system for OpenBSD

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

99 lines · 6.7 KB · download this file

package BlowfishCMS;
# Questions an owner writes for visitors to answer: the Forms add-on's forms
# and the Services add-on's booking forms. Moved into the core in 0.40.3 from
# the copies those add-ons kept, so both ask and check them the same way.
#
# A question is {id, label, type, options, required}: type is one of
# question_kinds (text, long, email, number, date, choice, choices, check);
# options are a list's choices, separated by commas. An answer is
# {id, label, value}: the label as it was asked, so old answers still read
# right after the question changes.
#
#   question_kinds, question_options     the kinds of answer; a list's choices
#   questions_editor_html(ID, QUESTIONS) the editor (a list field), in a form posting b.ID.questions.N.*
#   questions_from_form(ID, OLD, %o)     the editor's questions read back, ids kept while words stay
#   question_html(QUESTION, %o)          one question as form fields, named a.ID
#   question_posted(QUESTION)            what was posted for it, to fill the form in again
#   question_answers(QUESTIONS)          the answers posted, checked
use v5.36;
use utf8;
use Encode ();

my %kinds=(text=>'Short answer',long=>'Long answer',email=>'Email address',number=>'Number',date=>'Date',choice=>'One of a list',choices=>'Any of a list',check=>'A tick box');
my @kind_order=qw(text long email number date choice choices check);
sub question_kinds { return map {[$_=>$kinds{$_}]} @kind_order }
sub question_options ($q) { return grep {length} map {s/\A\s+|\s+\z//gr} split /,/,$q->{options}//'' }
# The editor's sub-fields for one question.
sub question_subs { return [[label=>'Question','text',200],[type=>'Kind of answer','select',[question_kinds()]],[options=>'Choices','text',1000,'for lists: separated by commas'],[required=>'Must be answered','check']] }
sub questions_editor_html ($id,$qs) {
    return field_html({id=>$id,data=>{questions=>[map {{%$_,required=>$_->{required} ? 1 : 0}} @$qs]}},['questions','Questions','items',question_subs()]);
}
# The editor's questions, checked: a list question needs its choices; a
# question keeps its id while its words stay the same (so answers line up),
# and new ones get the next free q1, q2…; empty ones are left out. %o: max
# (how many, 40 unless said).
sub questions_from_form ($id,$old,%o) {
    my $items=block_items_value({id=>$id},['questions','Questions','items',question_subs()]);
    my %was=map {($_->{label}=>$_->{id})} @$old;
    my ($n,@qs,%used)=(0);
    for my $q (grep {length($_->{label}//'')} @$items) {
        my $type=exists $kinds{$q->{type}//''} ? $q->{type} : 'text';
        die "“$q->{label}”: give the choices, separated by commas.\n" if ($type eq 'choice' || $type eq 'choices') && !question_options($q);
        my $qid=$was{$q->{label}} && !$used{$was{$q->{label}}} ? $was{$q->{label}} : do {my $k;do {$k='q'.(++$n)} while grep {$_->{id} eq $k} @$old,@qs;$k};
        $used{$qid}=1;
        push @qs,{id=>$qid,label=>$q->{label},type=>$type,required=>$q->{required} ? 1 : 0,options=>($type =~ /\Achoices?\z/ ? join(', ',question_options($q)) : '')};
    }
    my $max=$o{max}//40;
    die "Up to $max questions.\n" if @qs>$max;
    return \@qs;
}
# One question as form fields, named a.ID. %o: id (the start of its
# elements' ids, so two forms on a page don't clash), value (what to fill
# in: text, or a list of choices).
sub question_html ($q,%o) {
    my $name='a.'.$q->{id};my $id=($o{id}//'question').'-'.$q->{id};
    my $req=$q->{required} ? ' required' : '';
    my $label=h($q->{label}).($q->{required} ? '' : ' <span class="optional">(optional)</span>');
    my $t=$q->{type};my $now=ref $o{value} eq 'ARRAY' ? $o{value} : [$o{value}//''];
    return '<label class="question-option"><input type="checkbox" name="'.h($name).'" value="yes"'.(($now->[0]//'') eq 'yes' ? ' checked' : '').$req.'> '.$label.'</label>' if $t eq 'check';
    if ($t eq 'choice' || $t eq 'choices') {
        my $kind=$t eq 'choice' ? 'radio' : 'checkbox';my $n=0;my %on=map {($_=>1)} @$now;
        return '<fieldset class="question-choices"><legend>'.$label.'</legend>'.join('',map {'<label class="question-option"><input type="'.$kind.'" name="'.h($name).'" value="'.h($_).'"'.($on{$_} ? ' checked' : '').($t eq 'choice' && $q->{required} && !$n++ ? ' required' : '').'> '.h($_).'</label>'} question_options($q)).'</fieldset>';
    }
    return '<label for="'.h($id).'">'.$label.'<textarea id="'.h($id).'" name="'.h($name).'" rows="4" maxlength="5000"'.$req.'>'.h($now->[0]).'</textarea></label>' if $t eq 'long';
    my $type={email=>'email',date=>'date'}->{$t} // 'text';
    return '<label for="'.h($id).'">'.$label.'<input id="'.h($id).'" type="'.$type.'" name="'.h($name).'" value="'.h($now->[0]).'" maxlength="300"'.($t eq 'number' ? ' inputmode="decimal"' : '').($t eq 'email' ? ' autocomplete="email"' : '').$req.'></label>';
}
# Every value posted under one name, decoded (the choices of "any of a list").
sub posted_all ($name) { return map {Encode::decode('UTF-8',$_)} ($BlowfishCMS::q->can('multi_param') ? $BlowfishCMS::q->multi_param($name) : $BlowfishCMS::q->param($name)) }
# What was posted for one question, to fill a form in again after a
# mistake: a list for "any of a list", else the text.
sub question_posted ($q) { return $q->{type} eq 'choices' ? [posted_all('a.'.$q->{id})] : param('a.'.$q->{id},$q->{type} eq 'long' ? 5000 : 300) }
# The answers posted: (answers, problem, email). Each answer is {id, label,
# value}; problem is the first thing wrong, in words for the visitor, or '';
# email is the first email address answered (for a reply-to), or undef.
sub question_answers ($qs) {
    my (@got,$email);
    for my $q (@$qs) {
        my $name='a.'.$q->{id};my $v;
        if ($q->{type} eq 'choices') {
            my %ok=map {($_=>1)} question_options($q);
            $v=join ', ',grep {$ok{$_}} posted_all($name);
        }
        else {$v=param($name,$q->{type} eq 'long' ? 5000 : 300);$v =~ s/\r\n?/\n/g}
        $v//='';
        return (\@got,"“$q->{label}” needs an answer.",$email) if $q->{required} && !length $v;
        if (length $v) {
            return (\@got,"“$q->{label}”: that isn’t an email address.",$email) if $q->{type} eq 'email' && !mail_address_ok($v);
            return (\@got,"“$q->{label}”: enter a number.",$email) if $q->{type} eq 'number' && $v !~ /\A-?\d+(?:[.,]\d+)?\z/;
            return (\@got,"“$q->{label}”: enter a date.",$email) if $q->{type} eq 'date' && $v !~ /\A\d{4}-\d\d-\d\d\z/;
            return (\@got,"“$q->{label}”: choose one of the choices.",$email) if $q->{type} eq 'choice' && !grep {$_ eq $v} question_options($q);
            $v='yes' if $q->{type} eq 'check';
            $email //= $v if $q->{type} eq 'email';
        }
        push @got,{id=>$q->{id},label=>$q->{label},value=>$v};
    }
    return (\@got,'',$email);
}

1;