3c0b248bf9d859160269261912e745fa39bb16ad
[sheet.git] / writer.plp
1 <(common.inc.plp)><:
2
3 Html({
4         title => 'words cheat sheet admin',
5         version => '1.0',
6         nocache => 1,
7         raw => <<'EOT',
8 <style>
9 dl {
10         display: inline-grid;
11         grid: auto-flow / min-content repeat(10, auto);
12 }
13
14 form > ul {
15         display: table;
16         border-spacing: 0 2px;
17 }
18 form > ul > li {
19         display: table-row;
20 }
21 form > ul > li > * {
22         display: table-cell;
23         padding-right: .5em;
24 }
25 form > ul > li > label {
26         /* th */
27         text-align: right;
28 }
29 form > ul > li > label + * {
30         /* td */
31         width: 40em;
32 }
33
34 .multiinput,
35 input,select {
36         box-sizing: border-box;
37         flex-grow: 1;
38 }
39 input:not([type=submit]) {
40         padding: .4rem;
41         font-family: monospace;
42 }
43 input[type=number] {
44         max-width: 7em;
45 }
46 select {
47         padding: .3rem .2rem; /* TODO: input */
48 }
49 #thumbpreview {
50         width: 300px;
51         align-self: start;
52         flex-shrink: 0;
53 }
54
55 ul.popup {
56         display: flex;
57         flex-wrap: wrap;
58         align-items: end;
59         position: fixed;
60         left: 0;
61         top: 0;
62         margin: auto;
63         max-height: 90%;
64         max-width: 90%;
65         overflow: auto;
66         background: rgba(0, 0, 0, .8);
67         border: 1px solid #CCC;
68 }
69
70 h1 {
71         margin-bottom: 1ex;
72 }
73 .inline {
74         display: inline-flex;
75         align-items: baseline;
76         margin: 0 -1ex; /* inner gap */
77 }
78 .inline > * {
79         margin: 0 1ex;
80 }
81 .inline .inline {
82         display: flex;
83         margin: 0;
84 }
85 .inline.multiinput {
86         flex-wrap: wrap;
87 }
88 .multiinput > input {
89         width: 10em;
90 }
91
92 #nav > ul,
93 #nav > ul strong,
94 #nav form {
95         margin: 1ex 0;
96         display: inline-block;
97 }
98 </style>
99
100 <script src="/writer.js"></script>
101 EOT
102 });
103
104 use List::Util qw( pairs pairkeys );
105
106 my $db = eval {
107         my @dbinfo = (
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], {
112                 RaiseError => 1,
113                 pg_enable_utf8 => 1,
114         });
115 } or Abort('Database error', 501, $@);
116 $db->abstract->{array_datatypes}++;
117
118 my $user = eval {
119         if (defined $post{username}) {
120                 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
121         }
122         elsif (exists $fields{logout}) {
123                 require CGI::Cookie;
124                 if (AddCookie(CGI::Cookie->new(
125                         -name    => 'login',
126                         -value   => '',
127                         -path    => '/writer',
128                         -expires => 'now',
129                 )->as_string)) {
130                         delete $cookie{login};
131                         die "Logged out as requested\n";
132                 }
133                 Alert("Failed to log out", "Login cookie could not be removed.");
134         }
135
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";
141
142         eval {
143                 require CGI::Cookie;
144                 my $httpcookie = CGI::Cookie->new(
145                         -name    => 'login',
146                         -value   => join(':', @{$found}{qw( username pass )}),
147                         -path    => '/writer',
148                 ) or die "prepared object is empty\n";
149                 AddCookie($httpcookie->as_string);
150         } or Abort(["Unable to create login cookie", $@], 403);
151
152         return $found;
153 } or do {
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'},
161         );
162         say '<li><input type="submit" value="Login" /></li>';
163         say '</ul></form>';
164         exit;
165 };
166
167 my %lang = (
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}", 'русский'],
172 );
173 my @wordcols = pairkeys
174 my %wordcol = (
175         lang    => {-label => 'Language', -select => {
176                 map { $_ => "@{$lang{$_}}" } keys %lang
177         }},
178         cat     => [{-label => 'Category'}, 'ref'],
179         ref     => {-label => 'Reference'},
180         prio    => [
181                 {-label => 'Level', -select => [qw(
182                         essential basic common distinctive rare invisible
183                 )]},
184                 'cover', 'grade',
185         ],
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},
193 );
194 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
195
196 my $row;
197 if ($find) {
198         $row = $db->select(word => '*', $find)->hash
199                 or Abort("Word not found", 404);
200 }
201
202 if (exists $get{copy}) {
203         $row = {%{$row}{ qw(prio lang cat) }};
204 }
205 elsif (defined $post{form}) {{
206         sub parseinput {
207                 return if not length $_[0];
208                 require Encode;
209                 return Encode::decode_utf8($_[0]);
210         }
211
212         my $replace = $row;
213         $row = {map { $_ =>
214                 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
215                         [ map { parseinput($_) } $post{'@'.$_}->@* ] :
216                 scalar parseinput($post{$_})
217         } keys %wordcol};
218
219         if (!$row->{form}) {
220                 if ($row->{ref} ne 'delete') {
221                         Alert("Empty title",
222                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
223                         );
224                 }
225                 else {
226                         $db->delete(word => $find);
227                         Alert("Entry removed");
228                 }
229                 next;
230         }
231
232         eval {
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);
238                 $row = $query->hash;
239         } or do {
240                 Alert("Entry could not be saved", $@);
241                 next;
242         };
243
244         eval {
245                 while (my ($lang, $val) = each %post) {
246                         my $field = $lang;
247                         $lang =~ s/^trans-// or next;
248                         $val = parseinput($val) or next;
249                         my %subrow = (
250                                 ref   => $row->{id},
251                                 lang  => $lang,
252                                 form  => $val,
253                         );
254                         $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
255                         $db->insert(word => \%subrow);
256                         delete $fields{$field};
257                 }
258                 return 1;
259         } or Alert('Error creating translation entries', $@);
260
261         my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
262         my $reimage = eval {
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;
269                 $ua->agent('/');
270                 my $status = $ua->mirror($download, $imgpath);
271                 $status->is_success
272                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
273         };
274         !$@ or Alert(["Source image not found", $@]);
275
276         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
277         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
278         $reimage++ if $fields{rethumb};  # force refresh
279
280         my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
281         if ($reimage) {
282                 if (-e $imgpath) {
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
294                                         ),
295                                         -distort => SRT => 0, # noop transform to apply viewport
296                                 );
297                         }
298                         @cmds = (
299                                 'convert',
300                                 $imgpath,
301                                 -delete => '1--1', -background => 'white',
302                                 -gravity => @cmds ? 'northwest' : 'center',
303                                 @cmds,
304                                 -resize => "$xyres^", -extent => $xyres,
305                                 '-strip', -quality => '60%', -interlace => 'plane',
306                                 $thumbpath
307                         );
308                         eval {
309                                 require IPC::Run;
310                                 my $output;
311                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
312                                         or die $output ||
313                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
314                         } or Alert([
315                                 "Thumbnail image not generated",
316                                 "Failed to convert source image.",
317                         ], "@cmds\n$@");
318                 }
319                 else {
320                         unlink $thumbpath;
321                 }
322         }
323 }}
324 else {
325         $row->{prio} //= 1;
326         $row->{lang} //= $user->{editlang}->[0];
327         $row->{$_} = $get{$_} for keys %get;
328 }
329
330 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
331
332 package Shiar_Sheet::FormRow {
333         use PLP::Functions 'EscapeHTML';
334
335         sub input {
336                 my ($row, $col, $attr) = @_;
337                 my $val = $row->{$col} // '';
338                 my $html = '';
339                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
340
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
345                         return (
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}),
350                                 '</select>',
351                         );
352                 }
353                 elsif ($attr->{type} eq 'checkbox') {
354                         $html .= ' checked' if $val;
355                         return sprintf(
356                                 join('',
357                                         '<label>',
358                                         '<input name="%1$s" value="0" type="hidden" />',
359                                         '<input id="%s" name="%1$s" value="1"%s>',
360                                         ' %s</label>',
361                                 ), $col, $html, $attr->{-label}
362                         );
363                 }
364                 else {
365                         my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
366                         return (
367                                 (map {
368                                         sprintf('<label for="%s">%s</label>', $col, $_)
369                                 } $attr->{-label} // ()),
370                                 $multiple ? '<span class="inline multiinput">' : (),
371                                 (map {
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
376                                 ),
377                                 $multiple ? '</span>' : (),
378                                 (map {
379                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
380                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
381                                 } grep { -e } $row->imagepath($col)),
382                         );
383                 }
384         }
385
386         sub imagepath {
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';
390                 return;
391         }
392 }
393 bless $row, 'Shiar_Sheet::FormRow';
394 :>
395 <h1>Words <:= $title :></h1>
396
397 <div class="inline">
398
399 <form action="?" method="post">
400 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
401 <ul>
402 <:
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;
411                 print '</span>';
412         say '</p></li>';
413 }
414
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 };
423         }
424         my %existing = map { $_->{lang} => 1 } $row, @children;
425         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
426
427         for my $ref (@children) {
428                 printf(
429                         '<li><label for="%s" title="%3$s">%s </label>',
430                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
431                 );
432                 printf(
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} // ''),
436                 );
437         }
438         say '</ul></div></li>';
439 }
440 :>
441 </ul>
442 <p>
443         <input type="submit" value="Save" />
444         <input type="submit" value="New" formaction="/writer?copy=cat" />
445 </p>
446 </form>
447
448 <:
449 if ($row->{id}) {
450 :>
451 <section id="nav">
452 <h2>Hierarchy</h2>
453
454 <:
455 say '<ul>';
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});
459 }
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});
464 }
465 :>
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" />
470 </form></li>
471 </ul>
472 </section>
473 <:
474 }
475 :>
476 </div>