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 $db->insert(word => {
252 }) for parseinput($val);
253 delete $fields{$field};
256 } or Alert('Error creating translation entries', $@);
258 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
260 ($row->{source} // '') ne ($replace->{source} // '') or return;
261 # copy changed remote url to local file
262 unlink $imgpath if -e $imgpath;
263 my $download = $row->{source} or return 1;
264 require LWP::UserAgent;
265 my $ua = LWP::UserAgent->new;
267 my $status = $ua->mirror($download, $imgpath);
269 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
271 !$@ or Alert(["Source image not found", $@]);
273 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
274 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
275 $reimage++ if $fields{rethumb}; # force refresh
277 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
280 my $xyres = $row->{cover} ? '600x400' : '300x200';
281 my @cmds = @{ $row->{thumb} // [] };
282 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
283 # replace option by permillage crop
284 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
285 splice @cmds, $cmdarg, 2, (
286 -set => 'option:distort:viewport' => sprintf(
287 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
288 ($dim[2] || 1) - $dim[0], # width = x2 - x1
289 ($dim[3] || 1) - $dim[1], # height = y2 - y1
290 @dim[0, 1] # offset = x1,y1
292 -distort => SRT => 0, # noop transform to apply viewport
297 -delete => '1--1', -background => 'white',
298 -gravity => @cmds ? 'northwest' : 'center',
300 -resize => "$xyres^", -extent => $xyres,
301 '-strip', -quality => '60%', -interlace => 'plane',
302 $imgpath => $thumbpath
307 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
309 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
311 "Thumbnail image not generated",
312 "Failed to convert source image.",
322 $row->{lang} //= $user->{editlang}->[0];
323 $row->{$_} = $get{$_} for keys %get;
326 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
328 package Shiar_Sheet::FormRow {
329 use PLP::Functions 'EscapeHTML';
332 my ($row, $col, $attr) = @_;
333 my $val = $row->{$col} // '';
335 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
337 if (my $options = $attr->{-select}) {
338 $options = { map {$_ => $options->[$_]} 0 .. $#{$options} }
339 if ref $options eq 'ARRAY';
340 $options->{$val} //= "unknown ($val)"; # preserve current
342 sprintf('<select id="%s" name="%1$s">', $col),
343 (map { sprintf('<option value="%s"%s>%s</option>',
344 $_, $val eq $_ && ' selected', $options->{$_}
345 ) } sort keys %{$options}),
349 elsif ($attr->{type} eq 'checkbox') {
350 $html .= ' checked' if $val;
354 '<input name="%1$s" value="0" type="hidden" />',
355 '<input id="%s" name="%1$s" value="1"%s>',
357 ), $col, $html, $attr->{-label}
361 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
364 sprintf('<label for="%s">%s</label>', $col, $_)
365 } $attr->{-label} // ()),
366 $multiple ? '<span class="inline multiinput">' : (),
368 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
369 } ref $val eq 'ARRAY' ? @{$val} : ()),
370 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
371 $col, $multiple ? '' : EscapeHTML($val), $html
373 $multiple ? '</span>' : (),
375 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
376 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
377 } grep { -e } $row->imagepath($col)),
383 my ($row, $col) = @_;
384 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
385 return "data/word/en/$row->{form}.jpg" if $col eq 'thumb';
389 bless $row, 'Shiar_Sheet::FormRow';
391 <h1>Words <:= $title :></h1>
395 <form action="?" method="post">
396 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
399 for my $col (@wordcols) {
400 my $info = $wordcol{$col} or next;
401 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
402 my $title = ref $attr ? delete $attr->{-label} : $attr;
403 printf '<li><label for="%s">%s</label><p>', $col, $title;
404 printf '<span class=inline>';
405 print $row->input($col => $attr);
406 print $row->input($_ => delete $wordcol{$_}) for @span;
411 if (not $row->{ref}) {
412 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
413 'trans', 'Translations';
414 my @children = !$row->{id} ? () :
415 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
416 while (my ($lang, $val) = each %fields) {
417 $lang =~ s/^trans-// or next;
418 push @children, { lang => $lang, form => $val };
420 my %existing = map { $_->{lang} => 1 } $row, @children;
421 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
423 for my $ref (@children) {
425 '<li><label for="%s" title="%3$s">%s </label>',
426 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
429 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
430 '<input id="%s" name="%1$s" value="%3$s" />',
431 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
434 say '</ul></div></li>';
439 <input type="submit" value="Save" />
440 <input type="submit" value="New" formaction="/writer?copy=cat" />
452 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
453 while (my $ref = $parents->hash) {
454 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
456 say "<li><strong>$row->{form}</strong></li>";
457 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
458 while (my $ref = $children->hash) {
459 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
462 <li><form action="/writer">
463 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
464 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
465 <input type="submit" value="Add" />