BlowfishCMS
A small content management system for OpenBSD
version 0.45.6 · ISC · 2026-12-03 · releases
474 lines · 39.1 KB · download this file
package BlowfishCMS::Addon::Course;
# Courses: free courses on the site, each written as one Markdown document
# (the format is in the README and parse_course below), shown at
# /x/course/SLUG/ (the course: its units and a dashboard), /x/course/SLUG/N/
# (week or lesson N: its checklists, assignment, self-assessment and notes),
# /x/course/SLUG/guide/ (facts, materials and the guide sections) and
# /x/course/SLUG/progress/ (progress by unit, export, import, reset).
# /x/course/ lists the published courses (as the course_list block does).
#
# Learners' progress is kept in their own browser by course.js (localStorage,
# a key per course); nothing about them reaches the server.
#
# Table: course_courses (id, slug, title, summary, source: the Markdown,
# materials: "Name | URL | words, to, match" lines, rubric: "Category |
# weight" lines, pass_mark, hours: a week, active, sort_order, created_at,
# updated_at); course_seeded (slug) remembers seed courses already added.
# Seeds: each seed/NAME.json in this folder ({"slug","title","summary",
# "hours","pass_mark","rubric","materials","source": "NAME.md"}) is added,
# published, the first time migrate runs with it, and never again.
# Blocks: course_list, course_overview. Admin: kind=x-course.
use v5.36;
use utf8;
use Encode qw(encode decode);
use File::Basename qw(dirname);
use JSON::PP ();
use Digest::SHA ();
BEGIN { no strict 'refs'; *{$_}=\&{"BlowfishCMS::$_"} for qw(h param redirect admin_page window window_html end_page start_page fields hidden failed_action random_id now attempt
render_markdown json_ld header site_url admin_row admin_list row_menu move_buttons list_order sort_order_save order_list_attrs switch_button) }
my $home_dir=dirname(__FILE__).'/..';
sub db { $BlowfishCMS::db }
sub migrate ($db) {
$db->do("CREATE TABLE IF NOT EXISTS course_courses (id TEXT PRIMARY KEY, slug TEXT NOT NULL UNIQUE, title TEXT NOT NULL, summary TEXT NOT NULL DEFAULT '', source TEXT NOT NULL DEFAULT '',
materials TEXT NOT NULL DEFAULT '', rubric TEXT NOT NULL DEFAULT '', pass_mark INTEGER NOT NULL DEFAULT 70, hours INTEGER NOT NULL DEFAULT 0, active INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)");
$db->do('CREATE TABLE IF NOT EXISTS course_seeded (slug TEXT PRIMARY KEY, at TEXT NOT NULL)');
seed($db);
}
# Courses shipped in seed/: added once each, published, at the end of the list.
sub seed ($db) {
opendir my $dh,"$home_dir/seed" or return;
for my $file (sort grep {/\A[a-z0-9-]+\.json\z/} readdir $dh) {
my $s=attempt {open my $fh,'<:raw',"$home_dir/seed/$file" or die;local $/;JSON::PP->new->utf8->decode(scalar <$fh>)} or next;
my $slug=$s->{slug}//'';next unless slug_ok($slug) && ($s->{source}//'') =~ /\A[a-z0-9-]+\.md\z/;
next if $db->selectrow_array('SELECT 1 FROM course_seeded WHERE slug=?',undef,$slug) || $db->selectrow_array('SELECT 1 FROM course_courses WHERE slug=?',undef,$slug);
my $text=attempt {open my $fh,'<:encoding(UTF-8)',"$home_dir/seed/$s->{source}" or die;local $/;scalar <$fh>} or next;
my $order=($db->selectrow_array('SELECT max(sort_order) FROM course_courses')//-1)+1;
$db->do('INSERT INTO course_courses (id,slug,title,summary,source,materials,rubric,pass_mark,hours,active,sort_order,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,1,?,?,?)',undef,
substr(random_id(),0,16),$slug,$s->{title}//$slug,$s->{summary}//'',$text,$s->{materials}//'',$s->{rubric}//'',$s->{pass_mark}//70,$s->{hours}//0,$order,now(),now());
$db->do('INSERT INTO course_seeded (slug,at) VALUES (?,?)',undef,$slug,now());
}
}
sub slug_ok ($s) { return ($s//'') =~ /\A[a-z0-9][a-z0-9-]{0,39}\z/ }
sub courses ($all=0) { return (attempt {db()->selectall_arrayref('SELECT * FROM course_courses'.($all ? '' : ' WHERE active=1').' ORDER BY sort_order,created_at',{Slice=>{}})}) // [] }
sub course_by ($col,$v) { return (attempt {db()->selectrow_hashref("SELECT * FROM course_courses WHERE $col=?",undef,$v)}) }
sub base ($c) { return "/x/course/$c->{slug}/" }
# ---- Reading a course ---------------------------------------------------------------
# A course is one Markdown document:
# # Course title the first heading, when it has no number
# **Key:** value facts, before the first section (duration…)
# # 1. Some section a guide section: Markdown, shown on the guide
# # 3. Phase I — Title a unit: a section with lessons in it
# **Weeks 1–16** (left out: the unit's weeks are counted)
# ## Week 1 — Title a lesson (Week, Lesson, Module, Session, Day,
# Class or Chapter, and its number)
# **Lectures**, **Reading**… a checklist; its "- " lines are the items
# **Assignment: Title** the assignment, until the next label;
# **Assignment:** text or in one line
# **Deliverable:** text what to hand in
# **Anything else:** text a note on the lesson (an examination…)
# Lesson numbers are their addresses, so they're unique; a repeat is left out
# with a warning.
my $LESSON=qr/\A##\s+(Week|Lesson|Module|Session|Day|Class|Chapter)\s+(\d{1,4})\s*[—–:-]\s*(.+?)\s*\z/;
sub trim ($s) { return ($s//'') =~ s/\A\s+|\s+\z//gr }
sub parse_course ($text) {
my %c=(title=>'',intro=>'',facts=>[],units=>[],guide=>[],lessons=>[],by=>{},warnings=>[]);
my (@sections,$sec,$lesson,$group,$mode);
for my $line (split /\r?\n/,$text//'') {
if ($line =~ /\A#\s+(?:(\d+)\.\s+)?(.+?)\s*\z/) {
if (!defined $1 && !length $c{title} && !@sections) {$c{title}=$2;next}
$sec={title=>$2,md=>'',lessons=>[]};push @sections,$sec;undef $lesson;next;
}
if ($line =~ $LESSON) {
my ($kind,$n,$title)=($1,0+$2,$3);
unless ($sec) {$sec={title=>'',md=>'',lessons=>[]};push @sections,$sec}
$lesson={n=>$n,kind=>$kind,title=>$title,groups=>[],assignment=>undef,notes=>[],md=>''};
($group,$mode)=(undef,'');
if ($c{by}{$n}) {push @{$c{warnings}},"$kind $n appears twice; the second one is left out.";$lesson->{ignored}=1;next}
push @{$sec->{lessons}},$lesson;push @{$c{lessons}},$lesson;$c{by}{$n}=$lesson;
next;
}
if ($line =~ /\A##\s/ && $lesson) {undef $lesson} # another heading: back to the section
if ($lesson) {
next if $line =~ /\A-{3,}\s*\z/;
if ($line =~ /\A\*\*(Assignment|Project|Homework|Task)(?::\s*(.*?))?\*\*\s*(.*?)\s*\z/) {
$lesson->{assignment}={label=>$1,title=>$2//'',md=>length $3 ? "$3\n" : '',deliverable=>''};($group,$mode)=(undef,'assignment');next;
}
if ($line =~ /\A\*\*Deliverables?:\*\*\s*(.+?)\s*\z/) {
($lesson->{assignment}//={label=>'Assignment',title=>'',md=>'',deliverable=>''})->{deliverable}=$1;$mode='';next;
}
if ($line =~ /\A\*\*([^*]{1,60}?):\*\*\s*(.+?)\s*\z/) {push @{$lesson->{notes}},[$1,$2];next}
if ($line =~ /\A\*\*([^*:]{1,60})\*\*\s*\z/) {$group={label=>$1,items=>[],md=>''};push @{$lesson->{groups}},$group;$mode='group';next}
if ($mode eq 'assignment') {$lesson->{assignment}{md}.="$line\n";next}
if ($mode eq 'group') {
if ($line =~ /\A(?:[-*+]|\d+\.)\s+(.+?)\s*\z/) {push @{$group->{items}},$1;next}
$group->{md}.="$line\n";next;
}
$lesson->{md}.="$line\n";next;
}
if ($sec) {
next if $line =~ /\A-{3,}\s*\z/ || $line =~ /\A\*\*(?:Weeks|Lessons|Modules|Sessions|Days|Classes|Chapters)\s+\d+\s*[–—-]\s*\d+\*\*\s*\z/;
$sec->{md}.="$line\n";next;
}
next if $line =~ /\A-{3,}\s*\z/;
if ($line =~ /\A\*\*([^*]{1,60}?):\*\*\s*(.+?)\s*\z/) {push @{$c{facts}},[$1,$2];next}
$c{intro}.="$line\n";
}
my $u=0;
for my $s (@sections) {
$s->{md}=trim($s->{md});
if (@{$s->{lessons}}) {
my ($kicker,$title)=$s->{title} =~ /\A(.+?)\s+[—–]\s+(.+)\z/ ? ($1,$2) : ('',$s->{title});
push @{$c{units}},{n=>++$u,kicker=>$kicker,title=>$title,intro=>$s->{md},lessons=>$s->{lessons}};
$_->{unit}=$u for @{$s->{lessons}};
}
elsif (length $s->{title} || length $s->{md}) {push @{$c{guide}},{title=>$s->{title},md=>$s->{md},anchor=>anchor($s->{title})}}
}
for my $l (@{$c{lessons}}) {$l->{md}=trim($l->{md});$_->{md}=trim($_->{md}) for @{$l->{groups}};$l->{assignment}{md}=trim($l->{assignment}{md}) if $l->{assignment}}
$c{intro}=trim($c{intro});
my @none=map {$_->{n}} grep {!$_->{assignment}} @{$c{lessons}};
push @{$c{warnings}},(@none==1 ? 'Number '.$none[0].' has' : 'Numbers '.join(', ',@none).' have').' no assignment.' if @none;
push @{$c{warnings}},'There are no lessons: write them as “## Week 1 — Title” under a numbered section such as “# 1. Unit one”.' unless @{$c{lessons}};
return \%c;
}
sub anchor ($t) { my $a=lc($t//'') =~ s/[^a-z0-9]+/-/gr =~ s/\A-|-\z//gr;return length $a ? $a : 'section' }
# Parsed once per text of the course, for the life of the worker (keyed by
# the text's digest: two saves in one second can have texts of one length).
my %parsed;
sub parsed ($c) {
my $key=Digest::SHA::sha1_hex(encode('UTF-8',$c->{source}//''));
return $parsed{$c->{id}}[1] if $parsed{$c->{id}} && $parsed{$c->{id}}[0] eq $key;
my $p=parse_course($c->{source});$parsed{$c->{id}}=[$key,$p];return $p;
}
sub title_of ($c,$p) { return length $c->{title} ? $c->{title} : length $p->{title} ? $p->{title} : $c->{slug} }
# Materials: "Name | URL | words, to, match" a line. An item that mentions one
# of a material's words gets a link to it; a longer word of another material
# wins over a shorter one inside it ("OSTEP course guide" over "OSTEP").
sub materials ($c) {
my @m;
for my $line (split /\r?\n/,$c->{materials}//'') {
next unless $line =~ /\S/;
my ($name,$url,$words)=map {trim($_)} split /\|/,$line,3;
next unless length($name//'');
$url='' unless ($url//'') =~ m{\Ahttps?://[^\s<>"']+\z};
push @m,{name=>$name,url=>$url,words=>[grep {length} map {trim($_)} split /,/,(length($words//'') ? $words : $name)]};
}
return \@m;
}
sub chips ($text,$mats) {
my @hits;
for my $i (0..$#$mats) {for my $w (@{$mats->[$i]{words}}) {my $p=index($text,$w);while ($p>=0) {push @hits,[$p,$p+length($w),$i];$p=index($text,$w,$p+1)}}}
my (%seen,@out);
for my $h (sort {$a->[0]<=>$b->[0]} @hits) {
next if grep {$_->[2]!=$h->[2] && $_->[0]<=$h->[0] && $_->[1]>=$h->[1] && ($_->[1]-$_->[0])>($h->[1]-$h->[0])} @hits;
push @out,$mats->[$h->[2]] unless $seen{$h->[2]}++;
}
return join '',map {length $_->{url} ? '<a class="course-chip" href="'.h($_->{url}).'" rel="noopener" target="_blank">'.h($_->{name}).' ↗</a>' : '<span class="course-chip is-book">'.h($_->{name}).'</span>'} @out;
}
# Rubric: "Category | weight" a line.
sub rubric ($c) {
my @r;
for my $line (split /\r?\n/,$c->{rubric}//'') {
my ($name,$w)=map {trim($_)} split /\|/,$line,2;
push @r,[$name,0+$w] if length($name//'') && ($w//'') =~ /\A\d{1,3}\z/;
}
return \@r;
}
sub md_inline ($t) { my $html=render_markdown($t//'');$html =~ s{\A\s*<p>(.*)</p>\s*\z}{$1}s;return $html }
# Course text as written by people: a list straight under a sentence ("It
# must:" then "- …") is a list, though Markdown wants a blank line first.
sub md ($t) {
my $list=qr/\A\s{0,3}(?:[-*+]|\d{1,3}\.)\s+\S/;my ($prev,@out)=('');
for my $line (split /\n/,$t//'',-1) {push @out,'' if $line =~ $list && $prev =~ /\S/ && $prev !~ $list;push @out,$line;$prev=$line}
return render_markdown(join "\n",@out);
}
sub plural ($n,$word) { return "$n ".lc($word).($n==1 ? '' : 's') }
# ---- Pieces of the public pages ------------------------------------------------------
# The course's place in each learner's browser: course.js reads it.
sub meta_html ($c,$p,%o) {
return '<div hidden data-course-meta data-course="'.h($c->{slug}).'" data-hours="'.(0+$c->{hours}).'" data-pass="'.(0+$c->{pass_mark}).'"'
.' data-kind="'.h(lc(($p->{lessons}[0]//{})->{kind}//'week')).'"'
.(defined $o{lesson} ? ' data-lesson="'.$o{lesson}.'" data-parts="'.h(JSON::PP->new->encode(rubric($c))).'"' : '')
.' data-plan="'.h(JSON::PP->new->encode([map {[$_->{n},$_->{unit},$_->{title}]} @{$p->{lessons}}])).'"></div>';
}
sub facts_html ($p) {
return '' unless @{$p->{facts}};
return '<dl class="course-facts">'.join('',map {'<div><dt>'.h($_->[0]).'</dt><dd>'.md_inline($_->[1]).'</dd></div>'} @{$p->{facts}}).'</dl>';
}
sub nojs_html { return '<p class="course-nojs media-label">Keeping track of your progress needs JavaScript. The course itself doesn’t.</p>' }
sub dashboard_html ($c,$p) {
my $kind=lc(($p->{lessons}[0]//{})->{kind}//'week');my $n=@{$p->{lessons}};my $first=$p->{lessons}[0];
return '<div class="course-dash" data-course-dash="'.h($c->{slug}).'">'
.'<p class="course-dash__count course-js-only"><strong data-out="done">0</strong> of '.plural($n,$kind).' done <span class="media-label" data-out="percent"></span></p>'
.'<div class="course-bar course-js-only" aria-hidden="true"><span data-bar></span></div>'
.($first ? '<p><a class="buttonlike course-continue" data-continue href="'.base($c).$first->{n}.'/">start with '.h(lc $first->{kind}).' '.$first->{n}.'</a></p>' : '')
.'<p class="course-js-only media-label" data-out="hours"></p>'
.($c->{hours} ? '<p class="course-js-only course-pace"><label>I started on <input type="date" data-start></label> <span data-out="pace"></span></p>' : '')
.nojs_html()
.'<p class="course-links"><a href="'.base($c).'guide/">guide & materials</a> · <a href="'.base($c).'progress/">your progress</a></p></div>';
}
sub unit_list_html ($c,$u) {
return '<ol class="course-lessons">'.join('',map {my $l=$_;my $a=$l->{assignment};
'<li data-course-lesson="'.h($c->{slug}).'" data-lesson="'.$l->{n}.'"><a href="'.base($c).$l->{n}.'/"><span class="course-dot" aria-hidden="true"></span>'
.'<span class="course-num">'.h($l->{kind}).' '.$l->{n}.'</span> <span class="course-title">'.h($l->{title}).'</span><span class="course-sr" data-status-text></span></a>'
.($a && length $a->{title} ? ' <span class="course-task media-label">'.h($a->{title}).'</span>' : '').'</li>'} @{$u->{lessons}}).'</ol>';
}
sub unit_heading ($u) { return (length $u->{kicker} ? '<span class="course-kicker">'.h($u->{kicker}).'</span> ' : '').h($u->{title}) }
sub range ($u) { my @l=@{$u->{lessons}};return lc($l[0]{kind}).(@l>1 ? 's '.$l[0]{n}.'–'.$l[-1]{n} : ' '.$l[0]{n}) }
# ---- The blocks ----------------------------------------------------------------------
sub blocks {
my @choices=map {[$_->{slug},$_->{title}]} @{courses(1)};
return {
course_list=>{label=>'Courses',order=>46,group=>'content',about=>'Every published course, with each learner’s progress.',
fields=>[[title=>'Panel title','text',120],[subtitle=>'Panel subtitle','text',160,'optional']],
defaults=>{title=>'courses'},manage=>['x-course','manage courses'],render=>\&render_list},
course_overview=>{label=>'Course',order=>47,group=>'content',about=>'One course: the learner’s progress, and its units and lessons.',
fields=>[[course=>'Course','select',(@choices ? \@choices : [['','(no courses yet)']])],[title=>'Panel title','text',120,'optional; the course’s title'],
[units=>'Show its units and lessons','check']],
defaults=>{course=>(@choices ? $choices[0][0] : ''),title=>'',units=>1},manage=>['x-course','manage courses'],render=>\&render_overview},
};
}
sub card_html ($c) {
my $p=parsed($c);my $n=@{$p->{lessons}};my $kind=lc(($p->{lessons}[0]//{})->{kind}//'lesson');
return '<li class="course-card" data-course-card="'.h($c->{slug}).'" data-pass="'.(0+$c->{pass_mark}).'" data-lessons="'.join(' ',map {$_->{n}} @{$p->{lessons}}).'">'
.'<h3><a href="'.base($c).'">'.h(title_of($c,$p)).'</a></h3>'
.(length $c->{summary} ? '<div class="course-card__about">'.md($c->{summary}).'</div>' : '')
.'<p class="media-label">'.join(' · ',grep {length} plural(scalar @{$p->{units}},'unit'),plural($n,$kind),($c->{hours} ? "about $c->{hours} hours a $kind" : '')).'</p>'
.'<div class="course-bar course-js-only" aria-hidden="true"><span data-bar></span></div><p class="media-label course-js-only" data-out="progress"></p>'
.'<p><a class="buttonlike" href="'.base($c).'" data-continue>open the course</a></p></li>';
}
sub list_html ($list) {
return @$list ? '<ul class="course-cards">'.join('',map {card_html($_)} @$list).'</ul>' : '<p class="empty-media">No courses yet.</p>';
}
sub render_list ($b,%o) { my $d=$b->{data};return window_html(length($d->{title}//'') ? $d->{title} : 'courses',$d->{subtitle}//'',list_html(courses()),%o) }
sub render_overview ($b,%o) {
my $d=$b->{data};my $c=course_by('slug',$d->{course}//'');
return window_html($d->{title} || 'course','','<p class="empty-media">This course isn’t published.</p>',%o) unless $c && $c->{active};
my $p=parsed($c);
my $html='<h3 class="course-name"><a href="'.base($c).'">'.h(title_of($c,$p)).'</a></h3>'.meta_html($c,$p).dashboard_html($c,$p);
$html.=join '',map {'<section class="course-unit"><h4>'.unit_heading($_).' <span class="media-label">'.h(range($_)).'</span></h4>'.unit_list_html($c,$_).'</section>'} @{$p->{units}} if $d->{units};
return window_html(length($d->{title}//'') ? $d->{title} : lc title_of($c,$p),'',$html,%o);
}
# ---- Public pages ---------------------------------------------------------------------
sub route ($rest) {
$rest=~s{/+\z}{};
if ($rest eq '') {
start_page('Courses','/x/course/',200,{description=>'Free courses to learn from, at your own pace.'});
window('courses',list_html(courses()));
BlowfishCMS::end_page();return 1;
}
my ($slug,$what)=$rest =~ m{\A([a-z0-9][a-z0-9-]{0,39})(?:/(guide|progress|\d{1,4}))?\z} or return 0;
my $c=course_by('slug',$slug);return 0 unless $c && $c->{active};
my $p=parsed($c);
return course_home($c,$p) unless defined $what;
return guide_page($c,$p) if $what eq 'guide';
return progress_page($c,$p) if $what eq 'progress';
my $l=$p->{by}{0+$what} or return 0;
return 0 if $what ne $l->{n}; # one address per lesson (no /007/)
return lesson_page($c,$p,$l);
}
sub course_home ($c,$p) {
my $title=title_of($c,$p);
start_page($title,base($c),200,{description=>length $c->{summary} ? $c->{summary} =~ s/\s+/ /gr : "$title: a free course.",og=>1});
my $about=(length $c->{summary} ? '<div class="course-summary">'.md($c->{summary}).'</div>' : '').(length $p->{intro} ? md($p->{intro}) : '');
window(lc $title,'<h1 class="course-h1">'.h($title).'</h1>'.$about.facts_html($p).meta_html($c,$p).dashboard_html($c,$p));
for my $u (@{$p->{units}}) {
print window_html(lc(length $u->{kicker} ? $u->{kicker} : 'unit '.$u->{n}),range($u),'<h2 class="course-unit-title" id="unit-'.$u->{n}.'">'.h($u->{title}).'</h2>'
.(length $u->{intro} ? '<div class="course-unit-intro">'.md($u->{intro}).'</div>' : '').unit_list_html($c,$u),body_class=>'course-unit-window');
}
print json_ld({'@type'=>'Course',name=>$title,description=>(length $c->{summary} ? $c->{summary} : $title),url=>site_url().base($c),isAccessibleForFree=>JSON::PP::true,
provider=>{'@type'=>'Organization',name=>BlowfishCMS::setting('site_title'),sameAs=>site_url()}});
BlowfishCMS::end_page();return 1;
}
sub guide_page ($c,$p) {
my $title=title_of($c,$p);
start_page("Guide · $title",base($c).'guide/',200,{description=>"How $title works, and what it uses."});
my $mats=materials($c);
my $toc=join '',map {'<li><a href="#'.h($_->{anchor}).'">'.h($_->{title}).'</a></li>'} @{$p->{guide}};
window('guide','<p class="course-crumbs"><a href="'.base($c).'">'.h($title).'</a> › guide</p><h1 class="course-h1">'.h($title).': guide</h1>'.facts_html($p)
.($toc ? '<ol class="course-toc">'.($mats && @$mats ? '<li><a href="#materials">Materials</a></li>' : '').$toc.'</ol>' : ''));
window('materials','<ul class="course-materials" id="materials">'.join('',map {'<li>'.(length $_->{url} ? '<a href="'.h($_->{url}).'" rel="noopener" target="_blank">'.h($_->{name}).' ↗</a>' : '<strong>'.h($_->{name}).'</strong> <span class="media-label">book</span>').'</li>'} @$mats).'</ul>') if @$mats;
print window_html(lc $_->{title},'','<div class="course-guide" id="'.h($_->{anchor}).'">'.md($_->{md}).'</div>') for @{$p->{guide}};
BlowfishCMS::end_page();return 1;
}
sub progress_page ($c,$p) {
my $title=title_of($c,$p);my $kind=lc(($p->{lessons}[0]//{})->{kind}//'lesson');
start_page("Your progress · $title",base($c).'progress/',200,{description=>"Your progress through $title.",noindex=>1});
window('your progress','<p class="course-crumbs"><a href="'.base($c).'">'.h($title).'</a> › your progress</p><h1 class="course-h1">Your progress</h1>'.meta_html($c,$p).dashboard_html($c,$p)
.'<table class="course-units course-js-only"><thead><tr><th scope="col">Unit</th><th scope="col">'.h(ucfirst $kind).'s done</th><th scope="col"><span class="course-sr">Progress</span></th></tr></thead><tbody>'
.join('',map {my $u=$_;'<tr data-unit-lessons="'.join(' ',map {$_->{n}} @{$u->{lessons}}).'"><td><a href="'.base($c).'#unit-'.$u->{n}.'">'.unit_heading($u).'</a></td><td><span data-out="done">0</span> of '.scalar(@{$u->{lessons}}).'</td><td><div class="course-bar" aria-hidden="true"><span data-bar></span></div></td></tr>'} @{$p->{units}})
.'</tbody></table>');
window('keep it safe','<div class="course-keep">'
.'<p>Your progress is kept in this browser only: nothing about you is sent to this site. To move it to another browser or keep a copy, save it to a file, then load that file there.</p>'
.'<p class="course-js-only"><button type="button" class="buttonlike" data-export>save my progress to a file</button> <label class="buttonlike course-file">load progress from a file<input type="file" accept=".json,application/json" data-import></label></p>'
.'<p class="course-js-only"><button type="button" class="text-button danger" data-reset>start again (forget my progress)</button></p><p class="media-label" data-out="message" role="status"></p>'.nojs_html().'</div>');
BlowfishCMS::end_page();return 1;
}
sub lesson_page ($c,$p,$l) {
my $title=title_of($c,$p);my $u=$p->{units}[$l->{unit}-1];my $mats=materials($c);my @all=@{$p->{lessons}};
my ($i)=grep {$all[$_] == $l} 0..$#all;my ($prev,$next)=($i>0 ? $all[$i-1] : undef,$all[$i+1]);
my $name="$l->{kind} $l->{n}";
my $nav='<nav class="course-nav" aria-label="'.h(ucfirst lc $l->{kind}).'s">'.($prev ? '<a href="'.base($c).$prev->{n}.'/" rel="prev">← '.h("$prev->{kind} $prev->{n}").'</a>' : '<span></span>')
.'<a href="'.base($c).'#unit-'.$l->{unit}.'">all '.h(lc $l->{kind}).'s</a>'.($next ? '<a href="'.base($c).$next->{n}.'/" rel="next">'.h("$next->{kind} $next->{n}").' →</a>' : '<span></span>').'</nav>';
start_page("$name: $l->{title} · $title",base($c).$l->{n}.'/',200,{description=>"$name of $title: $l->{title}."});
window(lc($name).' of '.scalar(@all),'<p class="course-crumbs"><a href="'.base($c).'">'.h($title).'</a> › <a href="'.base($c).'#unit-'.$u->{n}.'">'.unit_heading($u).'</a></p>'
.'<h1 class="course-h1">'.h($l->{title}).'</h1><p class="course-status course-js-only" data-lesson-status></p>'.meta_html($c,$p,lesson=>$l->{n})
.(length $l->{md} ? md($l->{md}) : '').$nav.nojs_html());
for my $gi (0..$#{$l->{groups}}) {
my $g=$l->{groups}[$gi];
print window_html(lc $g->{label},plural(scalar @{$g->{items}},'item'),(length $g->{md} ? md($g->{md}) : '')
.'<ul class="course-checks">'.join('',map {my $ii=$_;my $t=$g->{items}[$ii];
'<li><label><input type="checkbox" class="course-js-only" data-check="'.$l->{n}.".$gi.$ii".'"> <span>'.md_inline($t).'</span></label>'.(@$mats ? chips($t,$mats) : '').'</li>'} 0..$#{$g->{items}}).'</ul>');
}
if (my $a=$l->{assignment}) {
print window_html(lc $a->{label},length $a->{title} ? $a->{title} : '','<div class="course-assignment">'.(length $a->{title} ? '<h2>'.h($a->{title}).'</h2>' : '').md($a->{md})
.(length $a->{deliverable} ? '<p class="course-deliverable"><strong>Deliverable:</strong> '.md_inline($a->{deliverable}).'</p>' : '')
.'<p class="course-js-only"><label class="course-done"><input type="checkbox" data-done> I’ve finished '.(length $a->{deliverable} ? 'the deliverable' : 'it').'</label></p></div>');
}
print window_html(lc $_->[0],'','<div class="course-note">'.md($_->[1]).'</div>') for @{$l->{notes}};
unless ($l->{assignment}) {print window_html('done?','','<p class="course-js-only"><label class="course-done"><input type="checkbox" data-done> I’ve finished this '.h(lc $l->{kind}).'</label></p>'.nojs_html())}
my $r=rubric($c);
if (@$r && $l->{assignment}) {
print window_html('self-assessment','pass mark '.$c->{pass_mark}.'%','<div class="course-rubric course-js-only"><p>Score your work honestly against each part, from 0 to 100. It counts as done at '.$c->{pass_mark}.'% or more; below that, revise it before you move on.</p>'
.'<table><thead><tr><th scope="col">Part</th><th scope="col">Weight</th><th scope="col">Your score</th></tr></thead><tbody>'
.join('',map {'<tr><td>'.h($r->[$_][0]).'</td><td>'.$r->[$_][1].'%</td><td><input type="number" min="0" max="100" step="1" inputmode="numeric" data-rubric="'.$_.'" aria-label="'.h($r->[$_][0]).': your score out of 100"></td></tr>'} 0..$#$r)
.'</tbody><tfoot><tr><th scope="row">Total</th><td></td><td><output data-out="score">–</output></td></tr></tfoot></table></div>'.nojs_html());
}
print window_html('your notes','kept in this browser','<div class="course-mine course-js-only">'
.'<label>Notes<textarea rows="5" data-notes placeholder="What you learned, what to come back to"></textarea></label>'
.'<div class="course-mine__row"><label>Link to your work<input type="url" data-link placeholder="https://"></label><label>Hours spent<input type="number" min="0" max="200" step="0.5" inputmode="decimal" data-hours></label></div></div>'.nojs_html());
print '<div class="course-bottom">'.$nav.'</div>';
BlowfishCMS::end_page();return 1;
}
sub sitemap {
my @out;
for my $c (@{courses()}) {
my $p=parsed($c);my $d=substr($c->{updated_at},0,10);
push @out,[base($c),$d],[base($c).'guide/',$d],map {[base($c).$_->{n}.'/',$d]} @{$p->{lessons}};
}
return \@out;
}
# ---- Admin (kind=x-course) -------------------------------------------------------------
# The course list (published switch, edit, view, order, delete), adding a
# course (a title, and its text pasted or from a .md file), and a course's
# editor: its settings, materials, rubric and text, with what was found in it.
sub form_values ($old) {
my %v=(title=>param('title',200),slug=>lc param('slug',40),summary=>param('summary',2000),hours=>param('hours',3),pass_mark=>param('pass_mark',3),
rubric=>param('rubric',3000),materials=>param('materials',20000),source=>param('source',600000));
s/\r\n?/\n/g for @v{qw(summary rubric materials source)};
if (my $fh=$BlowfishCMS::q->upload('source_file')) {
local $/;my $raw=<$fh>;
if (defined $raw && length $raw) {
die "The course file is too large: up to 600 KB.\n" if length($raw)>600_000;
$v{source}=(attempt {decode('UTF-8',$raw,Encode::FB_CROAK())}) // die "The course file isn’t UTF-8 text. Save it as UTF-8 and try again.\n";
$v{source}=~s/\r\n?/\n/g;
}
}
die "Give the course a title.\n" unless length $v{title};
$v{slug}=lc($v{title}) =~ s/[^a-z0-9]+/-/gr =~ s/\A-+|-+\z//gr unless length $v{slug};
$v{slug}=substr($v{slug},0,40) =~ s/-+\z//r;
die "Address: lowercase letters, digits and dashes, such as computer-science.\n" unless slug_ok($v{slug});
my $other=course_by('slug',$v{slug});
die "Another course is at /x/course/$v{slug}/. Choose another address.\n" if $other && (!$old || $other->{id} ne $old->{id});
$v{hours}=length $v{hours} ? $v{hours} : 0;$v{pass_mark}=length $v{pass_mark} ? $v{pass_mark} : 70;
die "Hours a week: a whole number from 0 to 168.\n" unless $v{hours} =~ /\A\d{1,3}\z/ && $v{hours}<=168;
die "Pass mark: a whole number from 0 to 100.\n" unless $v{pass_mark} =~ /\A\d{1,3}\z/ && $v{pass_mark}<=100;
my $sum=0;my $n=0;
for (split /\n/,$v{rubric}) {next unless /\S/;my ($name,$w)=map {trim($_)} split /\|/,$_,2;die "Rubric: write each part as “Name | weight”, such as “Correctness | 40”.\n" unless length($name//'') && ($w//'') =~ /\A\d{1,3}\z/;$sum+=$w;$n++}
die "Rubric: the weights add up to $sum; make them add up to 100.\n" if $n && $sum!=100;
for (split /\n/,$v{materials}) {next unless /\S/;my (undef,$url)=map {trim($_)} split /\|/,$_,3;die "Materials: “".trim($url)."” isn’t a web address. Write each as “Name | https://… | words to match”, or leave the address out.\n" if length($url//'') && $url !~ m{\Ahttps?://[^\s<>"']+\z}}
return \%v;
}
sub admin {
my $message=param('notice',2000);my $eid=param('edit',40) || param('id',40);
my $edit=$eid =~ /\A[a-f0-9]{16}\z/ ? course_by('id',$eid) : undef;
my $back=sub ($n,$id='') {redirect('/admin/?kind=x-course¬ice='.CGI::escape(encode('UTF-8',$n)).(length $id ? "&edit=$id" : ''))};
my $submitted;
if ($BlowfishCMS::method eq 'POST') {
attempt {
my $action=param('action',30);
list_order(ids=>[map {$_->{id}} @{courses(1)}],back=>'/admin/?kind=x-course',save=>sub (@ids) {sort_order_save(db(),'course_courses','id',@ids)});
if ($action eq 'course_add') {
my $v=form_values(undef);my $id=substr(random_id(),0,16);my $order=(db()->selectrow_array('SELECT max(sort_order) FROM course_courses')//-1)+1;
db()->do('INSERT INTO course_courses (id,slug,title,summary,source,materials,rubric,pass_mark,hours,active,sort_order,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,0,?,?,?)',undef,
$id,@$v{qw(slug title summary source materials rubric pass_mark hours)},$order,now(),now());
$back->("Added $v->{title}. It stays hidden until you publish it.",$id);
}
$edit or die "That course no longer exists.\n";
if ($action eq 'course_save') {
# What was typed, shown again if it's refused.
$submitted={%$edit,map {($_=>param($_,600000) =~ s/\r\n?/\n/gr)} qw(title slug summary hours pass_mark rubric materials source)};
$submitted=form_values($edit);
db()->do('UPDATE course_courses SET slug=?,title=?,summary=?,source=?,materials=?,rubric=?,pass_mark=?,hours=?,updated_at=? WHERE id=?',undef,@$submitted{qw(slug title summary source materials rubric pass_mark hours)},now(),$edit->{id});
$back->("Saved $submitted->{title}.",$edit->{id});
}
if ($action eq 'course_active') {
my $on=param('on',1) eq '1' ? 1 : 0;
db()->do('UPDATE course_courses SET active=?,updated_at=? WHERE id=?',undef,$on,now(),$edit->{id});
$back->($on ? "$edit->{title} is published at /x/course/$edit->{slug}/." : "$edit->{title} is hidden; it stays here.");
}
if ($action eq 'course_delete') {
db()->do('DELETE FROM course_courses WHERE id=?',undef,$edit->{id});
$back->("Deleted $edit->{title}. Learners’ progress stays in their browsers, but the course is gone.");
}
die "Choose an action.\n";
} or $message=failed_action($@);
}
return editor($edit,$submitted,$message) if $edit;
admin_page('Courses',section=>'x-course',notice=>$message,intro=>'Free courses for your visitors. Each is one Markdown document: units, a page per week or lesson with its lectures, reading, exercises and assignment, and a guide. Learners’ progress stays in their own browsers.');
my @list=@{courses(1)};my $i=0;
window('courses',admin_list([map {my $c=$_;$i++;my $p=parsed($c);
admin_row(title=>$c->{title},order=>$c->{id},off=>!$c->{active},
meta=>[h("/x/course/$c->{slug}/"),plural(scalar @{$p->{units}},'unit'),plural(scalar @{$p->{lessons}},$p->{lessons}[0] ? $p->{lessons}[0]{kind} : 'lesson'),(@{$p->{warnings}} ? plural(scalar @{$p->{warnings}},'warning') : ()),($c->{active} ? () : 'hidden')],
actions=>switch_button('x-course','course_active',$c->{id},$c->{active},'published',what=>'Published',name=>$c->{title})
.'<a class="buttonlike" href="/admin/?kind=x-course&edit='.h($c->{id}).'">edit</a>'.($c->{active} ? '<a class="buttonlike" href="'.h(base($c)).'" target="_blank" rel="noopener">view ↗</a>' : ''),
menu=>move_buttons('x-course',$c->{id},$i,scalar @list,label=>$c->{title})
.'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete $c->{title}? Its text goes with it.").'">'.fields('course_delete','x-course',$c->{id}).'<button class="text-button danger">delete</button></form>')} @list],
order=>'x-course',empty=>'No courses yet. Add the first one below.')
.'<div class="box-part" id="add-course"><h3>Add a course</h3><form method="post" action="/admin/" class="admin-form" enctype="multipart/form-data" data-warn-unsaved>'.fields('course_add','x-course')
.'<div class="theme-editor__grid"><label>Title<input name="title" maxlength="200" required placeholder="Computer Science"></label><label>Address<input name="slug" maxlength="40" pattern="[a-z0-9][a-z0-9-]*" placeholder="computer-science"><span class="optional">/x/course/<b>address</b>/; made from the title</span></label></div>'
.'<label>The course, as a Markdown file<input type="file" name="source_file" accept=".md,.markdown,.txt,text/markdown,text/plain"><span class="optional">Optional: you can paste or write it on the next screen. How to write one is there too.</span></label>'
.'<button class="buttonlike is-primary" type="submit">add course</button></form><p class="media-label">It starts hidden, so you can finish it before you publish it.</p></div>');
BlowfishCMS::end_page();return 1;
}
sub editor ($c,$v,$message) {
$v//=$c;my $p=parse_course($v->{source});
admin_page($c->{title},section=>'x-course',notice=>$message,crumbs=>[['Courses','/admin/?kind=x-course']],
intro=>($c->{active} ? 'Published at <a href="'.h(base($c)).'" target="_blank" rel="noopener">'.h(base($c)).' ↗</a>.' : 'Hidden: publish it from the list of courses when it’s ready.'));
print '<form id="course-form" method="post" action="/admin/" class="admin-form" enctype="multipart/form-data" data-warn-unsaved>'.fields('course_save','x-course',$c->{id});
window('the course','<div class="theme-editor__grid"><label>Title<input name="title" maxlength="200" required value="'.h($v->{title}).'"></label>'
.'<label>Address<input name="slug" maxlength="40" pattern="[a-z0-9][a-z0-9-]*" required value="'.h($v->{slug}).'"><span class="optional">/x/course/<b>address</b>/. Changing it breaks links to the old one, and learners’ progress is kept under the address.</span></label></div>'
.'<label>Summary<textarea name="summary" rows="3" maxlength="2000">'.h($v->{summary}).'</textarea><span class="optional">A sentence or two for the list of courses and search engines (Markdown).</span></label>'
.'<div class="theme-editor__grid"><label>Hours a week<input name="hours" inputmode="numeric" maxlength="3" value="'.h($v->{hours}||'').'" placeholder="20"><span class="optional">Optional: for the learner’s pace and hours.</span></label>'
.'<label>Pass mark (%)<input name="pass_mark" inputmode="numeric" maxlength="3" value="'.h($v->{pass_mark}).'"><span class="optional">An assignment scored below it should be revised.</span></label></div>');
window('self-assessment rubric','<label>The parts of an assignment’s score, one a line<textarea name="rubric" rows="6" maxlength="3000" placeholder="Correctness | 40 Understanding and explanation | 25">'.h($v->{rubric}).'</textarea>'
.'<span class="optional">“Name | weight”, the weights adding up to 100. Leave it empty for no scoring: learners just mark each assignment finished.</span></label>');
window('materials','<label>Courses, books and sites it uses, one a line<textarea name="materials" rows="10" maxlength="20000" class="course-mono" placeholder="Harvard CS50x | https://cs50.harvard.edu/x/ | CS50x Effective C (book) | | Effective C">'.h($v->{materials}).'</textarea>'
.'<span class="optional">“Name | address | words to look for”. A lecture or reading line that contains one of the words links to it; without words, the name is looked for. A book without an address is listed on the guide.</span></label>');
window('the course text','<label>Markdown<textarea name="source" rows="28" maxlength="600000" class="course-mono" spellcheck="false">'.h($v->{source}).'</textarea></label>'
.'<label>Or replace it with a file<input type="file" name="source_file" accept=".md,.markdown,.txt,text/markdown,text/plain"></label>'
.'<details class="box-part"><summary>How to write a course</summary><pre class="course-format">'.h(join "\n",
'# Course title','**Duration:** 12 weeks (facts, before the first section)','',
'# 1. How to use this course (a guide section: any Markdown)','',
'# 2. Unit one — Getting started (a unit: a section with weeks in it)','Why this unit matters.','',
'## Week 1 — First steps (Week, Lesson, Module, Session, Day, Class or Chapter)','**Lectures**','- Watch the introduction.','**Reading**','- Chapter 1.','**Exercises**','- Try the examples.','',
'**Assignment: Hello**','Write a program that prints a greeting.','**Deliverable:** The source and its output.','',
'**Unit assessment:** any other bold label with a colon is a note on the week.').'</pre></details>'
.'<p><button class="buttonlike is-primary" type="submit">save</button></p>');
print '</form>';
my $n=@{$p->{lessons}};
window('what it has',(@{$p->{warnings}} ? '<ul class="admin-notice--error course-warnings">'.join('',map {'<li>'.h($_).'</li>'} @{$p->{warnings}}).'</ul>' : '')
.'<p>'.join(' · ',plural(scalar @{$p->{units}},'unit'),plural($n,$n ? $p->{lessons}[0]{kind} : 'lesson'),plural(scalar(grep {$_->{assignment}} @{$p->{lessons}}),'assignment'),plural(scalar @{$p->{guide}},'guide section'),plural(scalar @{materials($v)},'material'),plural(scalar @{$p->{facts}},'fact')).' (as saved)</p>'
.admin_list([map {my $u=$_;admin_row(title=>(length $u->{kicker} ? "$u->{kicker}: " : '').$u->{title},meta=>[h(range($u)),plural(scalar(map {@{$_->{groups}}} @{$u->{lessons}}),'checklist')])} @{$p->{units}}],empty=>'No units yet.'));
window('delete','<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete $c->{title}? Its text goes with it.").'">'.fields('course_delete','x-course',$c->{id}).'<button class="buttonlike danger">delete this course</button></form>');
BlowfishCMS::end_page();return 1;
}
1;