repository

BlowfishCMS

A small content management system for OpenBSD

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

236 lines · 16.5 KB · download this file

package BlowfishCMS;
# Search and sharing: robots.txt, the tags search engines and link previews
# read (robots, Open Graph, structured data), site verification, redirects
# from old page addresses, and the admin screen for all of it (kind=search).
use v5.36;
use utf8;
use JSON::PP ();
use Encode qw(decode encode);
our ($base,$data,$store,$db,$q,$method,$csrf,$admin,%instance);

# The search settings and their defaults: listed by search engines, the
# site belongs to a person, English, no verification codes, no share picture.
sub seo_setting_defaults {
    return (search_visible=>'1',entity_type=>'person',language=>'en',google_verification=>'',bing_verification=>'',share_image=>'');
}
# The redirects table: an old address and where it now goes.
sub ensure_seo_tables {
    $db->do('CREATE TABLE IF NOT EXISTS redirects (from_path TEXT PRIMARY KEY, to_path TEXT NOT NULL, created_at TEXT NOT NULL)');
}
# Whether search engines are invited to list the site.
sub search_visible { return setting('search_visible') eq '1' }

# ---- robots.txt -------------------------------------------------------------
# /robots.txt, the file search engines read first: either "everything but
# the admin and the site's internal addresses (and what add-ons ask)", or
# "nothing" while the site is hidden. It always names the sitemap.
sub robots_txt {
    my $txt="User-agent: *\n";
    if (search_visible()) {
        $txt.="Allow: /\nDisallow: /admin\nDisallow: /contact/send\nDisallow: /talk/\nDisallow: /download/\nDisallow: /stats/\n";
        $txt.="Disallow: $_\n" for grep {m{\A/\S*\z}} addon_robots();
    }
    else {$txt.="Disallow: /\n"}
    return $txt."\nSitemap: ".site_url()."/sitemap.xml\n";
}

# ---- Tags in <head> ---------------------------------------------------------
# Structured data as JSON-LD. "<" is escaped so the data can't end the script element.
sub json_ld ($data) {
    my $json=JSON::PP->new->canonical->ascii->encode({'@context'=>'https://schema.org',%$data});
    $json =~ s/</\\u003c/g;
    return '<script type="application/ld+json">'.$json.'</script>';
}
# Who the site belongs to: a person (the author) or an organisation.
# Who the site belongs to, as structured data: a Person or an Organization,
# with a logo (organisations) or picture.
sub site_entity {
    my $org=setting('entity_type') eq 'organization';
    my $name=length setting('author') ? setting('author') : setting('site_title');
    my %e=('@type'=>$org ? 'Organization' : 'Person',name=>$name,url=>site_url().'/');
    my $logo=$org && length logo_url() ? logo_url() : favicon_large();
    $e{$org ? 'logo' : 'image'}=site_url().$logo if length $logo;
    return \%e;
}
# The site's share picture's address, if one is set.
sub share_image_url { my $id=setting('share_image');return $id =~ /\A[a-f0-9]{12}\z/ ? "/media/site/share-$id.jpg" : '' }
# Everything for <head> after the title: robots, verification, Open Graph,
# Twitter cards and structured data. $meta as start_page takes it, plus
# article (a post record) for articles and jsonld (more structured data).
# The search and sharing tags in every public page's <head>:
#   - noindex when the site or this page is hidden from search engines;
#   - on the home page, the Google and Bing verification codes;
#   - Open Graph tags (og:...), which chat apps and social sites read for
#     link previews: the title, address, description, language, picture;
#   - for an article, its dates and a BlogPosting in structured data; on the
#     home page, a WebSite; plus any structured data the page passes.
sub seo_head ($title,$path,$description,$meta) {
    my $url=site_url();my $site=setting('site_title');my $html='';
    my $page=$meta->{page};
    $html.='<meta name="robots" content="noindex">' if !search_visible() || ($page && $page->{noindex}) || $meta->{noindex};
    if ($path eq '/') {
        $html.='<meta name="google-site-verification" content="'.h(setting('google_verification')).'">' if length setting('google_verification');
        $html.='<meta name="msvalidate.01" content="'.h(setting('bing_verification')).'">' if length setting('bing_verification');
    }
    my $article=$meta->{article};
    my $image=$meta->{image} || share_image_url();
    $html.='<meta property="og:site_name" content="'.h($site).'"><meta property="og:type" content="'.($article?'article':'website').'">'
        .'<meta property="og:title" content="'.h($title).'"><meta property="og:url" content="'.h($url.$path).'">';
    $html.='<meta property="og:description" content="'.h($description).'">' if length $description;
    $html.='<meta property="og:locale" content="'.h(setting('language') =~ s/-/_/r).'">';
    $html.=length $image ? '<meta property="og:image" content="'.h($url.$image).'"><meta name="twitter:card" content="summary_large_image">' : '<meta name="twitter:card" content="summary">';
    if ($article) {
        $html.='<meta property="article:published_time" content="'.h($article->{published_at}).'">';
        $html.='<meta property="article:modified_time" content="'.h($article->{updated_at}).'">' if $article->{updated_at};
        my %a=('@type'=>'BlogPosting',headline=>$article->{title},url=>$url.$path,mainEntityOfPage=>$url.$path,
            datePublished=>$article->{published_at},author=>site_entity(),publisher=>site_entity());
        $a{dateModified}=$article->{updated_at} if $article->{updated_at};
        $a{image}=$url.$image if length $image;
        $a{description}=$description if length $description;
        $a{inLanguage}=setting('language');
        $html.=json_ld(\%a);
    }
    elsif ($path eq '/') {
        $html.=json_ld({'@type'=>'WebSite',name=>$site,url=>"$url/",inLanguage=>setting('language'),
            (length setting('description') ? (description=>setting('description')) : ()),publisher=>site_entity()});
    }
    $html.=json_ld($_) for @{$meta->{jsonld}//[]};
    return $html;
}

# ---- Redirects ----------------------------------------------------------------
# When a page's address changes, the old one answers with a permanent redirect
# so links and search results keep working. Chains are collapsed.
# Records that $from now goes to $to. Chains are collapsed: anything that
# went to $from now goes straight to $to, and a redirect away from $to (which
# is a real page again) is dropped.
sub redirect_record ($from,$to) {
    return if $from eq $to;
    ensure_seo_tables();
    $db->do('DELETE FROM redirects WHERE from_path=?',undef,$to);
    $db->do('UPDATE redirects SET to_path=? WHERE to_path=?',undef,$to,$from);
    $db->do('INSERT INTO redirects(from_path,to_path,created_at) VALUES (?,?,?) ON CONFLICT(from_path) DO UPDATE SET to_path=excluded.to_path,created_at=excluded.created_at',undef,$from,$to,now());
}
# A page now lives at $path: an old redirect from there would never be used.
sub redirect_forget_from ($path) { attempt {$db->do('DELETE FROM redirects WHERE from_path=?',undef,$path)} }
# Drops redirects to an address that's no longer a page.
sub redirect_forget_to ($path) { attempt {$db->do('DELETE FROM redirects WHERE to_path=?',undef,$path)} }
# Where an old address now goes, or undef.
sub redirect_lookup ($path) {
    return attempt {$db->selectrow_array('SELECT to_path FROM redirects WHERE from_path=?',undef,$path)};
}
# Old addresses that redirects may start from: /name/.
sub redirect_path_ok ($p) { return $p =~ m{\A/[a-z0-9][a-z0-9-]{0,39}/\z} }

# ---- The admin screen (kind=search) -------------------------------------------
# A verification code, or the whole <meta> tag the search engine gives you.
# A search engine's verification code from what was pasted: the code itself,
# or the whole <meta> tag they give you (only its content is kept).
sub verification_value ($v,$label) {
    if ($v =~ /</) {
        # A pasted <meta> tag: keep only its content.
        my ($code)=$v =~ /\A\s*<meta\b[^>]*\bcontent\s*=\s*["']([^"'<>]*)["'][^>]*>\s*\z/i;
        $v=$code // die "$label: paste the code, or the whole <meta> tag exactly as given.\n";
    }
    $v =~ s/^\s+|\s+$//g;
    die "$label: paste the code (letters, numbers, - and _), or the whole <meta> tag.\n" if length $v && $v !~ /\A[A-Za-z0-9_-]{6,128}\z/;
    return $v;
}
# Makes the share picture from an upload: at least 600 px wide, cropped to
# the middle at 1200 × 630 (the shape link previews use), saved as JPEG
# under a new name (so caches pick up the change). Returns its id.
sub share_image_save ($fh) {
    die "Choose a PNG, JPEG or WebP picture.\n" unless $fh;
    binmode $fh;seek($fh,0,0);my $bytes='';
    while (read($fh,my $part,65536)) {$bytes.=$part;die "The picture must be 30 MB or smaller.\n" if length($bytes)>30*1048576}
    my $image=decode_image($bytes);my ($w,$h)=$image->getBounds;
    die "Use a picture at least 600 pixels wide.\n" if $w<600;
    # 1200×630 (the shape link previews use), cropped to the middle.
    my ($tw,$th)=(1200,630);my $scale=($w/$h > $tw/$th) ? $h/$th : $w/$tw;
    my ($sw,$sh)=(int($tw*$scale),int($th*$scale));
    my $out=GD::Image->newTrueColor($tw,$th);
    $out->copyResampled($image,0,0,int(($w-$sw)/2),int(($h-$sh)/2),$tw,$th,$sw,$sh);
    my $dir="$store/site";mkdir $dir,0755 unless -d $dir;
    -d $dir && -w $dir or die "The media folder for site files can't be written.\n";
    my $id=substr(random_id(),0,12);my $path="$dir/share-$id.jpg";
    open my $out_fh,'>:raw',"$path.tmp" or die "Cannot save the picture.\n";print {$out_fh} $out->jpeg(85);
    close $out_fh or do {unlink "$path.tmp";die "Cannot save the picture.\n"};
    rename "$path.tmp",$path or die "Cannot save the picture.\n";chmod 0644,$path;
    return $id;
}
# Deletes a share picture file.
sub share_image_remove ($id) { unlink "$store/site/share-$id.jpg" if ($id//'') =~ /\A[a-f0-9]{12}\z/ }

# Search & sharing (owners): the search engine settings (visible, owner,
# language, verification codes), a check of every page's title and
# description lengths, and the redirects (list, add, remove).
sub search_admin {
    ensure_seo_tables();
    my $message=param('notice',2000);my $fetch=fetch_request();
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',30);
            if ($action eq 'search_save') {
                my %v=(search_visible=>(param('search_visible',1) eq '1' ? '1' : '0'),entity_type=>param('entity_type',20),language=>param('language',20));
                die "Choose a person or an organisation.\n" unless $v{entity_type} =~ /\A(?:person|organization)\z/;
                die "Language: a code such as en, fr or pt-BR.\n" unless $v{language} =~ /\A[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*\z/;
                $v{google_verification}=verification_value(param('google_verification',600),'Google');
                $v{bing_verification}=verification_value(param('bing_verification',600),'Bing');
                setting_save(%v);
                json_response({ok=>JSON::PP::true}) if $fetch;
                redirect('/admin/?kind=search&notice=Saved.');
            }
            if ($action eq 'redirect_add') {
                my ($from,$to)=(param('from',60),param('to',300));
                $from="/$from" unless $from =~ m{\A/};$from.='/' unless $from =~ m{/\z};
                die "Old address: a page address such as /old-name/.\n" unless redirect_path_ok($from);
                die "A page already uses $from. Delete or rename that page first.\n" if page_by_path($from);
                die "New address: a path on this site such as /new-name/, or a full https:// address.\n" unless $to =~ m{\A/(?!/)\S*\z} || $to =~ m{\Ahttps://[^\s/]+\.[^\s]*\z};
                die "The old and new addresses are the same.\n" if $from eq $to;
                redirect_record($from,$to);
                redirect('/admin/?kind=search&notice='.CGI::escape("$from now redirects to $to.").'#redirects');
            }
            if ($action eq 'redirect_delete') {
                $db->do('DELETE FROM redirects WHERE from_path=?',undef,param('from',60));
                redirect('/admin/?kind=search&notice=Redirect%20removed.#redirects');
            }
            die "Choose an action.\n";
        } or do {
            $message=failed_action($@);
            json_response({ok=>JSON::PP::false,message=>$message},400) if $fetch;
        };
    }
    admin_page('Search & sharing',section=>'search',notice=>$message,save=>['save','All changes saved'],
        intro=>'How search engines find and list your site. The site name and description are under <a href="/admin/?kind=settings">Site</a>, the share picture under <a href="/admin/?kind=branding#share">Look</a>; each page’s title and description are in its page settings.');
    print '<form id="bulk-edit" method="post" action="/admin/">'.fields('search_save','search').'</form>';
    my $f='<div class="admin-form">';
    $f.=switch_field('search_visible','Let search engines list this site',search_visible(),form=>'bulk-edit',hint=>'Turn off while you build the site. Search engines are then asked not to list any page.');
    $f.='<div class="theme-editor__grid"><label>This site belongs to<select form="bulk-edit" name="entity_type">'
        .join('',map {'<option value="'.$_->[0].'"'.(setting('entity_type') eq $_->[0]?' selected':'').'>'.$_->[1].'</option>'} [person=>'a person'],[organization=>'an organisation or business'])
        .'</select><span class="optional">Search engines show it as the site’s owner, named after the Author setting.</span></label>';
    $f.='<label>Language<input form="bulk-edit" name="language" value="'.h(setting('language')).'" maxlength="20" required pattern="[a-z]{2,3}(-[A-Za-z0-9]{2,8})*"><span class="optional">The language pages are written in: en, fr, de, pt-BR…</span></label></div>';
    $f.='<div class="theme-editor__grid"><label>Google Search Console code<input form="bulk-edit" name="google_verification" value="'.h(setting('google_verification')).'" maxlength="600"><span class="optional">From Search Console’s “HTML tag” method. Pasting the whole tag works too.</span></label>';
    $f.='<label>Bing Webmaster Tools code<input form="bulk-edit" name="bing_verification" value="'.h(setting('bing_verification')).'" maxlength="600"><span class="optional">From Bing’s “meta tag” method.</span></label></div>';
    $f.='<p class="media-label">Your sitemap is at <a href="/sitemap.xml" target="_blank" rel="noopener">'.h(site_url()).'/sitemap.xml</a>. Give that address to Search Console and Bing after verifying.</p></div>';
    window('search engines',$f);
    # A quick check of every page.
    my $c='<table class="seo-table"><thead><tr><th>Page</th><th>Title</th><th>Description</th><th>Search</th></tr></thead><tbody>';
    for my $p (@{all_pages()}) {
        my $tl=length $p->{title};my $dl=length $p->{description};
        my $title_note=$tl>65 ? 'long ('.$tl.' characters; search results show about 60)' : 'ok';
        my $desc_note=!$dl ? ($p->{path} eq '/' && length setting('description') ? 'uses the site description' : 'missing') : $dl<50 ? 'short ('.$dl.' characters)' : $dl>160 ? 'long ('.$dl.' characters; about 155 show)' : 'ok';
        $c.='<tr><td><a href="/admin/?kind=page&amp;page='.h($p->{slug}).'">'.h($p->{nav_label}).'</a> <span class="media-label">'.h($p->{path}).'</span></td>'
            .'<td class="'.($title_note eq 'ok'?'':'is-warn').'">'.h($title_note).'</td><td class="'.($desc_note eq 'ok' || $desc_note =~ /^uses/?'':'is-warn').'">'.h($desc_note).'</td>'
            .'<td>'.(!search_visible() ? 'whole site hidden' : $p->{noindex} ? 'hidden' : 'listed').'</td></tr>';
    }
    window('page check',$c.'</tbody></table><p class="media-label">Change a page’s title, description or search setting in its page settings.</p>');
    my $r=$db->selectall_arrayref('SELECT * FROM redirects ORDER BY created_at DESC',{Slice=>{}});
    my $rh='<div id="redirects">'.admin_list([map {admin_row(title=>$_->{from_path},meta=>['goes to <a href="'.h($_->{to_path}).'" target="_blank" rel="noopener">'.h($_->{to_path}).'</a>'],
        menu=>'<form method="post" action="/admin/" class="delete-form" data-confirm="Remove this redirect? Links to '.h($_->{from_path}).' will stop working.">'.fields('redirect_delete','search').hidden(from=>$_->{from_path}).'<button class="text-button danger">remove</button></form>')} @$r],
        empty=>'No redirects yet. They’re added automatically when you change a page’s address.');
    $rh.='<form method="post" action="/admin/" class="admin-form">'.fields('redirect_add','search').'<div class="theme-editor__grid"><label>Old address<input name="from" maxlength="60" placeholder="/old-name/" required></label><label>Goes to<input name="to" maxlength="300" placeholder="/new-name/" required></label></div><button class="buttonlike" type="submit">add redirect</button></form></div>';
    window('redirects',$rh);
    end_page();
}

1;