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