4 title => 'words cheat sheet admin',
11 grid: auto-flow / min-content repeat(10, auto);
16 border-spacing: 0 2px;
25 form > ul > li > label {
29 form > ul > li > label + * {
36 box-sizing: border-box;
39 input:not([type=submit]) {
41 font-family: monospace;
47 padding: .3rem .2rem; /* TODO: input */
66 background: rgba(0, 0, 0, .8);
67 border: 1px solid #CCC;
75 align-items: baseline;
76 margin: 0 -1ex; /* inner gap */
96 display: inline-block;
100 <script src="/writer.js"></script>
104 use List::Util qw( pairs pairkeys );
108 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
109 ) or die "database not configured\n";
110 require DBIx::Simple;
111 DBIx::Simple->new(@dbinfo[0..2], {
115 } or Abort('Database error', 501, $@);
116 $db->abstract->{array_datatypes}++;
119 if (defined $post{username}) {
120 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
122 elsif (exists $fields{logout}) {
124 if (AddCookie(CGI::Cookie->new(
130 delete $cookie{login};
131 die "Logged out as requested\n";
133 Alert("Failed to log out", "Login cookie could not be removed.");
136 my $cookiedata = $cookie{login} or return;
137 my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
138 my %rowmatch = (username => $name, pass => $key);
139 my $found = $db->select(login => '*', \%rowmatch)->hash
140 or die "Invalid user or password\n";
144 my $httpcookie = CGI::Cookie->new(
146 -value => join(':', @{$found}{qw( username pass )}),
148 ) or die "prepared object is empty\n";
149 AddCookie($httpcookie->as_string);
150 } or Abort(["Unable to create login cookie", $@], 403);
154 say '<h1>Login to edit words</h1>';
155 Alert('Access denied', $@) if $@;
156 say '<form action="?" method="post" class="inline"><ul>';
157 my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
158 say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
159 username => {-label => 'User name'},
160 pass => {-label => 'Password', type => 'password'},
162 say '<li><input type="submit" value="Login" /></li>';
168 nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
169 en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
170 eo => ['<span style="color:green">★</span>', 'esperanto'],
171 ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
173 my @wordcols = pairkeys
175 lang => {-label => 'Language', -select => {
176 map { $_ => "@{$lang{$_}}" } keys %lang
178 cat => [{-label => 'Category'}, 'ref'],
179 ref => {-label => 'Reference'},
181 {-label => 'Level', -select => [qw(
182 essential basic common distinctive rare invisible
186 cover => {-label => 'Highlighted', type => 'checkbox'},
187 grade => {-label => 'Order', type => 'number'},
188 form => {-label => 'Title'},
189 alt => {-label => 'Synonyms', -multiple => 1},
190 wptitle => {-label => 'Wikipedia'},
191 source => {-label => 'Image'},
192 thumb => {-label => 'Convert options', -multiple => 1},
194 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
198 $row = $db->select(word => '*', $find)->hash
199 or Abort("Word not found", 404);
202 if (exists $get{copy}) {
203 $row = {%{$row}{ qw(prio lang cat) }};
205 elsif (defined $post{form}) {{
207 return if not length $_[0];
209 return Encode::decode_utf8($_[0]);
214 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
215 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
216 scalar parseinput($post{$_})
220 if ($row->{ref} ne 'delete') {
222 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
226 $db->delete(word => $find);
227 Alert("Entry removed");
233 my %res = (returning => '*');
234 $row->{creator} = $user->{id} unless $find;
235 $row->{updated} = ['now()'];
236 my $query = $find ? $db->update(word => $row, $find, \%res) :
237 $db->insert(word => $row, \%res);
240 Alert("Entry could not be saved", $@);
245 while (my ($lang, $val) = each %post) {
247 $lang =~ s/^trans-// or next;
248 $val = parseinput($val) or next;
254 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
255 $db->insert(word => \%subrow);
256 delete $fields{$field};
259 } or Alert('Error creating translation entries', $@);
261 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
263 ($row->{source} // '') ne ($replace->{source} // '') or return;
264 # copy changed remote url to local file
265 unlink $imgpath if -e $imgpath;
266 my $download = $row->{source} or return 1;
267 require LWP::UserAgent;
268 my $ua = LWP::UserAgent->new;
270 my $status = $ua->mirror($download, $imgpath);
272 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
274 !$@ or Alert(["Source image not found", $@]);
276 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
277 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
278 $reimage++ if $fields{rethumb}; # force refresh
280 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
283 my $xyres = $row->{cover} ? '600x400' : '300x200';
284 my @cmds = @{ $row->{thumb} // [] };
285 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
286 # replace option by permillage crop
287 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
288 splice @cmds, $cmdarg, 2, (
289 -set => 'option:distort:viewport' => sprintf(
290 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
291 ($dim[2] || 1) - $dim[0], # width = x2 - x1
292 ($dim[3] || 1) - $dim[1], # height = y2 - y1
293 @dim[0, 1] # offset = x1,y1
295 -distort => SRT => 0, # noop transform to apply viewport
301 -delete => '1--1', -background => 'white',
302 -gravity => @cmds ? 'northwest' : 'center',
304 -resize => "$xyres^", -extent => $xyres,
305 '-strip', -quality => '60%', -interlace => 'plane',
311 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
313 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
315 "Thumbnail image not generated",
316 "Failed to convert source image.",
326 $row->{lang} //= $user->{editlang}->[0];
327 $row->{$_} = $get{$_} for keys %get;
330 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
332 package Shiar_Sheet::FormRow {
333 use PLP::Functions 'EscapeHTML';
336 my ($row, $col, $attr) = @_;
337 my $val = $row->{$col} // '';
339 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
341 if (my $options = $attr->{-select}) {
342 $options = { map {$_ => $options->[$_]} 0 .. $#{$options} }
343 if ref $options eq 'ARRAY';
344 $options->{$val} //= "unknown ($val)"; # preserve current
346 sprintf('<select id="%s" name="%1$s">', $col),
347 (map { sprintf('<option value="%s"%s>%s</option>',
348 $_, $val eq $_ && ' selected', $options->{$_}
349 ) } sort keys %{$options}),
353 elsif ($attr->{type} eq 'checkbox') {
354 $html .= ' checked' if $val;
358 '<input name="%1$s" value="0" type="hidden" />',
359 '<input id="%s" name="%1$s" value="1"%s>',
361 ), $col, $html, $attr->{-label}
365 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
368 sprintf('<label for="%s">%s</label>', $col, $_)
369 } $attr->{-label} // ()),
370 $multiple ? '<span class="inline multiinput">' : (),
372 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
373 } ref $val eq 'ARRAY' ? @{$val} : ()),
374 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
375 $col, $multiple ? '' : EscapeHTML($val), $html
377 $multiple ? '</span>' : (),
379 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
380 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
381 } grep { -e } $row->imagepath($col)),
387 my ($row, $col) = @_;
388 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
389 return "data/word/en/$row->{form}.jpg" if $col eq 'thumb';
393 bless $row, 'Shiar_Sheet::FormRow';
395 <h1>Words <:= $title :></h1>
399 <form action="?" method="post">
400 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
403 for my $col (@wordcols) {
404 my $info = $wordcol{$col} or next;
405 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
406 my $title = ref $attr ? delete $attr->{-label} : $attr;
407 printf '<li><label for="%s">%s</label><p>', $col, $title;
408 printf '<span class=inline>';
409 print $row->input($col => $attr);
410 print $row->input($_ => delete $wordcol{$_}) for @span;
415 if (not $row->{ref}) {
416 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
417 'trans', 'Translations';
418 my @children = !$row->{id} ? () :
419 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
420 while (my ($lang, $val) = each %fields) {
421 $lang =~ s/^trans-// or next;
422 push @children, { lang => $lang, form => $val };
424 my %existing = map { $_->{lang} => 1 } $row, @children;
425 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
427 for my $ref (@children) {
429 '<li><label for="%s" title="%3$s">%s </label>',
430 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
433 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
434 '<input id="%s" name="%1$s" value="%3$s" />',
435 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
438 say '</ul></div></li>';
443 <input type="submit" value="Save" />
444 <input type="submit" value="New" formaction="/writer?copy=cat" />
456 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
457 while (my $ref = $parents->hash) {
458 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
460 say "<li><strong>$row->{form}</strong></li>";
461 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
462 while (my $ref = $children->hash) {
463 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
466 <li><form action="/writer">
467 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
468 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
469 <input type="submit" value="Add" />