BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
377 lines · 26.7 KB · download this file
package BlowfishCMS;
# Library items: what every library shares. Articles, pictures, music,
# videos, files and pages' Comments and sharing blocks (and any library added
# later, by adding it to item_kinds) can be tagged, liked, commented on and
# shared, with one copy of the code.
#
# item_kinds each kind: its label, the address of an item's page,
# and how to find a public item. An item's reference in
# the comments database (comments.post_id, likes.post_id)
# is its bare id for articles and KIND:ID for the others
# (picture:ID, track:ID, video:ID, file:ID, page:ID).
# tags item_tags in the catalogue: (kind, item, tag). Tags are
# lowercase letters, digits and dashes (#tech is "tech").
# /tags/ lists them; /tags/TAG/ shows everything tagged.
# item pages /picture/ID/, /track/ID/, /video/ID/ (articles stay at
# /blog/?post=ID): the item, its tags, likes, sharing and
# comments.
# likes, comments /talk/like and /talk/comment, in the comments service,
# for any item (comments_db, spam traps, limits and
# reserved names as before). They can be turned off per
# library (the talk_KIND setting, on its screen) and per
# item (talk_off on uploads and posts).
use v5.36;
use utf8;
use POSIX qw(strftime);
use Encode qw(encode);
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);
# ---- Kinds -----------------------------------------------------------------------------
# Each kind of item: ref (its prefix in the comments database; '' for
# articles), label and one (its names), path (a function giving an item's
# public address) and, for pages, the shape of its id (a block id is 16 hex
# characters, the others 32).
sub item_kinds {
return {
blog=>{ref=>'',label=>'Articles',one=>'article',path=>sub ($id) {"/blog/?post=$id"}},
photography=>{ref=>'picture',label=>'Pictures',one=>'picture',path=>sub ($id) {"/picture/$id/"}},
music=>{ref=>'track',label=>'Music',one=>'track',path=>sub ($id) {"/track/$id/"}},
video=>{ref=>'video',label=>'Videos',one=>'video',path=>sub ($id) {"/video/$id/"}},
file=>{ref=>'file',label=>'Files',one=>'file',path=>sub ($id) {"/file/$id/"}},
# A page's Comments and sharing block: the item is the block, so
# its comments stay when the page moves; id is the block's.
page=>{ref=>'page',label=>'Pages',one=>'page',id=>qr/\A[a-f0-9]{16}\z/,path=>sub ($id) {talk_block_path($id)}},
};
}
# The kinds in the order lists and the tag pages show them.
sub item_kind_order { return qw(blog photography music video file page) }
# The address of the page carrying a Comments and sharing block ('/' if none).
sub talk_block_path ($id) { return (attempt {$db->selectrow_array("SELECT p.path FROM page_blocks b JOIN pages p ON p.slug=b.page WHERE b.id=? AND b.type='talk'",undef,$id)}) // '/' }
# An item's reference in the comments database: picture:ID, track:ID ...,
# or just the id for an article.
sub item_ref ($kind,$id) { my $k=item_kinds()->{$kind} or return '';return length $k->{ref} ? "$k->{ref}:$id" : $id }
# The other way round: a reference back to (kind, id), or () if it isn't one.
sub item_from_ref ($ref) {
return ('blog',$1) if ($ref//'') =~ /\A([a-f0-9]{32})\z/;
my ($r,$id)=($ref//'') =~ /\A([a-z]+):([a-f0-9]{32}|[a-f0-9]{16})\z/ or return ();
my ($kind)=grep {item_kinds()->{$_}{ref} eq $r} keys %{item_kinds()};
return $kind ? ($kind,$id) : ();
}
# An item's public address.
sub item_path ($item) { return item_kinds()->{$item->{kind}}{path}->($item->{id}) }
# An item as the shared code sees it: kind, id, title, description, image
# (for link previews), talk_off, and its row. Only public ones, unless %o all.
# Looks an item up and returns what the shared code needs about it. Only
# public items unless %o all: published articles while Blog is on, pages
# that are on, and pictures not kept out of galleries. The image is what
# link previews show: an article's first picture, the picture itself, a
# video's poster or a track's artwork.
sub item_find ($kind,$id,%o) {
my $k=item_kinds()->{$kind//''} or return undef;
return undef unless ($id//'') =~ ($k->{id} // qr/\A[a-f0-9]{32}\z/);
if ($kind eq 'page') {
my $p=$db->selectrow_hashref("SELECT p.* FROM page_blocks b JOIN pages p ON p.slug=b.page WHERE b.id=? AND b.type='talk'",undef,$id) or return undef;
return undef unless $o{all} || page_enabled($p->{slug});
return {kind=>$kind,id=>$id,title=>$p->{title},description=>$p->{description}//'',image=>'',talk_off=>0,row=>$p};
}
if ($kind eq 'blog') {
my $p=$db->selectrow_hashref('SELECT * FROM posts WHERE id=?'.($o{all} ? '' : ' AND published_at IS NOT NULL'),undef,$id) or return undef;
return undef unless $o{all} || page_enabled('blog');
my ($image)=($p->{body}//'') =~ m{!\[[^\]]*\]\((/media/[^)\s]+)};
return {kind=>$kind,id=>$id,title=>$p->{title},description=>post_excerpt($p->{body}),image=>$image//'',talk_off=>$p->{talk_off}//0,row=>$p};
}
my $u=$db->selectrow_hashref('SELECT * FROM uploads WHERE id=? AND kind=?',undef,$id,$kind) or return undef;
# Pictures kept out of galleries (a logo, a portrait) aren't shown as items.
return undef if !$o{all} && $kind eq 'photography' && ($u->{gallery_hidden} || folder_hidden($u->{folder}//''));
my $image=$kind eq 'photography' ? media_url($u) : $kind eq 'video' && $u->{thumbnail} ? media_url($u,1) : $kind eq 'music' && $u->{artwork} ? "/media/artwork/$u->{artwork}" : '';
return {kind=>$kind,id=>$id,title=>$u->{title},description=>$u->{description}//'',image=>$image,talk_off=>$u->{talk_off}//0,row=>$u};
}
# Likes and comments: on for the library (its screen) and the item.
# Likes and comments for a whole library: on unless its talk_KIND setting is 0.
sub talk_library_on ($kind) { return setting("talk_$kind") ne '0' }
# Likes and comments for one item: the comments service must be set up, its
# library's switch on, and its own switch not off.
sub item_talk_on ($item) { return comments_enabled() && talk_library_on($item->{kind}) && !$item->{talk_off} }
# ---- Tags ------------------------------------------------------------------------------
# The tags table: one row per (kind, item, tag), with an index for finding
# everything that has a tag.
sub ensure_item_tables {
$db->do('CREATE TABLE IF NOT EXISTS item_tags (kind TEXT NOT NULL, item TEXT NOT NULL, tag TEXT NOT NULL, PRIMARY KEY(kind,item,tag))');
$db->do('CREATE INDEX IF NOT EXISTS item_tags_by_tag ON item_tags(tag)');
}
# A tag in its stored form: lowercase, no leading #, anything other than
# letters, digits and dashes becomes a dash, 1-32 characters ('' otherwise).
sub tag_clean ($t) {
$t=lc($t//'');$t =~ s/\A#+//;$t =~ s/[^a-z0-9-]+/-/g;$t =~ s/\A-+|-+\z//g;
return length($t)>=1 && length($t)<=32 ? $t : '';
}
# "#tech, gaming tutorial" → (gaming, tech, tutorial); at most 20.
sub tags_parse ($text) { my %seen;my @t=grep {length && !$seen{$_}++} map {tag_clean($_)} split /[\s,]+/,($text//'');return (sort @t)[0..($#t<19 ? $#t : 19)] }
# An item's tags, sorted.
sub item_tags ($kind,$id) { return map {$_->[0]} @{(attempt {$db->selectall_arrayref('SELECT tag FROM item_tags WHERE kind=? AND item=? ORDER BY tag',undef,$kind,$id)}) // []} }
# Replaces an item's tags with those in a text ("#tech, tutorial").
sub item_tags_set ($kind,$id,$text) {
$db->do('DELETE FROM item_tags WHERE kind=? AND item=?',undef,$kind,$id);
$db->do('INSERT INTO item_tags (kind,item,tag) VALUES (?,?,?)',undef,$kind,$id,$_) for tags_parse($text);
}
# Ids of a kind's items with this tag (a hash, for filtering lists).
sub items_with_tag ($kind,$tag) { $tag=tag_clean($tag);return {map {($_->[0]=>1)} @{(attempt {$db->selectall_arrayref('SELECT item FROM item_tags WHERE kind=? AND tag=?',undef,$kind,$tag)}) // []}} }
# Keeps only the items of a list that have a tag (all of them when the tag
# is empty).
sub tag_filter ($kind,$tag,$list) {
return $list unless length tag_clean($tag);
my $has=items_with_tag($kind,$tag);return [grep {$has->{$_->{id}}} @$list];
}
# An item's tags as links to their tag pages.
sub tags_html (@tags) { return @tags ? '<p class="item-tags">'.join(' ',map {'<a href="/tags/'.h($_).'/">#'.h($_).'</a>'} @tags).'</p>' : '' }
# The block field that limits a list to one tag.
sub tag_field { return [tag=>'Only items tagged','text',40,'optional: one tag, such as tech'] }
# ---- Counts for lists ------------------------------------------------------------------------
# Likes and comments per item of a kind: (likes, comments) hashes by id.
# Likes and comments for every item of a kind, two hashes by id, in two
# queries rather than two per item. Items are matched by their reference
# prefix (picture:%); articles are the ones without a ':'.
sub talk_counts ($kind) {
my $c=comments_enabled() ? (attempt {comments_db()}) : undef or return ({},{});
my $r=item_kinds()->{$kind}{ref};my $like=length $r ? "$r:%" : '%';my $cut=length $r ? length($r)+1 : 0;
my $by=sub ($sql) {return {map {(substr($_->[0],$cut)=>$_->[1])} @{$c->selectall_arrayref($sql,undef,$like)}}};
my $not=length $r ? '' : " AND post_id NOT LIKE '%:%'";
return ($by->("SELECT post_id,count(*) FROM likes WHERE post_id LIKE ?$not GROUP BY post_id"),$by->("SELECT post_id,count(*) FROM comments WHERE hidden=0 AND post_id LIKE ?$not GROUP BY post_id"));
}
# "♥ 3 · 2 comments", shown in lists.
sub talk_stats_html ($likes,$comments) { return '<span class="post-stats">♥ '.($likes//0).' · '.($comments//0).' '.(($comments//0)==1 ? 'comment' : 'comments').'</span>' }
# ---- An item's page ---------------------------------------------------------------------------
# /picture/ID/, /track/ID/, /video/ID/: the item, its description and tags,
# then likes, sharing and comments. Not found unless the item is public.
# An item's own page: /picture/ID/, /track/ID/, /video/ID/ or /file/ID/.
# Shows the item (the picture, a player, or the file's card), its tags, then
# sharing and likes and comments. "Not found" unless the item is public.
sub item_page_route ($path) {
my ($r,$id)=$path =~ m{\A/(picture|track|video|file)/([a-f0-9]{32})/\z} or return 0;
my ($kind)=grep {item_kinds()->{$_}{ref} eq $r} keys %{item_kinds()};
my $item=item_find($kind,$id);
unless ($item) {start_page('Not found',$path,404);window('not found','<h1>Not found</h1><p>There’s nothing here. <a href="/">Home</a></p>');end_page();return 1}
my $u=$item->{row};
start_page($item->{title},$path,200,{og=>1,talk=>1,description=>(length $item->{description} ? $item->{description} : undef),image=>$item->{image},jsonld=>[item_jsonld($kind,$item->{row})]});
my $media=$kind eq 'photography' ? '<figure class="item-picture"><img src="'.h(media_url($u)).'" alt="'.h(length($u->{description}//'') ? $u->{description} : $u->{title}).'"'.($u->{width} ? ' width="'.$u->{width}.'" height="'.$u->{height}.'"' : '').' draggable="false"></figure>'
: $kind eq 'music' ? music_list_html([$u],0,page=>0) : $kind eq 'file' ? file_card_html($u,page=>0) : video_list_html([$u],0,page=>0);
my $text=$kind eq 'photography' ? '<h1>'.h($item->{title}).'</h1>'.(length $item->{description} ? '<p>'.h($item->{description}).'</p>' : '') : '';
window(item_kinds()->{$kind}{one},$text.$media.tags_html(item_tags($kind,$id)),'item-page');
item_engagement($item);
end_page();
return 1;
}
# /tags/: every tag; /tags/TAG/: everything with it, by library.
# /tags/ lists every tag with how many public items have it; /tags/TAG/
# shows everything with that tag, one panel per library. Each item is looked
# up once ($public remembers them) and only public ones count.
sub tags_page_route ($path) {
return 0 unless $path =~ m{\A/tags/(?:([a-z0-9-]{1,32})/)?\z};
my $tag=$1//'';
my %public;
my $rows=(attempt {$db->selectall_arrayref('SELECT kind,item,tag FROM item_tags'.(length $tag ? ' WHERE tag=?' : '').' ORDER BY tag',undef,length $tag ? ($tag) : ())}) // [];
my %by;for (@$rows) {my $i=$public{"$_->[0]:$_->[1]"} //= item_find($_->[0],$_->[1]) // 0;push @{$by{$_->[2]}{$_->[0]}},$i if $i}
unless (length $tag) {
start_page('Tags','/tags/',200,{description=>'Everything on the site, by tag.'});
my %n=map {my $t=$_;($t=>scalar map {@$_} values %{$by{$t}})} keys %by;
window('tags',%n ? '<p class="tag-cloud">'.join(' ',map {'<a href="/tags/'.h($_).'/">#'.h($_).' <span class="media-label">'.$n{$_}.'</span></a>'} sort keys %n).'</p>' : '<p class="empty-media">No tags yet.</p>');
end_page();return 1;
}
unless ($by{$tag}) {start_page("#$tag",$path,404);window('not found','<h1>#'.h($tag).'</h1><p>Nothing is tagged #'.h($tag).'. <a href="/tags/">All tags</a></p>');end_page();return 1}
start_page("#$tag",$path,200,{description=>"Everything tagged #$tag."});
window('tag','<h1>#'.h($tag).'</h1><p><a href="/tags/">all tags</a></p>','media-intro');
for my $kind (item_kind_order()) {
my $items=$by{$tag}{$kind} or next;my $label=lc item_kinds()->{$kind}{label};
my @rows=map {$_->{row}} @$items;
my $html=$kind eq 'blog' ? post_list_html([sort {($b->{published_at}//'') cmp ($a->{published_at}//'')} @rows])
: $kind eq 'photography' ? gallery_html(\@rows,'grid',1) : $kind eq 'music' ? music_list_html(\@rows,0) : $kind eq 'file' ? file_list_html(\@rows,brief=>1) : video_list_html(\@rows,0);
window($label,$html,$kind eq 'blog' ? 'blog-list' : '');
}
print photo_viewer_html() if $by{$tag}{photography};
end_page();
return 1;
}
# ---- Likes, sharing and comments on an item's page ---------------------------------------------
# Prints item_engagement_html.
sub item_engagement ($item) { print item_engagement_html($item) }
# Sharing, and likes and comments where they're on: two windows (an item's page, the Comments and sharing block).
# Two panels for an item's page (or a Comments and sharing block):
# share the like button and count (when likes are on), share and copy
# link buttons (shown by talk.js where the browser can do them),
# and the link itself
# comments the comments so far, any notice from the last post (?c=CODE),
# and the comment form
# The visitor's earlier username is filled in, and their own like shows as
# "liked". The form has a hidden "website" field as a trap for robots: a
# person never fills it in.
sub item_engagement_html ($item) {
my $ref=item_ref($item->{kind},$item->{id});my $url=site_url().item_path($item);
my $on=item_talk_on($item);my $c=$on ? (attempt {comments_db()}) : undef;
my $owner=visitor_owner(visitor_key());
my ($likes,$liked,$comments,$prefill)=(0,0,[],'');
if ($c) {
$likes=$c->selectrow_array('SELECT count(*) FROM likes WHERE post_id=?',undef,$ref);
$liked=$owner ? ($c->selectrow_array('SELECT 1 FROM likes WHERE post_id=? AND owner=?',undef,$ref,$owner) // 0) : 0;
$comments=$c->selectall_arrayref('SELECT id,display,body,created_at FROM comments WHERE post_id=? AND hidden=0 ORDER BY created_at, id',{Slice=>{}},$ref);
$prefill=$owner ? ($c->selectrow_array('SELECT display FROM names WHERE owner=? ORDER BY created_at DESC LIMIT 1',undef,$owner) // '') : '';
}
my $one=item_kinds()->{$item->{kind}}{one};
my $html='<div class="post-actions" id="post-actions" data-url="'.h($url).'" data-title="'.h($item->{title}).'">';
$html.='<form method="post" action="/talk/like" class="like-form">'.hidden(item=>$ref).'<button type="submit" class="buttonlike like-button" aria-pressed="'.($liked?'true':'false').'"><span aria-hidden="true">♥</span> <span class="like-label">'.($liked?'liked':'like').'</span></button><span class="like-count" aria-live="polite">'.$likes.' '.($likes==1?'like':'likes').'</span></form>' if $on;
$html.='<div class="share-tools"><button type="button" class="buttonlike" data-share hidden>share…</button><button type="button" class="buttonlike" data-copy-link hidden>copy link</button><label class="share-link">Link to this '.h($one).'<input type="url" readonly value="'.h($url).'"></label><span class="share-status" role="status"></span></div></div>';
my $out=window_html('share','',$html,body_class=>'post-actions-window');
return $out unless $on;
my $code=param('c',12);my $notice=comment_message($code);
my $count=@$comments;
$html='<h2 id="comments">'.($count ? $count.' '.($count==1?'comment':'comments') : 'Comments').'</h2>';
$html.='<p class="panel-note'.($code eq 'ok'?'':' is-error').'" role="status">'.h($notice).'</p>' if $notice;
if ($count) {
$html.='<ol class="comment-list">';
$html.='<li class="comment" id="comment-'.h($_->{id}).'"><p class="comment-meta"><strong>'.h($_->{display}).'</strong> · <time datetime="'.h($_->{created_at}).'">'.h(substr($_->{created_at},0,10)).'</time></p><div class="comment-body">'.comment_html($_->{body}).'</div></li>' for @$comments;
$html.='</ol>';
} else {$html.='<p class="empty-media">No comments yet. Start the conversation.</p>'}
$html.='<form method="post" action="/talk/comment" class="admin-form comment-form" id="comment-form">'.hidden(item=>$ref)
.'<label>Username<input name="name" maxlength="32" minlength="2" required autocomplete="nickname" value="'.h($prefill).'"></label>'
.'<p class="media-label">No account needed. The first time you use a username it is reserved for this browser, so nobody else can post as you.</p>'
.'<label>Comment<textarea name="body" rows="5" maxlength="2000" required></textarea></label>'
.'<label class="hp-field" aria-hidden="true">Leave this empty<input name="website" tabindex="-1" autocomplete="off"></label>'
.'<div class="editor-actions"><button class="buttonlike" type="submit">post comment</button><span class="comment-status" role="status"></span></div></form>';
return $out.window_html('comments','',$html,body_class=>'blog-comments');
}
# ---- /talk/like and /talk/comment (the comments service) ----------------------------------------
# The item a request is about, when it's public and open to likes and comments.
# The item a like or comment is for, if it's public and open to them.
sub talk_item { my ($kind,$id)=item_from_ref(param('item',60)) or return undef;my $i=item_find($kind,$id) or return undef;return item_talk_on($i) ? $i : undef }
# Answers a like or comment: JSON for talk.js, otherwise a redirect back to
# the item with ?c=CODE (the message to show) and an anchor to scroll to.
sub talk_reply ($item,$code,$anchor='comment-form') {
my $path=item_path($item);my $back=$path.($path =~ /\?/ ? '&' : '?')."c=$code#$anchor";
json_response({ok=>($code eq 'ok'?JSON::PP::true:JSON::PP::false),code=>$code,message=>comment_message($code),location=>$back},$code eq 'ok'?200:400) if wants_json();
redirect($back);
}
# /talk/comment (the comments service). In order: a filled-in trap field
# pretends success and stores nothing; the name and text are checked
# (Comments.pm); then, in one transaction, rate limits (3 per 5 minutes and
# 20 a day from one address, 3 per 5 minutes per browser, 300 a day in all),
# a duplicate check, and the username: the first browser to use a name keeps
# it (names.owner), so nobody else can post as them. Then the comment is
# stored.
sub talk_comment {
my $item=talk_item();
unless ($item) {header(404,'text/plain; charset=UTF-8');print 'Not found';return}
my $ref=item_ref($item->{kind},$item->{id});
return talk_reply($item,'ok') if param('website',200) ne '';
my ($name,$key)=comment_name(param('name',200));
return talk_reply($item,$key) unless defined $name;
my ($body,$problem)=comment_body(param('body',6000));
return talk_reply($item,$problem) unless defined $body;
my $c=comments_db(1) or return talk_reply($item,'unavailable');
my $owner=visitor_owner(ensure_visitor());my $ip=ip_actor();my $id=random_id();
$c->begin_work;
my $code=attempt {
return 'rate' unless rate_ok($c,'comment',[$ip,3,300],[$ip,20,86400],[$owner,3,300],['all',300,86400]);
return 'dup' if $c->selectrow_array('SELECT 1 FROM comments WHERE post_id=? AND owner=? AND body=? AND created_at>?',undef,$ref,$owner,$body,strftime('%Y-%m-%dT%H:%M:%SZ',gmtime(time-86400)));
my $claimed=$c->selectrow_array('SELECT owner FROM names WHERE name_key=?',undef,$key);
if (!defined $claimed) {$c->do('INSERT INTO names(name_key,display,owner,created_at) VALUES (?,?,?,?)',undef,$key,$name,$owner,now())}
elsif ($claimed ne $owner) {return 'taken'}
else {$c->do('UPDATE names SET display=? WHERE name_key=?',undef,$name,$key)}
$c->do('INSERT INTO comments(id,post_id,name_key,display,owner,body,ip,hidden,created_at) VALUES (?,?,?,?,?,?,?,0,?)',undef,$id,$ref,$key,$name,$owner,$body,$ip,now());
'ok';
};
if (defined $code && $code eq 'ok') {$c->commit} else {warn $@ if !defined $code;$c->rollback;$code //= 'unavailable'}
talk_reply($item,$code,$code eq 'ok'?"comment-$id":'comment-form');
}
# /talk/like: likes or un-likes an item for this browser (one like per
# browser per item), with rate limits for new likes. Answers with the new
# count for talk.js, or a redirect back.
sub talk_like {
my $item=talk_item();
unless ($item) {header(404,'text/plain; charset=UTF-8');print 'Not found';return}
my $ref=item_ref($item->{kind},$item->{id});my $back=item_path($item);
my $c=comments_db(1);
unless ($c) {json_response({ok=>JSON::PP::false,message=>comment_message('unavailable')},503) if wants_json();redirect("$back#post-actions")}
my $owner=visitor_owner(ensure_visitor());my $ip=ip_actor();my ($liked,$count);
$c->begin_work;
my $ok=attempt {
my $has=$c->selectrow_array('SELECT 1 FROM likes WHERE post_id=? AND owner=?',undef,$ref,$owner);
if ($has) {$c->do('DELETE FROM likes WHERE post_id=? AND owner=?',undef,$ref,$owner)}
else {
return 0 unless rate_ok($c,'like',[$ip,30,3600],['all',3000,86400]);
$c->do('INSERT INTO likes(post_id,owner,created_at) VALUES (?,?,?)',undef,$ref,$owner,now());
}
$liked=$has?0:1;$count=$c->selectrow_array('SELECT count(*) FROM likes WHERE post_id=?',undef,$ref);1;
};
if ($ok) {$c->commit} else {warn $@ if $@;$c->rollback}
if (wants_json()) {
json_response({ok=>JSON::PP::false,message=>'Too many likes from your network. Try again later.'},429) unless $ok;
json_response({ok=>JSON::PP::true,liked=>($liked?JSON::PP::true:JSON::PP::false),count=>0+$count});
}
redirect("$back#post-actions");
}
# ---- On each library's screen: tags, and likes and comments on or off --------------------------
# The Tags field of a library item's edit form.
sub tags_input_html ($kind,$id) { return '<label>Tags<input name="tags" maxlength="400" value="'.h(join(' ',map {"#$_"} item_tags($kind,$id))).'" placeholder="#tech #tutorial" autocapitalize="none"><span class="optional">separated by spaces or commas; they link to a page of everything with that tag</span></label>' }
# The item's own likes-and-comments switch (talk_on; the column is talk_off).
sub talk_off_input_html ($item_row) { return switch_field('talk_on','Likes and comments on this one',!$item_row->{talk_off},hint=>'While they’re on for the whole library (the switch under the list).') }
# The form under a library that switches likes and comments on or off for
# all its items.
sub talk_switch_html ($kind) {
my $on=talk_library_on($kind);my $one=item_kinds()->{$kind}{one};
return '<div class="talk-switch">'.switch_button($kind,'talk_switch','',$on,"likes and comments on $one pages",what=>"Likes and comments on $one pages").'</div>';
}
# An item's tags and its own likes-and-comments switch, from its edit form.
sub item_extras_save ($kind,$id) {
item_tags_set($kind,$id,param('tags',400)) if defined $q->param('tags');
if (defined $q->param('talk_on') || defined $q->param('talk_off')) {
my $off=defined $q->param('talk_on') ? (param('talk_on',1) eq '1' ? 0 : 1) : param('talk_off',1) eq '1' ? 1 : 0;
$db->do('UPDATE '.($kind eq 'blog' ? 'posts' : 'uploads').' SET talk_off=? WHERE id=?',undef,$off,$id);
}
}
# ---- Tag buttons for visitors -------------------------------------------------------
# Lists (gallery, music, videos, files) can offer visitors a row of tag buttons
# that show only the items with that tag, in the page, without reloading. One
# query for a kind's tags; each card carries data-tags; site.js does the rest
# (with the collection picker, if the list has one too).
sub item_tags_map ($kind) {
my %m;push @{$m{$_->[0]}},$_->[1] for @{(attempt {$db->selectall_arrayref('SELECT item,tag FROM item_tags WHERE kind=? ORDER BY tag',undef,$kind)}) // []};
return \%m;
}
# data-tags="a b c" for a card, which site.js reads to filter by tag.
sub tags_data_attr ($map,$id) { return $map ? ' data-tags="'.h(join ' ',@{$map->{$id}//[]}).'"' : '' }
# The row of tag buttons above a list: "all", then every tag its items have.
# Hidden until site.js shows it.
sub tag_buttons_html ($map,$list) {
return '' unless $map;my %n;$n{$_}++ for map {@{$map->{$_->{id}}//[]}} @$list;
return '' unless %n;
return '<div class="tag-filter" hidden role="group" aria-label="Show only items tagged"><button type="button" aria-pressed="true" data-tag="">all</button>'
.join('',map {'<button type="button" aria-pressed="false" data-tag="'.h($_).'">#'.h($_).'</button>'} sort keys %n).'</div>';
}
# The block setting that turns tag buttons on.
sub tag_buttons_field { return [tag_buttons=>'Tag buttons, so visitors can show one tag','check'] }
# ---- Structured data for an item's page -------------------------------------------------
# Structured data (schema.org VideoObject) for a video's page, which search
# engines read: name, description, upload date, addresses, poster, duration
# in ISO 8601 form (PT1H2M3S) and size.
sub item_jsonld ($kind,$u) {
return () unless $kind eq 'video';
my $abs=sub ($p) {$p =~ m{\Ahttps?://} ? $p : site_url().$p};
my %v=('@type'=>'VideoObject',name=>$u->{title},
description=>(length($u->{description}//'') ? $u->{description} : $u->{title}),
uploadDate=>$u->{created_at},contentUrl=>$abs->(media_url($u)),url=>$abs->("/video/$u->{id}/"));
$v{thumbnailUrl}=$abs->(media_url($u,1)) if $u->{thumbnail};
if (my $s=int($u->{duration}//0)) {$v{duration}=sprintf 'PT%s%s%dS',($s>=3600 ? int($s/3600).'H' : ''),($s>=60 ? int($s%3600/60).'M' : ''),$s%60}
$v{width}=0+$u->{width} if $u->{width};$v{height}=0+$u->{height} if $u->{height};
return \%v;
}
# Saves a library's likes-and-comments switch and returns the message.
sub talk_switch_save ($kind) { setting_save("talk_$kind"=>param('on',1) eq '1' ? '1' : '0');return talk_library_on($kind) ? 'Likes and comments are on.' : 'Likes and comments are off; the ones so far are kept.' }
1;