repository

BlowfishCMS

A small content management system for OpenBSD

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

161 lines · 11.8 KB · download this file

package BlowfishCMS;
# Setting up a new site: a short walkthrough an owner sees after the first
# sign-in (the site name, which starter pages are on, the theme, search
# engines, mail and add-ons), then a to-do list on the Overview until the
# usual finishing touches are done. Sites that were already running when this
# came in are marked as set up. It can be run again from Settings.
use v5.36;
use utf8;
use Encode qw(encode);
our ($base,$data,$db,$q,$method,$csrf,$cookie_header,%instance);

# The walkthrough's steps, in order, with their titles.
sub setup_steps {
    return ([basics=>'Your site'],[pages=>'Pages'],[look=>'Look'],[search=>'Search engines'],[mail=>'Mail'],[addons=>'Add-ons'],[done=>'Done']);
}
# A brand-new catalogue needs setting up; one that already had content doesn't.
# Called by migrate: a brand-new catalogue is marked as needing the
# walkthrough and gets a plain copyright footer; any other keeps its own.
sub ensure_setup_state ($fresh) {
    $db->do("INSERT OR IGNORE INTO site_settings(key,value) VALUES ('setup',?)",undef,$fresh ? 'new' : 'done');
    # New sites start with a plain copyright line; running sites keep the footer they have.
    $db->do("INSERT OR IGNORE INTO site_settings(key,value) VALUES ('footer_text',?)",undef,'© {year} · {site}') if $fresh;
}
# Whether the walkthrough still has to be done.
sub setup_needed { return setting('setup') eq 'new' ? 1 : 0 }
# Where an owner lands after signing in.
# Where to go after signing in: an owner of a site that isn't set up yet goes
# to the walkthrough, everyone else where they were going.
sub after_sign_in ($next,$user) {
    my $row=$next eq '/admin/' && setup_needed() ? admin_user_row($user) : undef;
    return $row && $row->{role} eq 'owner' ? '/admin/?kind=setup' : $next;
}

# A step's address.
sub setup_step_url ($step) { return '/admin/?kind=setup&step='.$step }
# The step after a step.
sub setup_next ($step) {
    my @s=map {$_->[0]} setup_steps();my ($i)=grep {$s[$_] eq $step} 0..$#s;
    return $s[($i//0)+1] // 'done';
}
# The walkthrough (/admin/?kind=setup&step=...): saves the step's form
# (the site's name and description, which pages are on, the default theme,
# search engine choices), or skips it, then goes to the next step. "Done"
# marks the site as set up. setup_restart (from Settings) starts again;
# setup_todo_hide hides the Overview's list. Each step's form is built by
# $form; skip bypasses the browser's checks of required fields
# (formnovalidate).
sub setup_admin {
    my @steps=setup_steps();my %titles=map {@$_} @steps;
    my $step=param('step',20);$step='basics' unless $titles{$step};
    my $message='';
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',30);
            if ($action eq 'setup_basics') {
                my %v;
                for my $f (grep {$_->[0] =~ /\A(?:site_title|author|description)\z/} settings_fields()) {
                    my $value=param($f->[0],$f->[2]);$value =~ s/\A\s+|\s+\z//g;$v{$f->[0]}=$value;
                }
                die "Give the site a name.\n" unless length $v{site_title};
                setting_save(%v);
            }
            elsif ($action eq 'setup_pages') {
                my %on=map {$_=>1} $q->multi_param('on');
                save_nav(map {+{%$_,visible=>($_->{page} eq 'home' || $on{$_->{page}}) ? 1 : 0}} nav_items());
            }
            elsif ($action eq 'setup_look') {
                my $t=theme_by_slug(param('theme',24));
                die "Choose one of the themes.\n" unless $t && $t->{enabled};
                setting_save(default_theme=>$t->{slug});
            }
            elsif ($action eq 'setup_search') {
                my $type=param('entity_type',20);
                die "Choose a person or an organisation.\n" unless $type =~ /\A(?:person|organization)\z/;
                setting_save(search_visible=>(param('search_visible',1) eq '1' ? '1' : '0'),entity_type=>$type);
            }
            elsif ($action eq 'setup_finish') {
                setting_save(setup=>'done');
                redirect('/admin/?notice='.CGI::escape('Your site is set up. The list below has a few finishing touches.'));
            }
            elsif ($action eq 'setup_todo_hide') {setting_save(setup_todo=>'hidden');redirect('/admin/?notice='.CGI::escape('The finishing touches are hidden.'))}
            elsif ($action eq 'setup_restart') {setting_save(setup=>'new',setup_todo=>'');redirect(setup_step_url('basics'))}
            elsif ($action ne 'setup_skip') {die "Choose an action.\n"}
            redirect(setup_step_url(setup_next(param('step',20))));
        } or $message=failed_action($@);
    }
    my ($index)=grep {$steps[$_][0] eq $step} 0..$#steps;
    admin_page('Set up your site',section=>'overview',notice=>$message,
        intro=>'A few questions to get the site ready. Everything here can be changed later; skip anything you’re not ready for.');
    print '<ol class="setup-steps">'.join('',map {my $i=$_;'<li class="'.($i<$index ? 'is-done' : $i==$index ? 'is-current' : '').'"><a href="'.h(setup_step_url($steps[$i][0])).'"'.($i==$index ? ' aria-current="step"' : '').'>'.h($steps[$i][1]).'</a></li>'} 0..$#steps).'</ol>';
    my $form=sub ($action,$body,$button='continue') {
        return '<form method="post" action="/admin/" class="admin-form setup-form">'.hidden(csrf=>$csrf,kind=>'setup',action=>$action,step=>$step).$body
            .'<div class="setup-form__actions"><button class="buttonlike is-primary" type="submit">'.h($button).'</button>'
            .($step ne 'done' ? '<button class="text-button" type="submit" name="action" value="setup_skip" formnovalidate>skip</button>' : '').'</div></form>';
    };
    if ($step eq 'basics') {
        my %f=map {($_->[0]=>$_)} settings_fields();
        my $field=sub ($key,$type='text') {
            my $x=$f{$key};my $v=setting($key);
            return '<label>'.h($x->[1]).($type eq 'area' ? '<textarea name="'.$key.'" maxlength="'.$x->[2].'" rows="3">'.h($v).'</textarea>' : '<input name="'.$key.'" type="'.$type.'" maxlength="'.$x->[2].'" value="'.h($v).'"'.($key eq 'site_title' ? ' required' : '').'>').'<span class="optional">'.h($x->[4]).'</span></label>';
        };
        window('your site',$form->('setup_basics',$field->('site_title').$field->('author').$field->('description','area')));
    }
    elsif ($step eq 'pages') {
        my $reg=page_registry();
        my $list=join '',map {my $p=$reg->{$_->{page}};$p ? '<label class="checkline"><input type="checkbox" name="on" value="'.h($_->{page}).'"'.($_->{visible} || $_->{page} eq 'home' ? ' checked' : '').($_->{page} eq 'home' ? ' disabled' : '').'> '.h($p->{title}).' <span class="media-label">'.h($p->{path}).'</span></label>' : ''} nav_items();
        window('pages',$form->('setup_pages','<p>Choose the pages visitors can open. Pages you leave off stay in the admin, ready to edit, and answer “not found” until you turn them on in Pages.</p><div class="setup-checks">'.$list.'</div>'));
    }
    elsif ($step eq 'look') {
        my $default=default_theme();
        my $list=join '',map {'<label class="checkline"><input type="radio" name="theme" value="'.h($_->{slug}).'"'.($_->{slug} eq $default ? ' checked' : '').' required> '.h($_->{name}).' <span class="media-label">'.h($_->{scheme}).'</span></label>'} grep {$_->{enabled}} @{all_themes()};
        window('look',$form->('setup_look','<p>The theme new visitors see. Its colours and fonts, and your logo and favicon, are under Look.</p><div class="setup-checks">'.$list.'</div>'));
    }
    elsif ($step eq 'search') {
        my $visible=setting('search_visible') ne '0';my $org=setting('entity_type') eq 'organization';
        window('search engines',$form->('setup_search','<p>Whether search engines may list the site, and who it belongs to, for the summary they show.</p><div class="setup-checks">'
            .'<label class="checkline"><input type="radio" name="search_visible" value="1"'.($visible ? ' checked' : '').'> Let search engines list the site</label>'
            .'<label class="checkline"><input type="radio" name="search_visible" value="0"'.($visible ? '' : ' checked').'> Not yet: ask them to stay away</label></div>'
            .'<label>This site belongs to<select name="entity_type"><option value="person"'.($org ? '' : ' selected').'>a person</option><option value="organization"'.($org ? ' selected' : '').'>an organisation</option></select></label>'
            .'<p class="optional">Verification for Google and Bing is in <a href="/admin/?kind=search">Search &amp; sharing</a>, and the picture shown when a link is shared under <a href="/admin/?kind=branding#share">Look</a>.</p>'));
    }
    elsif ($step eq 'mail') {
        window('mail','<p>The contact form sends its messages through <a href="https://postmarkapp.com/" rel="noopener">Postmark</a>. To turn it on, open <strong>Mail</strong>, paste your Postmark server token there, and send yourself a test message. The token is kept where only the mail service can read it.</p>'
            .'<p><a class="buttonlike" href="/admin/mail/" target="_blank" rel="noopener">open Mail</a></p>'
            .$form->('setup_skip','','continue'));
    }
    elsif ($step eq 'addons') {
        my $all=addons_available();my %on=map {$_=>1} addons_enabled();
        my $list=join '',map {my $m=$all->{$_};'<li><strong>'.h($m->{title}//$m->{name}).'</strong>'.($on{$_} ? ' <span class="media-label">on</span>' : '').(length($m->{description}//'') ? ' · '.h($m->{description}) : '').'</li>'} grep {!$all->{$_}{problem}} sort keys %$all;
        window('add-ons','<p>Add-ons bring features that not every site needs, such as a shop. Turn them on in <a href="/admin/?kind=addons">Add-ons</a> whenever you like.</p>'
            .(length $list ? '<ul class="setup-addons">'.$list.'</ul>' : '<p class="empty-media">No add-ons are installed.</p>')
            .$form->('setup_skip','','continue'));
    }
    else {
        window('done',$form->('setup_finish','<p>That’s it. The Overview keeps a short list of finishing touches (a logo, a favicon, a share picture, a first backup) until they’re done. You can run this setup again from Settings.</p>','go to the Overview'));
    }
    end_page();
}
# The Overview's "finishing touches": what's still to do, each with a link.
# Only owners see it (every link is to an owners' screen).
sub setup_todo {
    my @todo;
    return () if setting('setup_todo') eq 'hidden' && !setup_needed();
    # Every item links to an owner's screen: editors don't get the list.
    return () unless is_owner();
    push @todo,['Finish setting up the site','/admin/?kind=setup'] if setup_needed();
    push @todo,['Describe the site for search engines and link previews','/admin/?kind=settings'] unless length setting('description');
    push @todo,['Add a logo (or keep the site name on its own)','/admin/?kind=branding#logo'] unless length setting('logo');
    push @todo,['Give the site its own favicon','/admin/?kind=branding#favicon'] unless length setting('favicon');
    push @todo,['Choose a share picture for links to the site','/admin/?kind=branding#share'] unless length setting('share_image');
    push @todo,['Turn on two-step sign-in for your account','/admin/?kind=account#two-step'] if is_owner() && session_mode() && users_table() && !mfa_enabled(signed_in_admin());
    if (is_owner() && system_ready()) {push @todo,['Make a first backup and keep a copy off the server','/admin/?kind=system'] unless @{system_backups()}}
    return @todo;
}
# The finishing touches as a panel, with "hide this list".
sub setup_todo_html {
    my @todo=setup_todo();return '' unless @todo;
    return window_html('finishing touches','','<ul class="setup-todo">'.join('',map {'<li><a href="'.h($_->[1]).'">'.h($_->[0]).'</a></li>'} @todo).'</ul>'
        .(setup_needed() || !is_owner() ? '' : '<form method="post" action="/admin/">'.hidden(csrf=>$csrf,kind=>'setup',action=>'setup_todo_hide').'<button class="text-button" type="submit">dismiss</button></form>'));
}
1;