word edit: restrict access by login cookie
[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         my $cookiedata = $cookie{login} or return;
120         my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
121         my %rowmatch = (username => $name, pass => $key);
122         $db->select(login => '*', \%rowmatch)->hash;
123 } or Abort('Login required', 403);
124
125 my %lang = (
126         nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
127         en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
128         eo => ['<span style="color:green">★</span>', 'esperanto'],
129         ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
130 );
131 my @wordcols = pairkeys
132 my %wordcol = (
133         lang    => {-label => 'Language', -select => {
134                 map { $_ => "@{$lang{$_}}" } keys %lang
135         }},
136         cat     => [{-label => 'Category'}, 'ref'],
137         ref     => {-label => 'Reference'},
138         prio    => [
139                 {-label => 'Level', -select => [qw(
140                         essential basic common distinctive rare invisible
141                 )]},
142                 'cover', 'grade',
143         ],
144         cover   => {-label => 'Highlighted', type => 'checkbox'},
145         grade   => {-label => 'Order', type => 'number'},
146         form    => {-label => 'Title'},
147         alt     => {-label => 'Synonyms', -multiple => 1},
148         wptitle => {-label => 'Wikipedia'},
149         source  => {-label => 'Image'},
150         thumb   => {-label => 'Convert options', -multiple => 1},
151 );
152 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
153
154 my $row;
155 if ($find) {
156         $row = $db->select(word => '*', $find)->hash
157                 or Abort("Word not found", 404);
158 }
159
160 if (exists $get{copy}) {
161         $row = {%{$row}{ qw(prio lang cat) }};
162 }
163 elsif ($ENV{REQUEST_METHOD} eq 'POST') {{
164         sub parseinput {
165                 return if not length $_[0];
166                 require Encode;
167                 return Encode::decode_utf8($_[0]);
168         }
169
170         my $replace = $row;
171         $row = {map { $_ =>
172                 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
173                         [ map { parseinput($_) } $post{'@'.$_}->@* ] :
174                 scalar parseinput($post{$_})
175         } keys %wordcol};
176
177         if (!$row->{form}) {
178                 if ($row->{ref} ne 'delete') {
179                         Alert("Empty title",
180                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
181                         );
182                 }
183                 else {
184                         $db->delete(word => $find);
185                         Alert("Entry removed");
186                 }
187                 next;
188         }
189
190         eval {
191                 my %res = (returning => '*');
192                 my $query = $find ? $db->update(word => $row, $find, \%res) :
193                         $db->insert(word => $row, \%res);
194                 $row = $query->hash;
195         } or do {
196                 Alert("Entry could not be saved", $@);
197                 next;
198         };
199
200         eval {
201                 while (my ($lang, $val) = each %post) {
202                         my $field = $lang;
203                         $lang =~ s/^trans-// or next;
204                         $db->insert(word => {
205                                 ref   => $row->{id},
206                                 lang  => $lang,
207                                 form  => $_,
208                         }) for parseinput($val);
209                         delete $fields{$field};
210                 }
211                 return 1;
212         } or Alert('Error creating translation entries', $@);
213
214         my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
215         my $reimage = eval {
216                 ($row->{source} // '') ne ($replace->{source} // '') or return;
217                 # copy changed remote url to local file
218                 unlink $imgpath if -e $imgpath;
219                 my $download = $row->{source} or return 1;
220                 require LWP::UserAgent;
221                 my $ua = LWP::UserAgent->new;
222                 $ua->agent('/');
223                 my $status = $ua->mirror($download, $imgpath);
224                 $status->is_success
225                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
226         };
227         !$@ or Alert(["Source image not found", $@]);
228
229         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
230         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
231         $reimage++ if $fields{rethumb};  # force refresh
232
233         my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
234         if ($reimage) {
235                 if (-e $imgpath) {
236                         my $xyres = $row->{cover} ? '600x400' : '300x200';
237                         my @cmds = @{ $row->{thumb} // [] };
238                         if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
239                                 # replace option by permillage crop
240                                 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
241                                 splice @cmds, $cmdarg, 2, (
242                                         -set => 'option:distort:viewport' => sprintf(
243                                                 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
244                                                 ($dim[2] || 1) - $dim[0], # width  = x2 - x1
245                                                 ($dim[3] || 1) - $dim[1], # height = y2 - y1
246                                                 @dim[0, 1]                # offset = x1,y1
247                                         ),
248                                         -distort => SRT => 0, # noop transform to apply viewport
249                                 );
250                         }
251                         @cmds = (
252                                 'convert',
253                                 -delete => '1--1', -background => 'white',
254                                 -gravity => @cmds ? 'northwest' : 'center',
255                                 @cmds,
256                                 -resize => "$xyres^", -extent => $xyres,
257                                 '-strip', -quality => '60%', -interlace => 'plane',
258                                 $imgpath => $thumbpath
259                         );
260                         eval {
261                                 require IPC::Run;
262                                 my $output;
263                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
264                                         or die $output ||
265                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
266                         } or Alert([
267                                 "Thumbnail image not generated",
268                                 "Failed to convert source image.",
269                         ], "@cmds\n$@");
270                 }
271                 else {
272                         unlink $thumbpath;
273                 }
274         }
275 }}
276 else {
277         $row->{prio} //= 1;
278         $row->{$_} = $get{$_} for keys %get;
279 }
280
281 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
282
283 package Shiar_Sheet::FormRow {
284         use PLP::Functions 'EscapeHTML';
285
286         sub input {
287                 my ($row, $col, $attr) = @_;
288                 my $val = $row->{$col} // '';
289                 my $html = '';
290                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
291
292                 if (my $options = $attr->{-select}) {
293                         $options = { map {$_ => $options->[$_]} 0 .. $#{$options} }
294                                 if ref $options eq 'ARRAY';
295                         $options->{$val} //= "unknown ($val)";  # preserve current
296                         return (
297                                 sprintf('<select id="%s" name="%1$s">', $col),
298                                 (map { sprintf('<option value="%s"%s>%s</option>',
299                                         $_, $val eq $_ && ' selected', $options->{$_}
300                                 ) } sort keys %{$options}),
301                                 '</select>',
302                         );
303                 }
304                 elsif ($attr->{type} eq 'checkbox') {
305                         $html .= ' checked' if $val;
306                         return sprintf(
307                                 join('',
308                                         '<label>',
309                                         '<input name="%1$s" value="0" type="hidden" />',
310                                         '<input id="%s" name="%1$s" value="1"%s>',
311                                         ' %s</label>',
312                                 ), $col, $html, $attr->{-label}
313                         );
314                 }
315                 else {
316                         my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
317                         return (
318                                 (map {
319                                         sprintf('<label for="%s">%s</label>', $col, $_)
320                                 } $attr->{-label} // ()),
321                                 $multiple ? '<span class="inline multiinput">' : (),
322                                 (map {
323                                         sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
324                                 } ref $val eq 'ARRAY' ? @{$val} : ()),
325                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
326                                         $col, $multiple ? '' : EscapeHTML($val), $html
327                                 ),
328                                 $multiple ? '</span>' : (),
329                                 (map {
330                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
331                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
332                                 } grep { -e } $row->imagepath($col)),
333                         );
334                 }
335         }
336
337         sub imagepath {
338                 my ($row, $col) = @_;
339                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
340                 return "data/word/en/$row->{form}.jpg"  if $col eq 'thumb';
341                 return;
342         }
343 }
344 bless $row, 'Shiar_Sheet::FormRow';
345 :>
346 <h1>Words <:= $title :></h1>
347
348 <div class="inline">
349
350 <form action="?" method="post">
351 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
352 <ul>
353 <:
354 for my $col (@wordcols) {
355         my $info = $wordcol{$col} or next;
356         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
357         my $title = ref $attr ? delete $attr->{-label} : $attr;
358         printf '<li><label for="%s">%s</label><p>', $col, $title;
359                 printf '<span class=inline>';
360                 print $row->input($col => $attr);
361                 print $row->input($_ => delete $wordcol{$_}) for @span;
362                 print '</span>';
363         say '</p></li>';
364 }
365
366 if ($row->{id} and not $row->{ref}) {
367         printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
368                 'trans', 'Translations';
369         my @children = $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
370         while (my ($lang, $val) = each %fields) {
371                 $lang =~ s/^trans-// or next;
372                 push @children, { lang => $lang, form => $val };
373         }
374         for my $ref (@children) {
375                 printf(
376                         '<li><label for="%s" title="%3$s">%s </label>',
377                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
378                 );
379                 printf(
380                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
381                         '<input id="%s" name="%1$s" value="%3$s" />',
382                         "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form}),
383                 );
384         }
385         say '</ul></div></li>';
386 }
387 :>
388 </ul>
389 <p>
390         <input type="submit" value="Save" />
391         <input type="submit" value="New" formaction="/writer?copy=cat" />
392 </p>
393 </form>
394
395 <:
396 if ($row->{id}) {
397 :>
398 <section id="nav">
399 <h2>Hierarchy</h2>
400
401 <:
402 say '<ul>';
403 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
404 while (my $ref = $parents->hash) {
405         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
406 }
407 say "<li><strong>$row->{form}</strong></li>";
408 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
409 while (my $ref = $children->hash) {
410         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
411 }
412 :>
413 <li><form action="/writer">
414         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
415         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
416         <input type="submit" value="Add" />
417 </form></li>
418 </ul>
419 </section>
420 <:
421 }
422 :>
423 </div>