word edit: translation shorthand slash for alternate names
[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 <link rel="stylesheet" type="text/css" media="all" href="/editor.css" />
9 <script src="/writer.js"></script>
10 EOT
11 });
12
13 use List::Util qw( pairs pairkeys );
14
15 my $db = eval {
16         require Shiar_Sheet::DB;
17         Shiar_Sheet::DB->connect;
18 } or Abort('Database error', 501, $@);
19
20 my $user = eval {
21         if (defined $post{username}) {
22                 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
23         }
24         elsif (exists $fields{logout}) {
25                 require CGI::Cookie;
26                 if (AddCookie(CGI::Cookie->new(
27                         -name    => 'login',
28                         -value   => '',
29                         -path    => '/writer',
30                         -expires => 'now',
31                 )->as_string)) {
32                         delete $cookie{login};
33                         die "Logged out as requested\n";
34                 }
35                 Alert("Failed to log out", "Login cookie could not be removed.");
36         }
37
38         my $cookiedata = $cookie{login} or return;
39         my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
40         my %rowmatch = (username => $name, pass => $key);
41         my $found = $db->select(login => '*', \%rowmatch)->hash
42                 or die "Invalid user or password\n";
43
44         eval {
45                 require CGI::Cookie;
46                 my $httpcookie = CGI::Cookie->new(
47                         -name    => 'login',
48                         -value   => join(':', @{$found}{qw( username pass )}),
49                         -path    => '/writer',
50                 ) or die "prepared object is empty\n";
51                 AddCookie($httpcookie->as_string);
52         } or Abort(["Unable to create login cookie", $@], 403);
53
54         return $found;
55 } or do {
56         say '<h1>Login to edit words</h1>';
57         Alert('Access denied', $@) if $@;
58         say '<form action="?" method="post" class="inline"><ul>';
59         my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
60         say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
61                 username => {-label => 'User name'},
62                 pass     => {-label => 'Password', type => 'password'},
63         );
64         say '<li><input type="submit" value="Login" /></li>';
65         say '</ul></form>';
66         exit;
67 };
68
69 my %lang = (
70         nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
71         en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
72         eo => ['<span style="color:green">★</span>', 'esperanto'],
73         ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
74 );
75 my @wordcols = pairkeys
76 my %wordcol = (
77         lang    => {-label => 'Language', -select => {
78                 map { $_ => "@{$lang{$_}}" } keys %lang
79         }},
80         cat     => [{-label => 'Category'}, 'ref'],
81         ref     => {-label => 'Reference'},
82         prio    => [
83                 {-label => 'Level', -select => sub {
84                         my ($row) = @_;
85                         my @enum = qw[ essential basic common distinctive optional invisible ];
86                         return {
87                                 ('' => 'parent') x (defined $row->{ref}),
88                                 map { $_ => $enum[$_] } 0 .. $#enum
89                         };
90                 }},
91                 'cover', 'grade',
92         ],
93         cover   => {-label => 'Highlighted', type => 'checkbox'},
94         grade   => {-label => 'Order', type => 'number'},
95         form    => {-label => 'Title'},
96         alt     => {-label => 'Synonyms', -multiple => 1},
97         wptitle => {-label => 'Wikipedia'},
98         source  => {-label => 'Image'},
99         thumb   => {-label => 'Convert options', -multiple => 1},
100 );
101
102 if (my $search = $fields{q}) {
103         my %filter = (form => {ilike => '%'.$search.'%'});
104         my $results = $db->select(word => '*', \%filter);
105         say '<h1>Search</h1><ul>';
106         printf("<li><small>%s</small> %s %s</li>\n",
107                 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
108                 sprintf('<img src="/%s" style="height:3ex; width:auto" />', Shiar_Sheet::FormRow::imagepath($_ => 'thumb')) x defined $_->{thumb}
109         ) for $results->hashes;
110         say "</ul>\n";
111         exit;
112 }
113
114 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
115 my $row;
116 if ($find) {
117         $row = $db->select(word => '*', $find)->hash
118                 or Abort("Word not found", 404);
119 }
120
121 if (exists $get{copy}) {
122         $row = {%{$row}{ qw(prio lang cat) }};
123 }
124 elsif (defined $post{form}) {{
125         sub parseinput {
126                 return if not length $_[0];
127                 require Encode;
128                 return Encode::decode_utf8($_[0]);
129         }
130
131         my $replace = $row;
132         $row = {map { $_ =>
133                 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
134                         [ map { parseinput($_) } $post{'@'.$_}->@* ] :
135                 scalar parseinput($post{$_})
136         } keys %wordcol};
137
138         if (!$row->{form}) {
139                 if ($row->{ref} ne 'delete') {
140                         Alert("Empty title",
141                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
142                         );
143                 }
144                 else {
145                         $db->delete(word => $find);
146                         Alert("Entry removed");
147                 }
148                 next;
149         }
150
151         eval {
152                 my %res = (returning => '*');
153                 $row->{creator} = $user->{id} unless $find;
154                 $row->{updated} = ['now()'];
155                 my $query = $find ? $db->update(word => $row, $find, \%res) :
156                         $db->insert(word => $row, \%res);
157                 $row = $query->hash;
158         } or do {
159                 Alert("Entry could not be saved", $@);
160                 next;
161         };
162
163         eval {
164                 while (my ($lang, $val) = each %post) {
165                         my $field = $lang;
166                         $lang =~ s/^trans-// or next;
167                         $val = parseinput($val) or next;
168                         my %subrow = (
169                                 ref   => $row->{id},
170                                 lang  => $lang,
171                                 form  => $val,
172                                 prio  => undef,
173                         );
174                         $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
175                         $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
176                         $db->insert(word => \%subrow);
177                         delete $fields{$field};
178                 }
179                 return 1;
180         } or Alert('Error creating translation entries', $@);
181
182         my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
183         my $reimage = eval {
184                 ($row->{source} // '') ne ($replace->{source} // '') or return;
185                 # copy changed remote url to local file
186                 unlink $imgpath if -e $imgpath;
187                 my $download = $row->{source} or return 1;
188                 require LWP::UserAgent;
189                 my $ua = LWP::UserAgent->new;
190                 $ua->agent('/');
191                 my $status = $ua->mirror($download, $imgpath);
192                 $status->is_success
193                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
194         };
195         !$@ or Alert(["Source image not found", $@]);
196
197         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
198         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
199         $reimage++ if $fields{rethumb};  # force refresh
200
201         my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
202         if ($reimage) {
203                 if (-e $imgpath) {
204                         my $xyres = $row->{cover} ? '600x400' : '300x200';
205                         my @cmds = @{ $row->{thumb} // [] };
206                         if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
207                                 # replace option by permillage crop
208                                 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
209                                 splice @cmds, $cmdarg, 2, (
210                                         -set => 'option:distort:viewport' => sprintf(
211                                                 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
212                                                 ($dim[2] || 1) - $dim[0], # width  = x2 - x1
213                                                 ($dim[3] || 1) - $dim[1], # height = y2 - y1
214                                                 @dim[0, 1]                # offset = x1,y1
215                                         ),
216                                         -distort => SRT => 0, # noop transform to apply viewport
217                                 );
218                         }
219                         @cmds = (
220                                 'convert',
221                                 $imgpath,
222                                 -delete => '1--1', -background => 'white',
223                                 -gravity => defined $row->{thumb} ? 'northwest' : 'center',
224                                 @cmds,
225                                 -resize => "$xyres^", -extent => $xyres,
226                                 '-strip', -quality => '60%', -interlace => 'plane',
227                                 $thumbpath
228                         );
229                         eval {
230                                 require IPC::Run;
231                                 my $output;
232                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
233                                         or die $output ||
234                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
235                         } or Alert([
236                                 "Thumbnail image not generated",
237                                 "Failed to convert source image.",
238                         ], "@cmds\n$@");
239                 }
240                 else {
241                         unlink $thumbpath;
242                 }
243         }
244 }}
245 else {
246         $row->{lang} //= $user->{editlang}->[0];
247         $row->{$_} = $get{$_} for keys %get;
248         $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
249 }
250
251 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
252
253 package Shiar_Sheet::FormRow {
254         use PLP::Functions 'EscapeHTML';
255
256         sub input {
257                 my ($row, $col, $attr) = @_;
258                 my $val = $row->{$col} // '';
259                 my $html = '';
260                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
261
262                 if (my $options = $attr->{-select}) {
263                         $options = $options->(@_) if ref $options eq 'CODE';
264                         $options->{$val} //= "unknown ($val)";  # preserve current
265                         return (
266                                 sprintf('<select id="%s" name="%1$s">', $col),
267                                 (map { sprintf('<option value="%s"%s>%s</option>',
268                                         $_, $val eq $_ && ' selected', $options->{$_}
269                                 ) } sort keys %{$options}),
270                                 '</select>',
271                         );
272                 }
273                 elsif ($attr->{type} eq 'checkbox') {
274                         $html .= ' checked' if $val;
275                         return sprintf(
276                                 join('',
277                                         '<label>',
278                                         '<input name="%1$s" value="0" type="hidden" />',
279                                         '<input id="%s" name="%1$s" value="1"%s>',
280                                         ' %s</label>',
281                                 ), $col, $html, $attr->{-label}
282                         );
283                 }
284                 else {
285                         my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
286                         return (
287                                 (map {
288                                         sprintf('<label for="%s">%s</label>', $col, $_)
289                                 } $attr->{-label} // ()),
290                                 $multiple ? '<span class="inline multiinput">' : (),
291                                 (map {
292                                         sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
293                                 } ref $val eq 'ARRAY' ? @{$val} : ()),
294                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
295                                         $col, $multiple ? '' : EscapeHTML($val), $html
296                                 ),
297                                 $multiple ? '</span>' : (),
298                                 (map {
299                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
300                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
301                                 } grep { -e } $row->imagepath($col)),
302                         );
303                 }
304         }
305
306         sub imagepath {
307                 my ($row, $col) = @_;
308                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
309                 return "data/word/en/$row->{id}.jpg"  if $col eq 'thumb';
310                 return;
311         }
312 }
313 bless $row, 'Shiar_Sheet::FormRow';
314 :>
315 <h1>Words <:= $title :></h1>
316
317 <div class="inline">
318
319 <form action="?" method="post">
320 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
321 <ul>
322 <:
323 for my $col (@wordcols) {
324         my $info = $wordcol{$col} or next;
325         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
326         my $title = ref $attr ? delete $attr->{-label} : $attr;
327         printf '<li><label for="%s">%s</label><p>', $col, $title;
328                 printf '<span class=inline>';
329                 print $row->input($col => $attr);
330                 print $row->input($_ => delete $wordcol{$_}) for @span;
331                 print '</span>';
332         say '</p></li>';
333 }
334
335 if (not $row->{ref}) {
336         printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
337                 'trans', 'Translations';
338         my @children = !$row->{id} ? () :
339                 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
340         while (my ($lang, $val) = each %fields) {
341                 $lang =~ s/^trans-// or next;
342                 push @children, { lang => $lang, form => $val };
343         }
344         my %existing = map { $_->{lang} => 1 } $row, @children;
345         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
346
347         for my $ref (@children) {
348                 printf(
349                         '<li><label for="%s" title="%3$s">%s </label>',
350                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
351                 );
352                 printf(
353                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
354                         '<input id="%s" name="%1$s" value="%3$s" />',
355                         "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
356                 );
357         }
358         say '</ul></div></li>';
359 }
360 :>
361 </ul>
362 <p>
363         <input type="submit" value="Save" />
364         <input type="submit" value="New" formaction="/writer?copy=cat" />
365 </p>
366 </form>
367
368 <:
369 if ($row->{id}) {
370 :>
371 <section id="nav">
372 <h2>Hierarchy</h2>
373
374 <:
375 say '<ul>';
376 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
377 while (my $ref = $parents->hash) {
378         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
379 }
380 say "<li><strong>$row->{form}</strong></li>";
381 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
382 while (my $ref = $children->hash) {
383         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
384 }
385 :>
386 <li><form action="/writer">
387         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
388         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
389         <input type="submit" value="Add" />
390 </form></li>
391 </ul>
392 </section>
393 <:
394 }
395 :>
396 </div>