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 => sub {
183 my @enum = qw[ essential basic common distinctive optional invisible ];
185 ('' => 'parent') x (defined $row->{ref}),
186 map { $_ => $enum[$_] } 0 .. $#enum
191 cover => {-label => 'Highlighted', type => 'checkbox'},
192 grade => {-label => 'Order', type => 'number'},
193 form => {-label => 'Title'},
194 alt => {-label => 'Synonyms', -multiple => 1},
195 wptitle => {-label => 'Wikipedia'},
196 source => {-label => 'Image'},
197 thumb => {-label => 'Convert options', -multiple => 1},
199 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
203 $row = $db->select(word => '*', $find)->hash
204 or Abort("Word not found", 404);
207 if (exists $get{copy}) {
208 $row = {%{$row}{ qw(prio lang cat) }};
210 elsif (defined $post{form}) {{
212 return if not length $_[0];
214 return Encode::decode_utf8($_[0]);
219 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
220 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
221 scalar parseinput($post{$_})
225 if ($row->{ref} ne 'delete') {
227 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
231 $db->delete(word => $find);
232 Alert("Entry removed");
238 my %res = (returning => '*');
239 $row->{creator} = $user->{id} unless $find;
240 $row->{updated} = ['now()'];
241 my $query = $find ? $db->update(word => $row, $find, \%res) :
242 $db->insert(word => $row, \%res);
245 Alert("Entry could not be saved", $@);
250 while (my ($lang, $val) = each %post) {
252 $lang =~ s/^trans-// or next;
253 $val = parseinput($val) or next;
260 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
261 $db->insert(word => \%subrow);
262 delete $fields{$field};
265 } or Alert('Error creating translation entries', $@);
267 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
269 ($row->{source} // '') ne ($replace->{source} // '') or return;
270 # copy changed remote url to local file
271 unlink $imgpath if -e $imgpath;
272 my $download = $row->{source} or return 1;
273 require LWP::UserAgent;
274 my $ua = LWP::UserAgent->new;
276 my $status = $ua->mirror($download, $imgpath);
278 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
280 !$@ or Alert(["Source image not found", $@]);
282 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
283 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
284 $reimage++ if $fields{rethumb}; # force refresh
286 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
289 my $xyres = $row->{cover} ? '600x400' : '300x200';
290 my @cmds = @{ $row->{thumb} // [] };
291 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
292 # replace option by permillage crop
293 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
294 splice @cmds, $cmdarg, 2, (
295 -set => 'option:distort:viewport' => sprintf(
296 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
297 ($dim[2] || 1) - $dim[0], # width = x2 - x1
298 ($dim[3] || 1) - $dim[1], # height = y2 - y1
299 @dim[0, 1] # offset = x1,y1
301 -distort => SRT => 0, # noop transform to apply viewport
307 -delete => '1--1', -background => 'white',
308 -gravity => @cmds ? 'northwest' : 'center',
310 -resize => "$xyres^", -extent => $xyres,
311 '-strip', -quality => '60%', -interlace => 'plane',
317 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
319 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
321 "Thumbnail image not generated",
322 "Failed to convert source image.",
331 $row->{lang} //= $user->{editlang}->[0];
332 $row->{$_} = $get{$_} for keys %get;
333 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
336 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
338 package Shiar_Sheet::FormRow {
339 use PLP::Functions 'EscapeHTML';
342 my ($row, $col, $attr) = @_;
343 my $val = $row->{$col} // '';
345 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
347 if (my $options = $attr->{-select}) {
348 $options = $options->(@_) if ref $options eq 'CODE';
349 $options->{$val} //= "unknown ($val)"; # preserve current
351 sprintf('<select id="%s" name="%1$s">', $col),
352 (map { sprintf('<option value="%s"%s>%s</option>',
353 $_, $val eq $_ && ' selected', $options->{$_}
354 ) } sort keys %{$options}),
358 elsif ($attr->{type} eq 'checkbox') {
359 $html .= ' checked' if $val;
363 '<input name="%1$s" value="0" type="hidden" />',
364 '<input id="%s" name="%1$s" value="1"%s>',
366 ), $col, $html, $attr->{-label}
370 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
373 sprintf('<label for="%s">%s</label>', $col, $_)
374 } $attr->{-label} // ()),
375 $multiple ? '<span class="inline multiinput">' : (),
377 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
378 } ref $val eq 'ARRAY' ? @{$val} : ()),
379 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
380 $col, $multiple ? '' : EscapeHTML($val), $html
382 $multiple ? '</span>' : (),
384 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
385 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
386 } grep { -e } $row->imagepath($col)),
392 my ($row, $col) = @_;
393 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
394 return "data/word/en/$row->{form}.jpg" if $col eq 'thumb';
398 bless $row, 'Shiar_Sheet::FormRow';
400 <h1>Words <:= $title :></h1>
404 <form action="?" method="post">
405 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
408 for my $col (@wordcols) {
409 my $info = $wordcol{$col} or next;
410 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
411 my $title = ref $attr ? delete $attr->{-label} : $attr;
412 printf '<li><label for="%s">%s</label><p>', $col, $title;
413 printf '<span class=inline>';
414 print $row->input($col => $attr);
415 print $row->input($_ => delete $wordcol{$_}) for @span;
420 if (not $row->{ref}) {
421 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
422 'trans', 'Translations';
423 my @children = !$row->{id} ? () :
424 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
425 while (my ($lang, $val) = each %fields) {
426 $lang =~ s/^trans-// or next;
427 push @children, { lang => $lang, form => $val };
429 my %existing = map { $_->{lang} => 1 } $row, @children;
430 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
432 for my $ref (@children) {
434 '<li><label for="%s" title="%3$s">%s </label>',
435 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
438 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
439 '<input id="%s" name="%1$s" value="%3$s" />',
440 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
443 say '</ul></div></li>';
448 <input type="submit" value="Save" />
449 <input type="submit" value="New" formaction="/writer?copy=cat" />
461 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
462 while (my $ref = $parents->hash) {
463 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
465 say "<li><strong>$row->{form}</strong></li>";
466 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
467 while (my $ref = $children->hash) {
468 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
471 <li><form action="/writer">
472 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
473 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
474 <input type="submit" value="Add" />