repository

BlowfishCMS

A small content management system for OpenBSD

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

490 lines · 39.3 KB · download this file

package BlowfishCMS;
# Analytics: visitor numbers for the site's owners, in the admin only.
#
# Where each part runs:
#   the browser        /js/stats.js (on public pages, while Analytics is on)
#                      posts the page's address, the referrer, a tagged link's
#                      word (?ref=, ?utm_source=, ?from=, then taken out of the
#                      address) and the window's width to /stats/hit. No
#                      cookies, no identifiers. A
#                      browser that has been signed in to the admin isn't
#                      counted (admin.js; the owner can change that).
#   comments service   /stats/hit and the Analytics screen (/admin/analytics/),
#                      on $cdata/analytics/analytics.sqlite. The folder is the
#                      comments account's alone (0700), so no other service
#                      can read the numbers. "Off" is $cdata/analytics-off,
#                      which the public service checks before adding the script.
#
# What's kept: counts per day (views and visitors), per page, per referring
# site, per browser, system and kind of device, and per place (city, region,
# country). The place is looked up from the visitor's address in a city
# database on the server (places.mmdb in the same folder: DB-IP's IP to City
# Lite, fetched monthly by blowfishctl; BlowfishCMS::MMDB reads it); only the
# place is kept, and nothing is sent anywhere. A visitor is counted once
# a day by a hash of their address and browser with that day's random salt;
# the salt and the hashes are deleted when the day is over, so visitors can't
# be followed from day to day and no address is ever stored.
#
# Since 0.39.5 each visit is kept too (90 days): one visitor's pages in order,
# until half an hour without one or a new arrival from elsewhere, with where
# it came from (analytics_source: a tagged link's word, a known site or
# Android app by name, else the referring site), the place and the device.
# Visits are counted per source when they arrive, so the site's own pages no
# longer count as "not said". The visit has no hash; only today's "current"
# table links a hash to its visit, and it's emptied with the day.
use v5.36;
use utf8;
use Digest::SHA qw(sha256_hex);
use POSIX qw(strftime);
use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
our %instance;
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);

# The Analytics folder, inside the comments service's own folder.
sub analytics_dir { return "$cdata/analytics" }
# On unless the "analytics-off" file exists (and comments are set up).
sub analytics_on { return comments_enabled() && !-e "$cdata/analytics-off" }
# The counting script, for public pages.
sub analytics_head { return analytics_on() ? '<script defer src="/js/stats.js?v=2"></script>' : '' }

# The Analytics database, opened once per worker. WAL mode lets the screen
# read while visits are being counted. Its tables, all per day:
#   daily   views and visitors
#   pages   views per page address
#   refs    views per referring site
#   agents  views per browser, system and kind of device
#   places  views and visitors per place
#   seen    today's visitors, as hashes, and how many views each made
#   state   small values the code keeps
sub analytics_db {
    state %open;my $dir=analytics_dir();my $file="$dir/analytics.sqlite";
    return $open{$file} if $open{$file} && $open{$file}->ping;
    umask 0077;mkdir $dir,0700 unless -d $dir;
    my $s=DBI->connect("dbi:SQLite:dbname=$file",'','',{RaiseError=>1,PrintError=>0,AutoCommit=>1,sqlite_unicode=>1});
    $s->do('PRAGMA busy_timeout=5000');$s->do('PRAGMA journal_mode=WAL');
    $s->do('CREATE TABLE IF NOT EXISTS daily (day TEXT PRIMARY KEY, views INTEGER NOT NULL DEFAULT 0, visitors INTEGER NOT NULL DEFAULT 0)');
    $s->do('CREATE TABLE IF NOT EXISTS pages (day TEXT NOT NULL, path TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day,path))');
    $s->do('CREATE TABLE IF NOT EXISTS refs (day TEXT NOT NULL, host TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day,host))');
    $s->do('CREATE TABLE IF NOT EXISTS agents (day TEXT NOT NULL, kind TEXT NOT NULL, name TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day,kind,name))');
    # Today's visitors (hashes), to count each once; emptied each day.
    $s->do('CREATE TABLE IF NOT EXISTS seen (day TEXT NOT NULL, hash TEXT NOT NULL, hits INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day,hash))');
    $s->do('CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
    # Views and visitors per place; code '' is a place the database didn't know (0.28).
    $s->do('CREATE TABLE IF NOT EXISTS places (day TEXT NOT NULL, code TEXT NOT NULL, country TEXT NOT NULL, region TEXT NOT NULL, city TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0, visitors INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day,code,region,city))');
    # 0.39.5: each visit with its pages in order (kept 90 days), and visits per
    # source (where they came from, counted when they arrive; '' not known).
    # A visit has no visitor hash: today's visitors' current visits are in
    # "current", emptied each day like "seen".
    # AUTOINCREMENT: a visit's number is never used again once it's deleted.
    $s->do('CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY AUTOINCREMENT, day TEXT NOT NULL, started INTEGER NOT NULL, last INTEGER NOT NULL, source TEXT NOT NULL, via TEXT NOT NULL, landing TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0,'
        .' code TEXT NOT NULL, country TEXT NOT NULL, region TEXT NOT NULL, city TEXT NOT NULL, browser TEXT NOT NULL, system TEXT NOT NULL, device TEXT NOT NULL)');
    $s->do('CREATE INDEX IF NOT EXISTS visits_day ON visits(day)');
    $s->do('CREATE TABLE IF NOT EXISTS visit_views (visit INTEGER NOT NULL, at INTEGER NOT NULL, path TEXT NOT NULL)');
    $s->do('CREATE INDEX IF NOT EXISTS visit_views_visit ON visit_views(visit)');
    $s->do('CREATE TABLE IF NOT EXISTS sources (day TEXT NOT NULL, source TEXT NOT NULL, visits INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day,source))');
    $s->do('CREATE TABLE IF NOT EXISTS current (day TEXT NOT NULL, hash TEXT NOT NULL, visit INTEGER NOT NULL, last INTEGER NOT NULL, PRIMARY KEY (day,hash))');
    return $open{$file}=$s;
}
# ---- Places --------------------------------------------------------------------------------
sub analytics_places_file { return analytics_dir().'/places.mmdb' }
# The city database, opened once per worker and again when blowfishctl
# replaces the file (each month); undef while there's none.
# The city database reader. It's reopened when the file's modification time,
# size or inode changes (blowfishctl replaces it monthly), so a worker never
# keeps reading a replaced file.
sub analytics_places_db {
    state ($reader,$stamp);
    my $file=analytics_places_file();my @st=stat $file;
    return undef unless @st;
    require BlowfishCMS::MMDB;   # loaded on first use
    my $now="$st[9]:$st[7]:$st[1]";
    ($reader,$stamp)=(BlowfishCMS::MMDB->load($file),$now) unless $stamp && $stamp eq $now;
    return $reader;
}
# The place for an address: (country code, country, region, city), all ''
# when it isn't known. Regions go by their short code where people know them
# by it (Las Vegas, NV, United States), by name elsewhere.
# The place for an address: (country code, country, region, city), or four
# ''s. The names are the English ones from the city database.
sub analytics_place ($address) {
    my $r=(attempt {my $p=analytics_places_db();$p ? $p->lookup($address) : undef}) // return ('','','','');
    return ('','','','') unless ref $r eq 'HASH' && ref $r->{country} eq 'HASH';
    my $en=sub ($h) {ref $h eq 'HASH' && ref $h->{names} eq 'HASH' ? $h->{names}{en}//'' : ''};
    my $code=uc($r->{country}{iso_code}//'');return ('','','','') unless $code =~ /\A[A-Z]{2}\z/;
    my $sub=ref $r->{subdivisions} eq 'ARRAY' && ref $r->{subdivisions}[0] eq 'HASH' ? $r->{subdivisions}[0] : {};
    my $region=($code =~ /\A(?:US|CA|AU)\z/ && ($sub->{iso_code}//'') =~ /\A[A-Z]{2,3}\z/) ? $sub->{iso_code} : $en->($sub);
    return ($code,map {substr($_//'',0,120)} $en->($r->{country}),$region,$en->($r->{city}));
}
# "Las Vegas, NV, United States" (or "unknown").
sub analytics_place_label ($code,$country,$region,$city) {
    return 'unknown' unless length $code;
    return join ', ',grep {length} $city,$region,$country;
}
# Today's date on the server's clock.
sub analytics_today { return strftime('%Y-%m-%d',localtime) }
# Today's salt, made when the day's first view arrives; yesterday's goes,
# with the visitors seen with it, and anything kept longer than two years.
# Today's salt: a random value mixed into visitor hashes. On the day's first
# view a new one is made (O_EXCL: only one process can make it), the older
# salt files are deleted along with yesterday's visitor hashes, and anything
# older than two years is cleared. Without the old salt the old hashes can't
# be matched to anyone.
sub analytics_salt ($day) {
    my $dir=analytics_dir();my $file="$dir/salt-$day";
    unless (-e $file) {
        if (sysopen(my $fh,$file,O_WRONLY|O_CREAT|O_EXCL,0600)) {print {$fh} random_id().random_id();close $fh}
        unlink grep {!/salt-\Q$day\E\z/} glob("$dir/salt-*");
        my $s=analytics_db();
        $s->do("DELETE FROM $_ WHERE day<?",undef,$day) for qw(seen current);
        my $old=strftime('%Y-%m-%d',localtime(time-731*86400));
        $s->do("DELETE FROM $_ WHERE day<?",undef,$old) for qw(daily pages refs agents places sources);
        # Visits, page by page, are kept 90 days.
        my $gone=strftime('%Y-%m-%d',localtime(time-90*86400));
        $s->do('DELETE FROM visit_views WHERE visit IN (SELECT id FROM visits WHERE day<?)',undef,$gone);
        $s->do('DELETE FROM visits WHERE day<?',undef,$gone);
    }
    open my $fh,'<',$file or return '';my $v=<$fh>//'';close $fh;chomp $v;return $v;
}

# ---- Counting ---------------------------------------------------------------------------
# The browser's name from its User-Agent text. The order matters: Edge and
# Opera also say "Chrome", and Chrome also says "Safari".
sub analytics_browser ($ua) {
    return $ua =~ /Edg(?:e|A|iOS)?\// ? 'Edge' : $ua =~ /OPR\/|Opera/ ? 'Opera' : $ua =~ /SamsungBrowser/ ? 'Samsung Internet' : $ua =~ /Firefox\/|FxiOS/ ? 'Firefox'
        : $ua =~ /Chrome\/|CriOS/ ? 'Chrome' : $ua =~ /Safari\// && $ua =~ /Version\// ? 'Safari' : 'Other';
}
# The operating system from the User-Agent text (iOS before macOS, since
# iPads can say "Mac OS X").
sub analytics_system ($ua) {
    return $ua =~ /iPhone|iPad|iPod/ ? 'iOS' : $ua =~ /Android/ ? 'Android' : $ua =~ /CrOS/ ? 'ChromeOS' : $ua =~ /Windows/ ? 'Windows'
        : $ua =~ /Macintosh|Mac OS X/ ? 'macOS' : $ua =~ /Linux|BSD/ ? 'Linux and BSD' : 'Other';
}
# Phone, tablet or computer, from the User-Agent text and the window width.
sub analytics_device ($width,$ua) {
    return 'Tablet' if $ua =~ /iPad|Tablet/ || ($ua =~ /Android/ && $ua !~ /Mobile/);
    return 'Phone' if $ua =~ /Mobile|iPhone/ || ($width && $width<700);
    return 'Computer';
}
# ---- Where a visit came from --------------------------------------------------------------
# Known places, by the sites they send visitors from (a site or any of its
# subdomains: l.facebook.com is Facebook), by their Android apps (which open
# links with the referrer android-app://PACKAGE/), and by the word a tagged
# link uses (?ref=linkedin).
my @SOURCES=(
    [LinkedIn=>[qw(linkedin.com lnkd.in)],[qw(com.linkedin.android)],[qw(linkedin)]],
    [YouTube=>[qw(youtube.com youtu.be)],[qw(com.google.android.youtube)],[qw(youtube yt)]],
    [Steam=>[qw(steamcommunity.com steampowered.com steam.com)],[qw(com.valvesoftware.android.steam.community com.valvesoftware.steamlink)],[qw(steam)]],
    [Facebook=>[qw(facebook.com fb.com fb.me)],[qw(com.facebook.katana com.facebook.lite com.facebook.orca)],[qw(facebook fb)]],
    [Instagram=>[qw(instagram.com)],[qw(com.instagram.android)],[qw(instagram ig)]],
    ['X (Twitter)'=>[qw(t.co twitter.com x.com)],[qw(com.twitter.android)],[qw(x twitter)]],
    [Reddit=>[qw(reddit.com redd.it)],[qw(com.reddit.frontpage)],[qw(reddit)]],
    [Discord=>[qw(discord.com discordapp.com discord.gg)],[qw(com.discord)],[qw(discord)]],
    [GitHub=>[qw(github.com github.io)],[qw(com.github.android)],[qw(github)]],
    [TikTok=>[qw(tiktok.com)],[qw(com.zhiliaoapp.musically com.ss.android.ugc.trill)],[qw(tiktok)]],
    [Twitch=>[qw(twitch.tv)],[qw(tv.twitch.android.app)],[qw(twitch)]],
    [Bluesky=>[qw(bsky.app)],[qw(xyz.blueskyweb.app)],[qw(bluesky bsky)]],
    [Mastodon=>[qw(mastodon.social)],[qw(org.joinmastodon.android)],[qw(mastodon)]],
    [Pinterest=>[qw(pinterest.com pin.it)],[qw(com.pinterest)],[qw(pinterest)]],
    [Telegram=>[qw(t.me telegram.org)],[qw(org.telegram.messenger)],[qw(telegram)]],
    [WhatsApp=>[qw(whatsapp.com wa.me)],[qw(com.whatsapp)],[qw(whatsapp)]],
    [Slack=>[qw(slack.com)],[qw(com.Slack)],[qw(slack)]],
    ['Hacker News'=>[qw(news.ycombinator.com)],[],[qw(hn hackernews)]],
    [Gmail=>[qw(mail.google.com)],[qw(com.google.android.gm)],[qw(gmail)]],
    [Outlook=>[qw(outlook.live.com outlook.office.com outlook.office365.com)],[qw(com.microsoft.office.outlook)],[qw(outlook)]],
    [Google=>[],[qw(com.google.android.googlequicksearchbox com.google.android.gm.lite)],[qw(google)]],
    [Bing=>[qw(bing.com)],[qw(com.microsoft.bing)],[qw(bing)]],
    [DuckDuckGo=>[qw(duckduckgo.com)],[qw(com.duckduckgo.mobile.android)],[qw(duckduckgo ddg)]],
    ['Brave Search'=>[qw(search.brave.com)],[],[]],
    [Ecosia=>[qw(ecosia.org)],[],[]],
    [Yahoo=>[qw(search.yahoo.com)],[],[qw(yahoo)]],
    [Email=>[],[],[qw(email mail newsletter)]],
);
my (%by_host,%by_app,%by_tag);
for my $s (@SOURCES) {$by_host{$_}=$s->[0] for @{$s->[1]};$by_app{lc $_}=$s->[0] for @{$s->[2]};$by_tag{$_}=$s->[0] for @{$s->[3]}}
# The site a host belongs to: the host or the nearest of its parent domains
# that's known (m.youtube.com is YouTube); Google's search by country
# (google.co.uk); else ''.
sub analytics_known_host ($host) {
    return 'Google' if $host =~ /\A(?:[a-z]+\.)?google\.(?:com|[a-z]{2}|com?\.[a-z]{2})\z/ && $host !~ /\Amail\./;
    my @p=split /\./,$host;
    for my $i (0..$#p-1) {my $h=join '.',@p[$i..$#p];return $by_host{$h} if $by_host{$h}}
    return '';
}
# Where a view came from, as (source, via): the source groups visits (LinkedIn,
# news.example, or a tag's own word), via says how it was known ("link tagged
# ref=linkedin", "linkedin.com", "the LinkedIn app"). A tag wins over the
# referrer. The site's own pages give ('', 'own'), and nothing at all ('', '').
sub analytics_source ($referrer,$tag) {
    $tag=lc($tag//'');$tag =~ s/[^a-z0-9._-]+/-/g;$tag =~ s/\A-+|-+\z//g;
    return ($by_tag{$tag}//$tag,"link tagged ref=$tag") if length $tag && length $tag<=40;
    $referrer//='';
    if ($referrer =~ m{\Aandroid-app://([A-Za-z][A-Za-z0-9_.]{1,120})}) {
        my $app=$1;my $name=$by_app{lc $app};
        return $name ? ($name,"the $name app") : ($app,'an Android app');
    }
    return ('','') unless $referrer =~ m{\Ahttps?://([^/:?#]+)}i;
    my $host=lc $1;$host =~ s/\Awww\.//;
    return ('','') unless $host =~ /\A[a-z0-9.-]{1,200}\z/;
    my $own=lc($instance{domain}//'');$own =~ s/\Awww\.//;
    return ('','own') if $host eq $own || grep {lc($_) =~ s/\Awww\.//r eq $host} split ' ',$instance{aliases}//'';
    my $name=analytics_known_host($host);
    return (length $name ? $name : $host,$host);
}

# Robots (search engines, link previews, monitoring, scripts) and empty
# User-Agents, which aren't counted.
sub analytics_bot ($ua) { return !length($ua) || $ua =~ /bot\b|crawl|spider|slurp|preview|facebookexternalhit|headless|lighthouse|monitor|curl\/|wget\/|python-|go-http|java\//i }
# Pages of the site that are on, and articles (/blog/?post=…).
# The page address to count, or '' for anything that isn't a page of the
# site that's on (only page addresses and /blog/?post=ID are counted).
sub analytics_path ($p) {
    return '' unless ($p//'') =~ m{\A/[a-z0-9/._-]{0,150}(?:\?post=[a-z0-9-]{1,120})?\z};
    my ($path)=$p =~ m{\A([^?]*)};
    return '' if $path =~ m{\A/(?:admin|x|stats|addons|css|js|media|themes|assets)(?:/|\z)};
    my $page=(attempt {page_by_path($path)}) or return '';
    return '' unless page_enabled($page->{slug});
    return $p;
}
# /stats/hit, posted by stats.js on each public page view. It always answers
# "204 No Content" (so the visitor's browser learns nothing), and counts the
# view only if it's a POST from this site, not a robot, for a page that's on.
# The referring site is kept only if it's another site. The visitor is
# counted once a day by a hash of today's salt, their address and their
# browser; one visitor's views stop counting after 500 a day (someone
# reloading all day). Everything for one view is written in one transaction.
sub analytics_hit {
    my $ok=sub {header(204,'text/plain; charset=UTF-8',"Cache-Control: no-store\r\n");return 1};
    return $ok->() unless $method eq 'POST' && analytics_on();
    my $origin=$ENV{HTTP_ORIGIN}//'';
    return $ok->() if length $origin && !own_origin($origin);
    my $ua=substr($ENV{HTTP_USER_AGENT}//'',0,400);
    return $ok->() if analytics_bot($ua);
    my $path=analytics_path(param('p',300)) or return $ok->();
    my $width=param('w',6);$width=$width =~ /\A\d{1,5}\z/ ? 0+$width : 0;
    my ($source,$via)=analytics_source(param('r',600),param('t',40));
    my @place=analytics_place($ENV{REMOTE_ADDR}//'');
    my @agent=(analytics_browser($ua),analytics_system($ua),analytics_device($width,$ua));
    my $s=analytics_db();
    my $day=analytics_today();my $salt=analytics_salt($day);my $now=time;
    my $hash=sha256_hex($salt.'|'.($ENV{REMOTE_ADDR}//'').'|'.$ua);
    $s->begin_work;
    attempt {
        $s->do('INSERT INTO seen (day,hash,hits) VALUES (?,?,1) ON CONFLICT(day,hash) DO UPDATE SET hits=hits+1',undef,$day,$hash);
        my $hits=$s->selectrow_array('SELECT hits FROM seen WHERE day=? AND hash=?',undef,$day,$hash);
        # Someone reloading a page all day isn't counted past 500 views.
        if ($hits<=500) {
            $s->do('INSERT INTO daily (day,views,visitors) VALUES (?,1,1) ON CONFLICT(day) DO UPDATE SET views=views+1,visitors=visitors+?',undef,$day,$hits==1 ? 1 : 0);
            $s->do('INSERT INTO pages (day,path,views) VALUES (?,?,1) ON CONFLICT(day,path) DO UPDATE SET views=views+1',undef,$day,$path);
            $s->do('INSERT INTO places (day,code,country,region,city,views,visitors) VALUES (?,?,?,?,?,1,?) ON CONFLICT(day,code,region,city) DO UPDATE SET views=views+1,visitors=visitors+excluded.visitors',undef,$day,@place,$hits==1 ? 1 : 0);
            my @kinds=qw(browser system device);
            $s->do('INSERT INTO agents (day,kind,name,views) VALUES (?,?,?,1) ON CONFLICT(day,kind,name) DO UPDATE SET views=views+1',undef,$day,$kinds[$_],$agent[$_]) for 0..2;
            # The visit this view belongs to: a new one on the visitor's first
            # view today, after half an hour without one, or when they arrive
            # again from somewhere (a tagged link, another site or an app).
            my ($visit,$last)=$s->selectrow_array('SELECT visit,last FROM current WHERE day=? AND hash=?',undef,$day,$hash);
            my $was=$visit ? $s->selectrow_array('SELECT source FROM visits WHERE id=?',undef,$visit) : undef;
            if (!defined $was || $now-$last>1800 || (length $source && $source ne $was)) {
                $s->do('INSERT INTO visits (day,started,last,source,via,landing,views,code,country,region,city,browser,system,device) VALUES (?,?,?,?,?,?,0,?,?,?,?,?,?,?)',undef,
                    $day,$now,$now,$source,$via eq 'own' ? '' : $via,$path,@place,@agent);
                $visit=$s->sqlite_last_insert_rowid;
                $s->do('INSERT INTO sources (day,source,visits) VALUES (?,?,1) ON CONFLICT(day,source) DO UPDATE SET visits=visits+1',undef,$day,$source);
            }
            $s->do('INSERT INTO visit_views (visit,at,path) VALUES (?,?,?)',undef,$visit,$now,$path);
            $s->do('UPDATE visits SET views=views+1,last=? WHERE id=?',undef,$now,$visit);
            $s->do('INSERT INTO current (day,hash,visit,last) VALUES (?,?,?,?) ON CONFLICT(day,hash) DO UPDATE SET visit=excluded.visit,last=excluded.last',undef,$day,$hash,$visit,$now);
        }
        $s->commit;1;
    } or do {$s->rollback};
    return $ok->();
}

# ---- The Analytics screen (/admin/analytics/, owners only) --------------------------------
# A number with thousands separators: 12,345.
sub analytics_number ($n) { return scalar reverse(reverse($n//0) =~ s/(\d{3})(?=\d)/$1,/gr) }
# A compact list for the screen: each row on one line, its name (cut short,
# the whole of it in the tooltip), its number and a thin bar for its share.
# The first $o{show} rows (8) show; the rest wait behind "show all". A row is
# [name, number] or [name, number, html] when the name is drawn as HTML.
sub analytics_list ($rows,$total,$empty,%o) {
    return '<p class="empty-media">'.h($empty).'</p>' unless @$rows;
    my $show=$o{show}//8;
    my $row=sub ($r) {
        my ($name,$n,$html)=@$r;my $pct=$total ? 100*$n/$total : 0;
        return '<li title="'.h($name).': '.analytics_number($n).' ('.sprintf('%.0f%%',$pct).')"><span class="an-name">'.($html // h($name)).'</span><span class="an-n">'.analytics_number($n).'</span>'
            .'<svg class="an-bar" viewBox="0 0 100 4" preserveAspectRatio="none" aria-hidden="true"><rect width="100" height="4" rx="2" class="analytics-bar-bg"/><rect width="'.sprintf('%.1f',$pct).'" height="4" rx="2" class="analytics-bar"/></svg></li>';
    };
    my @rest=@$rows;my @first=splice @rest,0,$show;
    return '<ol class="an-list">'.join('',map {$row->($_)} @first).'</ol>'
        .(@rest ? '<details class="an-more"><summary>show all '.scalar(@$rows).'</summary><ol class="an-list">'.join('',map {$row->($_)} @rest).'</ol></details>' : '');
}
# A list with its heading: what's listed, and what's counted.
sub analytics_part ($what,$counted,$list) { return '<div class="an-part"><p class="an-head"><span>'.h($what).'</span><span>'.h($counted).'</span></p>'.$list.'</div>' }
# Pages as visitors know them: an article (/blog/?post=ID) by its title.
sub analytics_page_rows ($rows) {
    my @ids=map {$_->[0] =~ /\?post=([a-z0-9-]+)\z/ ? $1 : ()} @$rows;
    my %title;
    if (@ids) {
        my $found=(attempt {$db //= database();$db->selectall_arrayref('SELECT id,title FROM posts WHERE id IN ('.join(',',('?')x@ids).')',undef,@ids)}) // [];
        $title{$_->[0]}=$_->[1] for @$found;
    }
    return [map {
        my ($path,$n)=@$_;my ($id)=$path =~ /\?post=([a-z0-9-]+)\z/;
        defined $id && length($title{$id}//'') ? ["$title{$id} ($path)",$n,h($title{$id}).' <span class="media-label">article</span>'] : [$path,$n]
    } @$rows];
}
# Views (bars) and visitors (the darker part) per day, drawn on the server.
# The views-per-day chart, drawn on the server as SVG (no chart script):
# one bar per day for views, with the visitors as a darker bar inside it.
# Each bar has a <title>, which browsers show as a tooltip.
sub analytics_chart ($days,$by) {
    # Without making entries for days that have none (reading $by->{$_}[0] would).
    my $max=1;for (@$days) {my $v=($by->{$_}//[0])->[0]//0;$max=$v if $v>$max}
    my $n=@$days;my $w=1000/$n;
    my $svg='<svg class="analytics-chart" viewBox="0 0 1000 220" preserveAspectRatio="none" role="img" aria-label="Views and visitors per day">';
    for my $i (0..$#$days) {
        my ($v,$u)=map {$_//0} @{$by->{$days->[$i]}//[]}[0,1];   # a day without visitors yet has none
        my $hv=200*$v/$max;my $hu=200*$u/$max;
        $svg.='<g><title>'.h($days->[$i]).': '.analytics_number($v).' views, '.analytics_number($u).' visitors</title>'
            .'<rect x="'.sprintf('%.1f',$i*$w+$w*0.12).'" y="'.sprintf('%.1f',210-$hv).'" width="'.sprintf('%.1f',$w*0.76).'" height="'.sprintf('%.1f',$hv).'" class="analytics-views"/>'
            .'<rect x="'.sprintf('%.1f',$i*$w+$w*0.12).'" y="'.sprintf('%.1f',210-$hu).'" width="'.sprintf('%.1f',$w*0.76).'" height="'.sprintf('%.1f',$hu).'" class="analytics-visitors"/></g>';
    }
    $svg.='<line x1="0" y1="210.5" x2="1000" y2="210.5" class="analytics-axis"/></svg>';
    return '<div class="analytics-chart-wrap">'.$svg.'<p class="analytics-chart__axis media-label"><span>'.h($days->[0]).'</span><span>'.h($days->[-1]).'</span></p></div>';
}
# The visits of the period, newest first, 25 at a time (?vp=PAGE), or only
# those that came from one place (?from=NAME; "-" for not known): each says
# when, where it came from and how that's known, the place and the device,
# and opens to its pages in order, each with its time.
sub analytics_visits_html ($s,$from,$to,$range) {
    my $page=param('vp',4);$page=1 unless $page =~ /\A[1-9]\d{0,3}\z/;
    my $only=param('from',200);my $filter=length $only;
    my @bind=($from,$to);my $where='day BETWEEN ? AND ?';
    if ($filter) {$where.=' AND source=?';push @bind,$only eq '-' ? '' : $only}
    my $rows=$s->selectall_arrayref("SELECT * FROM visits WHERE $where ORDER BY id DESC LIMIT 26 OFFSET ".(($page-1)*25),{Slice=>{}},@bind);
    my $more=@$rows>25;splice @$rows,25 if $more;
    my %seen;
    if (@$rows) {
        my $ids=join ',',map {0+$_->{id}} @$rows;
        push @{$seen{$_->[0]}},[$_->[1],$_->[2]] for @{$s->selectall_arrayref("SELECT visit,at,path FROM visit_views WHERE visit IN ($ids) ORDER BY visit,at,rowid")};
    }
    my $names=$s->selectcol_arrayref('SELECT DISTINCT source FROM sources WHERE day BETWEEN ? AND ? ORDER BY source',undef,$from,$to);
    my $form='<form method="get" action="/admin/analytics/" class="analytics-filter" id="visits" data-auto-submit>'.hidden(days=>$range).'<label>Came from <select name="from"><option value="">anywhere</option>'
        .join('',map {my $v=length $_ ? $_ : '-';'<option value="'.h($v).'"'.($filter && $v eq $only ? ' selected' : '').'>'.h(length $_ ? $_ : 'not known').'</option>'} @$names)
        .'</select></label> <button class="buttonlike no-js-only" type="submit">show</button></form>';
    my $when=sub ($t) {return strftime('%e %b, %H:%M',localtime $t) =~ s/\A\s+//r};
    my $list=join '',map {
        my $v=$_;my $mins=int(($v->{last}-$v->{started})/60);
        '<li><details><summary><span class="analytics-visit__when">'.h($when->($v->{started})).'</span>'
        .'<span class="analytics-visit__from">'.h(length $v->{source} ? $v->{source} : 'not known').(length $v->{via} && $v->{via} ne $v->{source} ? ' <span class="media-label">'.h($v->{via}).'</span>' : '').'</span>'
        .'<span>'.h(analytics_place_label(@$v{qw(code country region city)})).'</span>'
        .'<span class="media-label">'.h(join ' · ',@$v{qw(device browser system)}).'</span>'
        .'<span class="media-label">'.h($v->{views}==1 ? '1 page' : "$v->{views} pages").($mins ? " · $mins min" : '').'</span></summary>'
        .'<ol class="analytics-visit__pages">'.join('',map {'<li><span class="media-label">'.h(strftime('%H:%M:%S',localtime $_->[0])).'</span> <a href="'.h($_->[1]).'" target="_blank" rel="noopener">'.h($_->[1]).'</a></li>'} @{$seen{$v->{id}}//[]}).'</ol></details></li>'
    } @$rows;
    my $at=sub ($p) {return '/admin/analytics/?days='.$range.($filter ? '&amp;from='.h(CGI::escape($only)) : '').'&amp;vp='.$p.'#visits'};
    my $pager=($page>1 || $more) ? '<p class="analytics-pager">'.($page>1 ? '<a href="'.$at->($page-1).'">newer</a>' : '').($more ? ' <a href="'.$at->($page+1).'">older</a>' : '').'</p>' : '';
    return $form.(length $list ? '<ol class="analytics-visits">'.$list.'</ol>'
        : '<p class="empty-media">'.($filter ? 'No visits from there in this period.' : 'No visits listed yet. They’re listed from BlowfishCMS 0.39.5 on, as they happen.').'</p>').$pager;
}
# A tagged link to share: a page's address with ?ref=WHERE, so every visit
# from it is counted under that name, even when the browser says nothing
# (an app, an email, a QR code). The form is a plain GET (?lp=PATH&tag=WORD).
sub analytics_link_html ($range) {
    my $reg=(attempt {page_registry()}) // {};
    my @pages=grep {defined} map {$reg->{$_->{page}}} grep {page_enabled($_->{page})} @{[attempt {nav_items()}]};
    my $want=param('lp',200);my ($page)=grep {$_->{path} eq $want} @pages;
    my $tag=lc param('tag',40);$tag =~ s/[^a-z0-9._-]+/-/g;$tag =~ s/\A-+|-+\z//g;
    my $made=$page && length $tag ? site_url().$page->{path}.'?ref='.$tag : '';
    my ($name)=analytics_source('',$tag);
    return '<p>When you post a link to the site (on LinkedIn, Steam, YouTube, in an email or a QR code), add <code>?ref=</code> and a word for where it’s posted. Visits from it are then counted under that word, from an app as from a website. The word leaves the address once the page opens, so a copied address doesn’t carry it. <code>?utm_source=</code> works too.</p>'
        .'<form method="get" action="/admin/analytics/" class="admin-form analytics-link" id="share-link">'.hidden(days=>$range)
        .'<label>Page<select name="lp">'.join('',map {'<option value="'.h($_->{path}).'"'.($page && $_->{path} eq $page->{path} ? ' selected' : '').'>'.h($_->{title}).' ('.h($_->{path}).')</option>'} @pages).'</select></label>'
        .'<label>Where you’ll post it<input name="tag" maxlength="40" value="'.h($tag).'" placeholder="linkedin" autocapitalize="none" spellcheck="false"><span class="optional">a word: linkedin, steam, youtube, newsletter…</span></label>'
        .'<button class="buttonlike" type="submit">make the link</button></form>'
        .(length $made ? '<p class="analytics-link__made"><label>Your link<input type="text" readonly value="'.h($made).'"></label><span class="optional">Visits from it are counted as “'.h($name).'”.</span></p>' : '');
}
# The Analytics screen (/admin/analytics/, owners only, in the comments
# service with its own CSRF cookie). Actions: turn Analytics off (makes the
# analytics-off file) or on. The screen: the period (7, 30, 90 or 365 days),
# the totals and the change on the period before, the chart, then the top
# pages, referring sites, browsers, systems, devices, places and countries,
# and how the numbers are made.
sub analytics_admin {
    require_admin(0,1) or return;
    unless (comments_enabled()) {admin_page('Analytics',section=>'analytics');window('analytics','<p>Analytics isn’t set up on the server yet.</p>');end_page();return}
    attempt {csrf_setup(comments_secret('csrf'),'bf_analytics_csrf','/admin/analytics/');1} or do {header(403,'text/plain; charset=UTF-8');print h(clean_error($@));return};
    my $message=param('notice',2000);
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',20);my $off="$cdata/analytics-off";
            if ($action eq 'analytics_off') {open my $fh,'>',$off or die "Analytics couldn’t be turned off. Try again.\n";close $fh;redirect('/admin/analytics/?notice='.CGI::escape('Analytics is off. Nothing is counted, and public pages no longer load its script. The numbers so far are kept.'))}
            if ($action eq 'analytics_on') {unlink $off;redirect('/admin/analytics/?notice='.CGI::escape('Analytics is on. Visits are counted from now on.'))}
            die "Choose an action.\n";
        } or $message=failed_action($@);
    }
    my $on=analytics_on();
    my $range=param('days',3);$range=30 unless $range =~ /\A(?:7|30|90|365)\z/;
    my $s=analytics_db();
    my $from=strftime('%Y-%m-%d',localtime(time-($range-1)*86400));my $to=analytics_today();
    my @days=map {strftime('%Y-%m-%d',localtime(time-$_*86400))} reverse 0..$range-1;
    my %by=map {($_->[0]=>[$_->[1],$_->[2]])} @{$s->selectall_arrayref('SELECT day,views,visitors FROM daily WHERE day BETWEEN ? AND ?',undef,$from,$to)};
    my ($views,$visitors)=(0,0);for (values %by) {$views+=$_->[0];$visitors+=$_->[1]}
    my $prev_from=strftime('%Y-%m-%d',localtime(time-(2*$range-1)*86400));my $prev_to=strftime('%Y-%m-%d',localtime(time-$range*86400));
    my ($pv)=$s->selectrow_array('SELECT coalesce(sum(views),0) FROM daily WHERE day BETWEEN ? AND ?',undef,$prev_from,$prev_to);
    my $top=sub ($sql,$limit=10) {$s->selectall_arrayref($sql." LIMIT $limit",undef,$from,$to)};
    my $pages=analytics_page_rows($top->('SELECT path,sum(views) v FROM pages WHERE day BETWEEN ? AND ? GROUP BY path ORDER BY v DESC',50));
    # Where visits came from, counted once each, when they arrived (0.39.5).
    my $sources=$top->('SELECT source,sum(visits) v FROM sources WHERE day BETWEEN ? AND ? GROUP BY source ORDER BY v DESC',50);
    my ($visit_count)=$s->selectrow_array('SELECT coalesce(sum(visits),0) FROM sources WHERE day BETWEEN ? AND ?',undef,$from,$to);
    # Before that, views per referring site (the site's own pages made "not said").
    my $refs=@$sources ? [] : $top->('SELECT host,sum(views) v FROM refs WHERE day BETWEEN ? AND ? GROUP BY host ORDER BY v DESC',50);
    my $direct=$views;$direct-=$_->[1] for @$refs;
    my %agents;
    for my $kind (qw(browser system device)) {$agents{$kind}=$s->selectall_arrayref("SELECT name,sum(views) v FROM agents WHERE kind=? AND day BETWEEN ? AND ? GROUP BY name ORDER BY v DESC LIMIT 20",undef,$kind,$from,$to)}
    my $places=[map {[analytics_place_label(@$_[0..3]),$_->[4]]} @{$top->('SELECT code,country,region,city,sum(views) v FROM places WHERE day BETWEEN ? AND ? GROUP BY code,region,city ORDER BY v DESC',100)}];
    my $countries=[map {[length $_->[0] ? $_->[1] : 'unknown',$_->[2]]} @{$top->('SELECT code,max(country),sum(views) v FROM places WHERE day BETWEEN ? AND ? GROUP BY code ORDER BY v DESC',100)}];
    my $placed=$s->selectrow_array('SELECT coalesce(sum(views),0) FROM places WHERE day BETWEEN ? AND ?',undef,$from,$to);
    my $have_db=-s analytics_places_file();
    admin_page('Analytics',section=>'analytics',notice=>$message,
        intro=>'Who visits, where they came from, and what they look at. Only owners see this: no cookies, and no addresses kept.',
        actions=>join('',map {'<a class="buttonlike'.($_->[0]==$range ? ' is-primary' : '').'" href="/admin/analytics/?days='.$_->[0].'"'.($_->[0]==$range ? ' aria-current="true"' : '').'>'.$_->[1].'</a>'} [7,'7 days'],[30,'30 days'],[90,'90 days'],[365,'a year']));
    print '<p class="panel-note admin-notice">Analytics is off: nothing is being counted. Turn it on under <a href="#more">more</a>, at the foot of this page.</p>' unless $on;
    # The numbers and the chart, in one panel.
    my $change=$pv ? sprintf('%+.0f%% on the %d days before',100*($views-$pv)/$pv,$range) : 'nothing to compare with yet';
    my $card=sub ($label,$value,$note) {'<div class="analytics-card"><span class="media-label">'.h($label).'</span><strong>'.$value.'</strong>'.(length $note ? '<span class="media-label">'.h($note).'</span>' : '').'</div>'};
    my $cards='<div class="analytics-cards">'.$card->('Page views',analytics_number($views),$change).$card->('Visitors',analytics_number($visitors),'counted once a day')
        .$card->('Visits',analytics_number($visit_count),'').$card->('Pages per visitor',$visitors ? sprintf('%.1f',$views/$visitors) : '–','').'</div>';
    window("the last $range days",$cards.($views ? analytics_chart(\@days,\%by).'<p class="media-label analytics-legend"><span class="analytics-key analytics-key--views"></span> views <span class="analytics-key analytics-key--visitors"></span> visitors</p>'
        : '<p class="empty-media">'.($on ? 'No visits counted yet. Visits are counted from now on, on pages that are on.' : 'No visits counted.').'</p>'));
    # Four panels, two by two: pages, where visits came from, where visitors
    # are, and what they use. Each shows its first rows; "show all" the rest.
    print '<div class="analytics-grid">';
    window('pages',analytics_part('Page','views',analytics_list($pages,$views,'No pages viewed yet.')));
    window('came from',@$sources
        ? analytics_part('From','visits',analytics_list([map {[length $_->[0] ? $_->[0] : 'not known',$_->[1]]} @$sources],$visit_count,'Nothing yet.'))
            .((grep {!length $_->[0]} @$sources) ? '<p class="media-label an-note">Not known: the browser didn’t say (an app, an email, a chat, a bookmark, a QR code). <a href="#share-link">Tag your links</a> to know those too.</p>' : '')
        : analytics_part('Site','views',analytics_list([@$refs,($direct>0 ? ['direct, or not said',$direct] : ())],$views,'Nothing yet.')));
    my $no_db=$have_db ? '' : '<p class="panel-note">Places appear once the server has fetched the city database, which it does each night (<code>doas blowfishctl places</code> fetches it now).</p>';
    window('where',$no_db.'<div class="an-cols">'.analytics_part('Country','views',analytics_list($countries,$placed,'No countries yet.',show=>6))
        .analytics_part('Place','views',analytics_list($places,$placed,'No places yet.',show=>6)).'</div>'
        .($placed<$views ? '<p class="media-label an-note">Views from before places were looked up aren’t here.</p>' : ''));
    window('devices','<div class="an-cols an-cols--3">'.join('',map {analytics_part(@$_[0,1],analytics_list($agents{$_->[2]},$views,'Nothing yet.',show=>5))} ['Device','views','device'],['Browser','views','browser'],['System','views','system']).'</div>');
    print '</div>';
    window('visits',analytics_visits_html($s,$from,$to,$range));
    # Less often needed, folded away: tagged links, how the numbers are made, and the switch.
    my $making=length(param('lp',200)) || length(param('tag',40));
    window('more','<details class="an-fold" id="more"'.($making ? ' open' : '').'><summary>Make a tagged link to share</summary>'.analytics_link_html($range).'</details>'
        .'<details class="an-fold"><summary>About these numbers</summary><ul class="mail-steps"><li>A view is counted when a page opens in a browser with JavaScript; search engines’ and other robots’ visits aren’t counted.</li>'
        .'<li>A visitor is counted once a day: from a hash of their address and browser, made with a random value that’s thrown away at the end of the day. No cookies are set and no address is stored, so a visitor can’t be followed from one day to the next.</li>'
        .'<li>A visit is one visitor’s pages, in order, until half an hour passes without one or they arrive again from somewhere else. Visits are listed with their pages for 90 days; the numbers are kept for two years.</li>'
        .'<li>Where a visit came from is what the visitor’s browser said (the site or app before), or the word of a tagged link (<code>?ref=linkedin</code>), which wins. Links opened from apps, emails, chats, PDFs, bookmarks and QR codes often say nothing: those are “not known” unless their link was tagged.</li>'
        .'<li>A visitor’s place (city, region and country) is looked up from their address in a database on this server, and only the place is kept. It’s a good guess, not a fact: phones, company networks and VPNs often show up as the nearest big city, or where their provider is. <a href="https://db-ip.com">IP Geolocation by DB-IP</a>.</li></ul></details>'
        .'<details class="an-fold"'.($on ? '' : ' open').'><summary>'.($on ? 'Turn Analytics off, or count your own visits' : 'Turn Analytics on').'</summary>'
        .'<p class="analytics-self" data-analytics-self hidden><button type="button" class="switch" aria-pressed="false"><span class="switch__track" aria-hidden="true"></span>count my visits from this browser</button></p>'
        .'<form method="post" action="/admin/analytics/" class="analytics-switch">'.hidden(csrf=>$csrf,action=>$on ? 'analytics_off' : 'analytics_on')
        .'<button type="submit" class="buttonlike'.($on ? '' : ' is-primary').'">'.($on ? 'turn Analytics off' : 'turn Analytics on').'</button> <span class="media-label">'
        .($on ? 'Off stops the counting and takes the script off public pages; the numbers so far are kept.' : 'On adds a small script to public pages that counts visits as described above.').'</span></form></details>');
    end_page();
}

1;