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