repository

BlowfishCMS

A small content management system for OpenBSD

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

609 lines · 38.4 KB · download this file

package BlowfishCMS;
# Add-ons: optional features that live in their own folder and plug into the
# site at a fixed set of places (see docs/ADDONS.md). A disabled add-on's code
# is never loaded.
#
#   addons/<name>/addon.json     what it is and what it adds (the manifest)
#   addons/<name>/lib/*.pm       its code: package BlowfishCMS::Addon::<Name>
#   addons/<name>/public/        CSS, JS and images, served at /addons/<name>/
#   addons/<name>/tests/         its own tests (optional)
#
# Add-ons are uploaded as .tar.gz archives into the site's list (the Add-ons
# screen, or blowfishctl addon add), then installed from it into
# /opt/blowfishcms-addons, which updates leave alone. A fresh install has none.
use v5.36;
use utf8;
use JSON::PP ();
use Encode qw(decode encode);
our ($base,$data,$root,$db,$q,$route,$method,$csrf,$admin,%instance);
our $VERSION;

# Where add-ons are found. Read when the code loads; the tests use a folder of
# their own.
my @addon_paths=grep {length} ($ENV{BLOWFISH_ADDONS_PATH} // '/opt/blowfishcms-addons');
# The folders add-ons are found in.
sub addon_paths { return @addon_paths }

# Compares two versions like 1.2.3 number by number: -1, 0 or 1. (Compared
# as text, "1.10.0" would come before "1.9.0".)
sub version_cmp ($a,$b) {
    my @a=split /\./,$a;my @b=split /\./,$b;
    for my $i (0..2) {my $c=($a[$i]//0) <=> ($b[$i]//0);return $c if $c}
    return 0;
}
# Checks a manifest; returns the problem, or '' when it's usable.
# Checks an add-on's addon.json: '' when it can be used, otherwise what's
# wrong, in words for the Add-ons screen. Its name must match its folder, it
# needs a label and a version, it must work with this BlowfishCMS, its code
# file must exist under lib/ and its package be BlowfishCMS::Addon::Name,
# its outside hosts and assets must be well-formed, "files" needs its own
# service, and request_max is 1-64 MB.
sub addon_manifest_problem ($m,$dir) {
    return 'addon.json must be a JSON object' unless ref $m eq 'HASH';
    my $name=$m->{name}//'';
    return 'name must be 2–20 lowercase letters and digits, starting with a letter' unless $name =~ /\A[a-z][a-z0-9]{1,19}\z/;
    return "the folder must be named $name" unless $dir =~ m{/\Q$name\E\z};
    return 'label is required' unless length($m->{label}//'');
    return 'version must look like 1.2.3' unless ($m->{version}//'') =~ /\A\d+\.\d+\.\d+\z/;
    my $needs=$m->{blowfishcms}//'';
    return 'blowfishcms must give the oldest BlowfishCMS version it works with, such as 1.0.0' unless $needs =~ /\A\d+\.\d+\.\d+\z/;
    return "needs BlowfishCMS $needs or newer (this is $VERSION)" if version_cmp($VERSION,$needs)<0;
    return 'module must be a .pm file under lib/' unless ($m->{module}//'') =~ m{\Alib/[A-Za-z0-9_/]+\.pm\z} && -f "$dir/$m->{module}";
    return 'package must be BlowfishCMS::Addon::<Name>' unless ($m->{package}//'') =~ /\ABlowfishCMS::Addon::[A-Z][A-Za-z0-9]*\z/;
    for my $host (@{$m->{network}//[]}) {return 'network must list host names' unless $host =~ /\A[a-z0-9.-]+\.[a-z]{2,}\z/}
    for my $asset (@{$m->{assets}{css}//[]},@{$m->{assets}{js}//[]}) {return 'assets must be files under public/' unless $asset =~ m{\A[a-z0-9_/-]+\.(?:css|js)\z} && -f "$dir/public/$asset"}
    return 'files needs "service": true (the folder belongs to its account)' if $m->{files} && !$m->{service};
    return 'request_max must be a number of MB from 1 to 64' if defined $m->{request_max} && ($m->{request_max} !~ /\A\d{1,2}\z/ || $m->{request_max}<1 || $m->{request_max}>64);
    return '';
}
# A folder of add-ons or themes as it stands: its entries and the times of the
# FILES in each, so a long-running worker sees one installed, updated or
# removed (by the request runner, as root) at its next request.
# A fingerprint of a folder of add-ons or themes: its entries and the times
# of the given files in each. When it changes, something was installed,
# updated or removed, and the folder is read again.
sub folder_stamp ($path,@files) {
    opendir(my $dh,$path) or return $path;
    my @entries=sort grep {!/\A\./} readdir $dh;closedir $dh;
    return join ',',$path,(stat $path)[9]//0,map {my $d="$path/$_";join ':',$_,map {(stat "$d/$_")[9]//0} @files} @entries;
}
our $addons_cache;   # this request's (cleared at the start of each); the folders are read again only when they change
my ($addons_kept,$addons_stamp)=(undef,'');
# Every add-on found, by name, with its manifest, folder and any problem.
# Kept between requests until folder_stamp says the folders changed, so a
# long-running worker notices an install at its next request.
sub addons_available {
    return $addons_cache if $addons_cache;
    my $stamp=join '|',map {folder_stamp($_,'addon.json')} addon_paths();
    return $addons_cache=$addons_kept if $addons_kept && $stamp eq $addons_stamp;
    my $found=do {
        my %all;
        for my $path (addon_paths()) {
            opendir(my $dh,$path) or next;
            for my $entry (sort readdir $dh) {
                next if $entry =~ /\A\./ || exists $all{$entry};
                my $dir="$path/$entry";next unless -f "$dir/addon.json";
                my $m=attempt {open my $fh,"<:raw","$dir/addon.json" or die;local $/;JSON::PP->new->utf8->decode(<$fh>)};
                $m={name=>$entry} unless ref $m eq 'HASH';
                $m->{dir}=$dir;$m->{problem}=addon_manifest_problem($m,$dir);
                $m->{name}=$entry if $m->{problem};
                $all{$entry}=$m;
            }
            closedir $dh;
        }
        \%all;
    };
    ($addons_kept,$addons_stamp)=($found,$stamp);
    return $addons_cache=$found;
}
# One usable add-on's manifest by name, or undef.
sub addon ($name) { my $m=addons_available()->{$name//''};return $m && !$m->{problem} ? $m : undef }
# The add-ons switched on, as saved in the `addons` setting.
sub addons_enabled_saved { my $list=json_cached(setting('addons'));return ref $list eq 'ARRAY' ? @$list : () }
# The add-ons that are switched on and can be used now.
sub addons_enabled { return grep {addon($_)} addons_enabled_saved() }
# Whether one add-on is on.
sub addon_enabled ($name) { return scalar grep {$_ eq $name} addons_enabled() }
# Saves which add-ons are on.
sub addons_save (@names) { my %seen;setting_save(addons=>JSON::PP->new->encode([grep {!$seen{$_}++} @names])) }

# Loads an enabled add-on's code once per process; returns its package.
# Loads an add-on's code the first time it's needed in this process (`do`
# runs the file), checks it defined its package, and returns the package
# name. An add-on that's off is never loaded.
sub addon_package ($name) {
    my $m=addon($name) or return undef;
    state %loaded;
    unless ($loaded{$name}) {
        my $file="$m->{dir}/$m->{module}";
        my $ok=do $file;
        die "Add-on $name failed to load: ".($@ || $! || 'it did not return true')."\n" unless $ok;
        {no strict 'refs';die "Add-on $name doesn't define $m->{package}\n" unless %{"$m->{package}::"}}
        $loaded{$name}=1;
    }
    return $m->{package};
}
# Calls one add-on's hook if it has it: (found, result).
# Calls one hook of one add-on (if the add-on has that function). Returns
# nothing when it hasn't.
sub addon_call ($name,$hook,@args) {
    my $pkg=addon_package($name) or return;
    my $code=$pkg->can($hook) or return;
    return $code->(@args);
}
# Calls a hook on every enabled add-on; returns name => result for those that answered.
# Calls a hook on every add-on that's on. One add-on failing doesn't stop the
# others: its failure is skipped. Returns name => result.
sub addon_hook ($hook,@args) {
    my %r;
    for my $name (addons_enabled()) {
        my $pkg=attempt {addon_package($name)} or next;
        my $code=$pkg->can($hook) or next;
        my @out=attempt {$code->(@args)};
        $r{$name}=$out[0] if @out;
    }
    return %r;
}

# ---- Places add-ons plug in ----------------------------------------------------------
# Block types: an add-on's blocks(): { type => spec } with types named <addon>_<something>;
# a spec is like a core block type plus render => sub ($block,%options) returning HTML.
our $addon_blocks_cache;   # cleared at the start of every request
# Every block type that add-ons that are on provide, worked out once a
# request. A type must be named after its add-on (store_products) and have a
# render function. Each also gets "leave out when printed".
sub addon_block_types {
    return %{$addon_blocks_cache //= do {
        my %all;my %by=addon_hook('blocks');
        for my $name (sort keys %by) {
            my $types=$by{$name};next unless ref $types eq 'HASH';
            for my $type (sort keys %$types) {
                next unless $type =~ /\A\Q$name\E_[a-z0-9_]+\z/ && ref $types->{$type}{render} eq 'CODE';
                my $t={order=>100,%{$types->{$type}},addon=>$name};
                $t->{fields}=[@{$t->{fields}//[]},anchor_field(),[print_hide=>'Leave out when the page is printed','check']];
                $all{$type}=$t;
            }
        }
        \%all;
    }};
}
# Extra addresses add-ons put in the sitemap.
sub addon_sitemap { my %r=addon_hook('sitemap');return map {ref $_ eq 'ARRAY' ? @$_ : ()} map {$r{$_}} sort keys %r }
# Extra addresses add-ons keep search engines away from.
sub addon_robots { my %r=addon_hook('robots');return map {ref $_ eq 'ARRAY' ? @$_ : ()} map {$r{$_}} sort keys %r }
# An add-on's CSS and JavaScript go only on the pages that use it: its own
# page, pages with its blocks, and its addresses under /x/NAME/. A manifest
# with "everywhere": true in its assets (the Store's cart, which follows the
# buyer) has them on every public page.
# The add-ons' CSS and JavaScript links for a page, with ?v=VERSION so an
# update is fetched at once.
sub addon_head ($meta={}) {
    my $page=$meta->{page};my %used;
    if ($page) {
        $used{$page->{addon}}=1 if length($page->{addon}//'');
        my $types=block_types();
        for (@{$page->{blocks}//[]}) {my $a=($types->{$_->{type}}//{})->{addon};$used{$a}=1 if $a}
    }
    $used{$1}=1 if ($route//'') =~ m{\A/x/([a-z0-9-]+)/};
    my $html='';
    for my $name (addons_enabled()) {
        my $m=addon($name);my $v=h($m->{version});
        next unless $used{$name} || ($m->{assets}{everywhere} && $m->{assets}{everywhere} ne 'false');
        $html.='<link rel="stylesheet" href="/addons/'.$name.'/'.h($_).'?v='.$v.'">' for @{$m->{assets}{css}//[]};
        $html.='<script defer src="/addons/'.$name.'/'.h($_).'?v='.$v.'"></script>' for @{$m->{assets}{js}//[]};
    }
    return $html;
}
# An add-on's admin screens (its tabs on the Add-ons screen). The manifest's "admin" is one
# screen or a list: {"label": …, "screen": "admin" | "service"}. An "admin"
# screen runs in the admin service (/admin/?kind=x-NAME: the catalogue and
# media, but no secrets); a "service" screen runs in the add-on's own service
# (/admin/x/NAME/: its private folders, read-only catalogue).
# An add-on's admin screens from its manifest ("admin" may be one or a list).
sub addon_admin_screens ($m) { my $a=$m->{admin};return grep {ref $_ eq 'HASH' && length($_->{label}//'')} ref $a eq 'ARRAY' ? @$a : ($a) }
# The admin screens of the add-ons that are on, for the Add-ons screen's tabs:
# {name, label, screens => [[section key, label, address], …]} in label order.
# The admin screens of the add-ons that are on, for the Add-ons tabs:
# {name, label, screens => [[key, label, address], ...]}. A screen can be one
# of the add-on's own (in the admin service or in its own service), a core
# screen it "claims" (Blog shows Articles and Comments in its tab), or its
# page in the page editor. Every add-on with a page gets a Page tab.
sub addon_admin_sections {
    my @groups;
    for my $name (addons_enabled()) {
        my $m=addon($name);my @screens;
        my $paged=ref $m->{page} eq 'HASH';my $page_tab=0;
        for my $s (addon_admin_screens($m)) {
            # A core screen the add-on takes into its tab (Blog: Articles, Comments).
            if (($s->{claims}//'') =~ /\A[a-z]+\z/ && ($s->{href}//'') =~ m{\A/admin/}) {push @screens,["x-$name-$s->{claims}",$s->{label},$s->{href}];next}
            # Its page, in the page editor ("screen": "page").
            if (($s->{screen}//'') eq 'page') {next unless $paged;push @screens,["x-$name-page",$s->{label},"/admin/?kind=x-$name-page"];$page_tab=1;next}
            my $service=($s->{screen}//($m->{service} ? 'service' : 'admin')) eq 'service' && $m->{service};
            # A service screen with a "path" (0.44.0) is another of its own
            # screens, at /admin/x/NAME/PATH (the Store's Print on demand).
            my $path=$service && ($s->{path}//'') =~ /\A[a-z][a-z0-9-]{0,19}\z/ ? $s->{path} : '';
            push @screens,$service ? ["x-$name-service".(length $path ? "-$path" : ''),$s->{label},"/admin/x/$name/$path"] : ["x-$name",$s->{label},"/admin/?kind=x-$name"];
        }
        # Every add-on with a page has a Page tab, after its own screens.
        push @screens,["x-$name-page",'Page',"/admin/?kind=x-$name-page"] if $paged && !$page_tab;
        push @groups,{name=>$name,label=>$m->{label}//$name,screens=>\@screens} if @screens;
    }
    return sort {lc $a->{label} cmp lc $b->{label}} @groups;
}
# An add-on's Page tab (kind x-NAME-page): its page in the page editor, with
# the add-on's tabs above it. When the page was deleted: how to give it one.
# An add-on's Page tab (?kind=x-NAME-page): its page in the page editor.
# When its page was deleted, the tab says how to give it one, and can make
# any other page its page ("use this page").
sub addon_page_screen ($name) {
    my $m=addon($name) or return 0;my $kind="x-$name-page";
    addon_pages_claim();
    my $message=param('notice',2000);
    if ($method eq 'POST' && param('action',30) eq 'addon_page_use' && !addon_page($name)) {
        attempt {
            my $p=page_by_slug(param('page',60)//'');
            die "Choose a page.\n" unless $p && $p->{slug} ne 'home' && !length($p->{addon}//'');
            addon_page_take($name,$p->{slug});
            redirect("/admin/?kind=$kind&notice=".CGI::escape(encode('UTF-8',"The $p->{nav_label} page is now $m->{label}’s page.")));
        } or $message=failed_action($@);
    }
    if (my $page=addon_page($name)) {page_builder_admin(page=>$page,section=>$kind,crumbs=>[]);return 1}
    admin_page($m->{label},section=>$kind,notice=>$message);
    my $slug=$m->{page}{slug}//$name;
    my @free=grep {$_->{slug} ne 'home' && !length($_->{addon}//'')} @{all_pages()};
    window('its page','<p>Its page was deleted. Make a page at <code>/'.h($slug).'/</code> under <a href="/admin/?kind=pages">Pages</a> and it becomes '.h($m->{label}).'’s page, or choose a page you have:</p>'
        .(@free ? '<form method="post" action="/admin/" class="inline-form">'.fields('addon_page_use',$kind).'<label class="visually-hidden" for="addon-page-use">Page</label><select id="addon-page-use" name="page">'
            .join('',map {'<option value="'.h($_->{slug}).'">'.h($_->{nav_label}).' ('.h($_->{path}).')</option>'} @free).'</select> <button class="buttonlike is-primary" type="submit">use this page</button></form>' : '<p>There are no other pages yet.</p>'));
    end_page();
    return 1;
}
# An add-on's page with none of the blocks its manifest gives the page (made
# before the add-on, or emptied): the add-on's label, for the page editor to
# offer them; '' otherwise.
# Whether an add-on's page has none of the blocks its manifest gives it (a
# page made before the add-on, or emptied): the add-on's label if so, for
# the editor's "add NAME's blocks", else ''.
sub addon_page_blocks_missing ($page) {
    my $a=$page->{addon}//'';
    return '' unless length $a && addon_enabled($a);
    my $m=addon($a);my @want=ref $m->{page} eq 'HASH' && ref $m->{page}{blocks} eq 'ARRAY' ? grep {block_types()->{$_}} map {$_->{type}//''} @{$m->{page}{blocks}} : ();
    return '' unless @want;
    my %have=map {($_->{type}=>1)} @{$page->{blocks}};
    return (grep {$have{$_}} @want) ? '' : ($m->{label}//$a);
}
# Adds them at the end of the page, as the manifest gives them; returns how many.
# Adds those blocks at the end of the page; returns how many.
sub addon_page_blocks_add ($page) {
    length addon_page_blocks_missing($page) or return 0;
    my $m=addon($page->{addon});my $n=0;
    for my $b (@{$m->{page}{blocks}}) {
        my $t=block_types()->{$b->{type}//''} or next;
        block_add($page,$b->{type},(grep {$_->[0] eq ($b->{width}//'')} widths()) ? $b->{width} : 'full',{%{block_defaults_of($t)},%{ref $b->{data} eq 'HASH' ? $b->{data} : {}}});
        $page=page_by_slug($page->{slug});$n++;
    }
    return $n;
}
# Settings an add-on keeps in the catalogue (written by the admin service).
# The addon_settings table: an add-on's own settings, by add-on and key.
sub ensure_addon_tables { $db->do('CREATE TABLE IF NOT EXISTS addon_settings (addon TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(addon,key))') }
# One add-on setting, or the default.
sub addon_setting ($name,$key,$default='') {
    my $v=attempt {$db->selectrow_array('SELECT value FROM addon_settings WHERE addon=? AND key=?',undef,$name,$key)};
    return $v // $default;
}
# Saves add-on settings.
sub addon_setting_save ($name,%values) {
    ensure_addon_tables();
    $db->do('INSERT INTO addon_settings(addon,key,value) VALUES (?,?,?) ON CONFLICT(addon,key) DO UPDATE SET value=excluded.value',undef,$name,$_,$values{$_}) for sort keys %values;
}
# The private folders of an add-on that runs as its own service (made by
# blowfishctl addon enable, owned by the add-on's account): its data (in
# backups) and its secrets such as API keys (only in --with-secrets backups).
sub addon_data_dir ($name) { return "$base/var/db/blowfishcms-addons/$name" }
sub addon_secret_dir ($name) { return "$base/etc/blowfishcms-addons/$name" }
# A service add-on with "files": true also gets NAME-files, which it writes and
# httpd serves as they are at /x/NAME/files/ (Live's stream pieces): group www,
# so httpd can read it, and nothing else of the add-on's.
sub addon_files_dir ($name) { return "$base/var/db/blowfishcms-addons/$name-files" }

# ---- Hand-overs from an add-on's service to its admin side (0.45.0) ----------
# An add-on's service can't write the catalogue, and the admin service can't
# read the add-on's secrets. So a service hands its admin side something to
# do as a JSON file: addon_hand_over(NAME, DATA) writes it into the add-on's
# data folder's to-admin/. Every minute root's runner (blowfishctl requests)
# moves each into the admin's addons-in/ as NAME-FILE.json, readable by the
# admin's account alone, and runs site.pl --addons-in as that account, which
# passes it to the add-on's from_service($data) hook, oldest first. The
# Store hands over Printful's products this way. One that fails goes to
# addons-in/failed/ with a .why, kept for a week.
sub addon_hand_over ($name,$data) {
    my $dir=addon_data_dir($name).'/to-admin';
    mkdir $dir,0700 unless -d $dir;
    my $file=sprintf('%s-%s.json',strftime('%Y%m%dT%H%M%S',gmtime),substr(random_id(),0,8));
    # Written beside it first, so the runner never moves half a file.
    open my $fh,'>:raw',"$dir/.$file.tmp" or die "The hand-over couldn’t be written: the add-on’s data folder isn’t set up.\n";
    print {$fh} JSON::PP->new->canonical->utf8->encode($data);close $fh or die "The hand-over couldn’t be written.\n";
    rename "$dir/.$file.tmp","$dir/$file" or do {unlink "$dir/.$file.tmp";die "The hand-over couldn’t be written.\n"};
    return $file;
}
sub addons_in_dir { "$data/addons-in" }
# site.pl --addons-in (as the admin's account): each waiting hand-over to its add-on.
sub addons_in_cli {
    binmode STDOUT,':encoding(UTF-8)';binmode STDERR,':encoding(UTF-8)';
    my $dir=addons_in_dir();
    opendir(my $dh,$dir) or return 0;
    my @files=grep {/\A[a-z][a-z0-9]{1,19}-[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.json\z/ && -f "$dir/$_" && !-l "$dir/$_"} readdir $dh;closedir $dh;
    @files=sort {(stat "$dir/$a")[9] <=> (stat "$dir/$b")[9] || $a cmp $b} @files;
    my $status=0;
    for my $file (@files) {
        my $path="$dir/$file";
        my ($name)=$file =~ /\A([a-z][a-z0-9]{1,19})-/;
        my $said;
        my $ok=attempt {
            die "It’s over 8 MB.\n" if -s $path>8*1048576;
            # Written as UTF-8 by addon_hand_over, so read as UTF-8 (read_json_file leaves bytes).
            my $data=attempt {open my $fh,'<:raw',$path or die "unreadable\n";local $/;JSON::PP->new->utf8->decode(<$fh>)};
            die "It isn’t JSON.\n" unless ref $data;
            die "$name isn’t on.\n" unless addon_enabled($name);
            my $pkg=addon_package($name) or die "$name can’t be loaded.\n";
            my $code=$pkg->can('from_service') or die "$name takes no hand-overs.\n";
            $said=$code->($data);1;
        };
        if ($ok) {unlink $path;say "$file: ".($said//'done');next}
        my $e=clean_error($@);attempt {$db->rollback} if $db->{BegunWork};
        mkdir "$dir/failed",0700;
        if (rename $path,"$dir/failed/$file") {if (open my $fh,'>:raw',"$dir/failed/$file.why") {print {$fh} encode('UTF-8',$e);close $fh}}
        else {unlink $path}
        say STDERR "$file: $e";$status=1;
    }
    return $status;
}

# Public routes /x/<name>/… and, for add-ons with their own service, admin
# screens /admin/x/<name>/…; httpd sends both here with SCRIPT_NAME "/_addon".
# An add-on's own addresses. /x/NAME/... is public: its route hook draws the
# answer. /admin/x/NAME/... runs in the add-on's own service, needs a
# signed-in owner, and gets its own CSRF cookie made with the add-on's secret
# key. The rest of the address may hold the characters file names use
# (Repositories shows README.md and .gitignore), but no "." or ".." part and
# no control characters; each add-on's route checks its own addresses too.
# Everything is refused while the add-on is off.
sub addon_route ($path) {
    my ($area,$name,$rest)=$path =~ m{\A/(admin/)?x/([a-z][a-z0-9]{1,19})/([A-Za-z0-9/._~+@,= -]*)\z} or return 0;
    return 0 if $rest =~ m{(?:\A|/)\.\.?(?:/|\z)|//};
    $db //= attempt {database()};
    unless (addon_enabled($name)) {header(404,'text/plain; charset=UTF-8');print 'Not Found';return 1}
    if ($area) {
        require_admin(0,1) or return 1;
        attempt {csrf_setup(addon_secret($name,'csrf'),"bf_x_${name}_csrf","/admin/x/$name/");1} or do {header(403,'text/plain; charset=UTF-8');print clean_error($@);return 1};
        my @r=addon_call($name,'service_admin',$rest);
        unless (@r) {header(404,'text/plain; charset=UTF-8');print 'Not Found'}
        return 1;
    }
    my @r=addon_call($name,'route',$rest);
    unless (@r && $r[0]) {header(404,'text/plain; charset=UTF-8');print 'Not Found'}
    return 1;
}
# A random key kept in the add-on's private folder (made on first use).
# A random secret for an add-on (made the first time, readable by its
# account only), such as its forms' key.
sub addon_secret ($name,$key) {
    my $dir=addon_secret_dir($name);my $file="$dir/$key.key";
    if (!-e $file && sysopen(my $out,$file,Fcntl::O_WRONLY()|Fcntl::O_CREAT()|Fcntl::O_EXCL(),0600)) {print {$out} random_id().random_id();close $out}
    open my $fh,'<',$file or die "The $name add-on's private folder isn't set up. Run: doas blowfishctl addon enable $name\n";
    local $/;my $s=<$fh>;close $fh;$s =~ s/\s+//g;
    return $s;
}

# ---- Turning add-ons on and off ----------------------------------------------------
# Add-ons that run their own service (accounts, folders, httpd) are switched
# by blowfishctl as root; it calls this through site.pl --addon-enable.
# Switches an add-on on: its migrate hook makes its tables, it's added to
# the enabled list, and it gets its page if its manifest has one. For an
# add-on with its own service, blowfishctl first makes its account and
# folders as root, then calls this through site.pl --addon-enable.
sub addon_enable ($name) {
    my $m=addon($name) or die "No usable add-on called $name.\n";
    ensure_addon_tables();
    addon_call($name,'migrate',$db);
    addons_save(addons_enabled_saved(),$name);
    undef $addon_blocks_cache;
    addon_page_ensure($name);
}
# ---- An add-on's own page ------------------------------------------------------------
# An add-on whose addon.json has a "page" ({slug, label, title, blocks:
# [{type, width, data}]}) gets that page when it's switched on: a page at an
# address its page.adopt list names is taken, otherwise one is made, off, so
# it can be filled before visitors see it. Its content is managed on the
# add-on's tab; its layout is edited like any page. While the add-on is off,
# its page answers "not found". Each add-on gets a page once (addon_pages
# remembers which have had one), so a page you delete stays deleted.
# An add-on's page, or undef.
sub addon_page ($name) { my ($p)=grep {($_->{addon}//'') eq $name} @{all_pages()};return $p }
# Gives an add-on its page, when its manifest has one:
#   - if it already has one, nothing changes;
#   - the first time: a page at one of its page.adopt addresses becomes its
#     page; otherwise a new page is made, switched off, with the manifest's
#     blocks, at its address (or its name, or with a number added);
#   - after its page was deleted ($create off): only a page the owner makes
#     at its address (or its name) is taken; nothing is made again.
# addon_pages remembers which add-ons have had a page.
sub addon_page_ensure ($name,$create=1) {
    my $m=addon($name) or return;my $spec=$m->{page};
    return unless ref $spec eq 'HASH';
    reset_page_cache();
    my $had=(attempt {decode_json($db->selectrow_array("SELECT value FROM site_settings WHERE key='addon_pages'")//'[]')}) // [];
    my $mark=sub {$db->do("INSERT INTO site_settings(key,value) VALUES ('addon_pages',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",undef,encode_json([sort {$a cmp $b} keys %{{map {($_=>1)} @$had,$name}}]))};
    if (my $p=addon_page($name)) {$mark->();return $p->{slug}}
    my $first=!grep {$_ eq $name} @$had;
    $create=0 unless $first;
    my $types=(attempt {addon_call($name,'blocks')}) // {};$types={} unless ref $types eq 'HASH';
    my %pages=map {($_->{slug}=>$_)} @{all_pages()};
    my @adopt=@{ref $spec->{adopt} eq 'ARRAY' ? $spec->{adopt} : []};
    # A page at one of the addresses it names becomes its page. Once its own
    # page has been deleted, a page the owner makes at its address, or its
    # name, is taken as the new one; nothing is made again.
    my @at=$first ? ($create ? @adopt : ()) : (@adopt,$spec->{slug}//(),$name);
    my ($at)=grep {my $p=$pages{$_};$p && $_ ne 'home' && !length($p->{addon}//'')} @at;
    return addon_page_take($name,$at,$mark) if $at;
    # Only the first time, and never Home (every site needs it, add-on or not).
    return unless $create;
    # Its address: the one it asks for, else its own name, else a number added.
    my ($slug)=grep {slug_ok($_) && !page_by_slug($_)} ($spec->{slug}//''),$name;
    unless ($slug) {my $base=slug_ok($spec->{slug}//'') ? $spec->{slug} : $name;my $n=2;$n++ while page_by_slug("$base-$n");$slug="$base-$n"}
    my $label=lc($spec->{label}//$m->{label}//$name);
    $db->do('INSERT INTO pages (slug,path,nav_label,title,description,style,created_at,updated_at,addon) VALUES (?,?,?,?,?,?,?,?,?)',undef,
        $slug,"/$slug/",$label,($spec->{title}//ucfirst $label).' | '.setting('site_title'),$spec->{description}//'','{}',now(),now(),$name);
    my $i=0;
    for my $b (grep {ref eq 'HASH' && ($types->{$_->{type}//''} || core_block_types()->{$_->{type}//''})} @{ref $spec->{blocks} eq 'ARRAY' ? $spec->{blocks} : []}) {
        my $t=$types->{$b->{type}} // core_block_types()->{$b->{type}};
        $db->do('INSERT INTO page_blocks (id,page,sort_order,type,width,data) VALUES (?,?,?,?,?,?)',undef,substr(random_id(),0,16),$slug,$i++,$b->{type},
            (grep({$_->[0] eq ($b->{width}//'')} widths()) ? $b->{width} : 'full'),JSON::PP->new->canonical->encode({%{block_defaults_of($t)},%{ref $b->{data} eq 'HASH' ? $b->{data} : {}}}));
    }
    reset_page_cache();
    redirect_forget_from("/$slug/");
    save_nav(nav_items(),{page=>$slug,visible=>0});
    $mark->();
    return $slug;
}
# An existing page becomes the add-on's.
# Makes an existing page an add-on's page.
sub addon_page_take ($name,$slug,$mark=undef) {
    $db->do('UPDATE pages SET addon=? WHERE slug=?',undef,$name,$slug);
    reset_page_cache();
    $mark->() if $mark;
    return $slug;
}
# After a page is made or moved: an add-on whose page was deleted takes one at its address.
# After a page is made or moved: any add-on that's on and has lost its page
# takes that page if it's at its address.
sub addon_pages_claim { attempt {addon_page_ensure($_,0) for grep {my $m=addon($_);$m && ref $m->{page} eq 'HASH' && !addon_page($_)} addons_enabled()} }
# Switches an add-on off. Its data stays; its blocks are hidden and its page
# answers "not found" until it's on again.
sub addon_disable ($name) { addons_save(grep {$_ ne $name} addons_enabled_saved());undef $addon_blocks_cache }

# The list of add-ons that can be installed, as the request runner last wrote it.
# The list of add-ons that can be installed, as the runner last wrote it.
sub addons_catalog { my $c=read_json_file(system_dir().'/results/addons.json');return ref $c eq 'HASH' && ref $c->{addons} eq 'ARRAY' ? $c : undef }
# The last add-on request, while it's the newest (to show how it went).
# The most recent add-on request, for the "last request failed" note.
sub addons_last_request { my ($r)=grep {($_->{action}//'') =~ /\Aaddons?_/} @{system_results()};return $r }

# The Add-ons screen (owners). Actions (most are requests for the root
# runner, as installing needs root):
#   addons_update_all / addons_upload / addons_refresh
#   addon_install / addon_update / addon_remove (switched off first when it's on)
#   addon_enable / addon_disable: done here for plain add-ons; for ones with
#                 their own service, a request (root makes or removes the
#                 account, folders, service and httpd addresses)
# Then the screen: the installed add-ons (on or off, what they connect to,
# update, switch, remove, open), and the ones that can be installed.
sub addons_admin {
    my $message=param('notice',2000);
    my $back='/admin/?kind=addons&notice=';
    my $catalog=addons_catalog();my %offered=map {($_->{name}=>$_)} grep {ref eq 'HASH'} @{$catalog ? $catalog->{addons} : []};
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',30);my $name=param('name',20);
            if ($action eq 'addons_update_all') {redirect($back.CGI::escape(encode('UTF-8',updates_all_request('addon'))))}
            if ($action eq 'addons_upload') {my $id=system_upload('archive','add-ons (a .tar.gz)','Add-on archives',32);system_request('addons_add','',$id);redirect($back.CGI::escape(encode('UTF-8','Uploaded. The server adds what’s in it to the list below within a minute.')))}
            if ($action eq 'addons_refresh') {system_request('addons_refresh');redirect($back.CGI::escape('Checking for add-ons. The list below updates within a minute or two.'))}
            if ($action eq 'addon_install') {
                my $o=$offered{$name} or die "There’s no add-on called that in the list. Upload it below.\n";
                die "$o->{label} is already installed.\n" if addons_available()->{$name};
                die "$o->{label} needs BlowfishCMS $o->{blowfishcms} or newer. Update BlowfishCMS first.\n" if version_cmp($VERSION,$o->{blowfishcms}//'0')<0;
                system_request('addon_install',$name);
                redirect($back.CGI::escape(encode('UTF-8',"Installing $o->{label}. The server installs it and switches it on within a minute or two.")));
            }
            my $m=addons_available()->{$name};$m=undef if $m && $m->{problem};
            die "There’s no usable add-on called that.\n" unless $m;
            if ($action eq 'addon_update') {
                my $o=$offered{$name};
                die "There’s no newer version of $m->{label}.\n" unless $o && version_cmp($o->{version}//'0',$m->{version})>0;
                die "$m->{label} $o->{version} needs BlowfishCMS $o->{blowfishcms} or newer. Update BlowfishCMS first.\n" if version_cmp($VERSION,$o->{blowfishcms}//'0')<0;
                system_request('addon_update',$name);
                redirect($back.CGI::escape(encode('UTF-8',"Updating $m->{label} to $o->{version}. The server does it within a minute or two.")));
            }
            if ($action eq 'addon_remove') {
                # The server switches it off first when it's on (blowfishctl's addon_remove request).
                my $on=addon_enabled($name);
                system_request('addon_remove',$name);
                redirect($back.CGI::escape(encode('UTF-8',($on ? "Switching $m->{label} off and removing it" : "Removing $m->{label}").'. Its data is kept, in case you install it again. The server does it within a minute or two.')));
            }
            if ($action eq 'addon_enable' || $action eq 'addon_disable') {
                my $on=$action eq 'addon_enable';
                if ($m->{service}) {
                    # Its account, folders, service and web addresses are made by root.
                    system_request($action,$name);
                    redirect($back.CGI::escape(encode('UTF-8',"Switching $m->{label} ".($on?'on':'off').'. The server does it within a minute or two.')));
                }
                if ($on) {
                    $db->begin_work;
                    attempt {addon_enable($name);$db->commit;1} or do {my $e=$@;$db->rollback;die $e};
                    redirect($back.CGI::escape(encode('UTF-8',"$m->{label} is on.")));
                }
                addon_disable($name);
                redirect($back.CGI::escape(encode('UTF-8',"$m->{label} is off. Its data is kept; its blocks are hidden until you switch it on again.")));
            }
            die "Choose an action.\n";
        } or $message=failed_action($@);
    }
    my $ready=system_ready() && !system_state()->{off};my $pending=$ready && system_pending();
    admin_page('Add-ons',section=>'addons',notice=>$message,intro=>'Optional features, uploaded under available below. An add-on that’s off isn’t loaded at all, so it costs nothing.');
    print '<div data-refresh="'.($pending ? 10 : 0).'"></div>';
    my $progress=updates_all_status_html(qr/\A(?:addons_update_all|updates_all)\z/);
    print '<p class="panel-note">Working on it… this page refreshes by itself.</p>' if $pending && $progress !~ /Updating/;
    print $progress,request_failed_notice(addons_last_request());
    print update_all_button_html('addon','addons');
    my $off=$pending ? ' disabled' : '';
    my $button=sub ($action,$name,$label,$class='',$confirm='') {
        return '<form method="post" action="/admin/"'.(length $confirm ? ' class="delete-form" data-confirm="'.h($confirm).'"' : '').'>'.fields($action,'addons').hidden(name=>$name)
            .'<button class="'.($class eq 'danger' ? 'text-button danger' : 'buttonlike'.($class ? " $class" : '')).'" type="submit"'.($action =~ /enable|disable/ && !addons_available()->{$name}{service} ? '' : $off).'>'.h($label).'</button></form>';
    };
    my $command=sub ($cmd) { return '<code class="addon-command">doas blowfishctl addon '.h($cmd).'</code>' };
    my $all=addons_available();my %on=map {$_=>1} addons_enabled();
    my @rows;
    for my $name (sort {($all->{$a}{label}//$a) cmp ($all->{$b}{label}//$b)} keys %$all) {
        my $m=$all->{$name};my $o=$offered{$name};my $label=$m->{label}//$name;
        my $title=h($label).($m->{version}?' <span class="media-label">'.h($m->{version}).'</span>':'');
        my $newer=$o && version_cmp($o->{version}//'0',$m->{version}//'0')>0;
        if ($m->{problem}) {
            push @rows,admin_row(title_html=>$title,off=>1,text=>'<span class="admin-notice--error">Can’t be used: '.h($m->{problem}).'</span>',
                actions=>$newer && version_cmp($VERSION,$o->{blowfishcms}//'0')>=0 ? ($ready ? $button->('addon_update',$name,'update to '.$o->{version},'is-primary') : $command->("update $name")) : '');
            next;
        }
        # On or off (a switch; a command to type while the server can't do it),
        # then its own screens, which are tabs of this screen (the row opens the
        # first), and an update; removing one that's off is in "…".
        my $actions=$m->{service} && !$ready ? $command->(($on{$name}?'disable':'enable')." $name")
            : switch_button('addons',$on{$name}?'addon_disable':'addon_enable','',$on{$name},'on',what=>'On',name=>$label,post=>{name=>$name},disabled=>$m->{service} && $pending ? 'Waiting for the server' : '');
        if ($on{$name}) {
            my ($g)=grep {$_->{name} eq $name} attempt {addon_admin_sections()};
            $actions.='<a class="buttonlike" href="'.h($g->{screens}[0][2]).'">open</a>' if $g;
        }
        if ($newer) {
            $actions.=version_cmp($VERSION,$o->{blowfishcms}//'0')<0 ? '<span class="media-label">'.h($o->{version}).' needs BlowfishCMS '.h($o->{blowfishcms}).'</span>'
                : $ready ? $button->('addon_update',$name,'update to '.$o->{version},'is-primary') : $command->("update $name");
        }
        push @rows,admin_row(title_html=>$title,menu_for=>$label,off=>!$on{$name},text=>h($m->{description}//''),
            meta=>[$on{$name}?'on':'off',($m->{service}?'runs as its own service':()),(@{$m->{network}//[]} ? 'connects to '.h(join(', ',@{$m->{network}})) : 'no outside connections'),($m->{author}?'by '.h($m->{author}):())],
            actions=>$actions,
            # Removing: from any installed add-on, switched off first when it's on.
            menu=>$ready ? $button->('addon_remove',$name,'remove','danger',($on{$name} ? "Switch $label off and remove it? " : "Remove $label? ")."Its data is kept, in case you install it again.")
                : ($on{$name} ? $command->("disable $name") : '').$command->("remove $name"));
    }
    window('installed',admin_list(\@rows,empty=>'No add-ons are installed. Install one below.'));
    # The list's add-ons that aren't installed.
    my @more=grep {!$all->{$_->{name}}} sort {($a->{label}//$a->{name}) cmp ($b->{label}//$b->{name})} values %offered;
    my $list='';
    for my $o (@more) {
        my $fits=version_cmp($VERSION,$o->{blowfishcms}//'0')>=0;
        $list.=admin_row(title_html=>h($o->{label}//$o->{name}).' <span class="media-label">'.h($o->{version}//'').'</span>',text=>h($o->{description}//''),
            meta=>[($o->{service}?'runs as its own service':()),(ref $o->{network} eq 'ARRAY' && @{$o->{network}} ? 'connects to '.h(join(', ',@{$o->{network}})) : 'no outside connections'),($o->{author}?'by '.h($o->{author}):())],
            actions=>!$fits ? '<span class="media-label">needs BlowfishCMS '.h($o->{blowfishcms}).'</span>' : $ready ? $button->('addon_install',$o->{name},'install','is-primary') : $command->("install $o->{name}"));
    }
    window('available',catalog_box('addons',$catalog,$list,scalar @more,$ready,$pending));
    end_page();
}

1;