05e14659e3fb2769ec44d08a6776f675509e4978
[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                         $db->insert(word => \%subrow);
176                         delete $fields{$field};
177                 }
178                 return 1;
179         } or Alert('Error creating translation entries', $@);
180
181         my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
182         my $reimage = eval {
183                 ($row->{source} // '') ne ($replace->{source} // '') or return;
184                 # copy changed remote url to local file
185                 unlink $imgpath if -e $imgpath;
186                 my $download = $row->{source} or return 1;
187                 require LWP::UserAgent;
188                 my $ua = LWP::UserAgent->new;
189                 $ua->agent('/');
190                 my $status = $ua->mirror($download, $imgpath);
191                 $status->is_success
192                         or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
193         };
194         !$@ or Alert(["Source image not found", $@]);
195
196         $reimage ||= $row->{thumb} ~~ $replace->{thumb};  # different convert
197         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
198         $reimage++ if $fields{rethumb};  # force refresh
199
200         my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
201         if ($reimage) {
202                 if (-e $imgpath) {
203                         my $xyres = $row->{cover} ? '600x400' : '300x200';
204                         my @cmds = @{ $row->{thumb} // [] };
205                         if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
206                                 # replace option by permillage crop
207                                 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
208                                 splice @cmds, $cmdarg, 2, (
209                                         -set => 'option:distort:viewport' => sprintf(
210                                                 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
211                                                 ($dim[2] || 1) - $dim[0], # width  = x2 - x1
212                                                 ($dim[3] || 1) - $dim[1], # height = y2 - y1
213                                                 @dim[0, 1]                # offset = x1,y1
214                                         ),
215                                         -distort => SRT => 0, # noop transform to apply viewport
216                                 );
217                         }
218                         @cmds = (
219                                 'convert',
220                                 $imgpath,
221                                 -delete => '1--1', -background => 'white',
222                                 -gravity => defined $row->{thumb} ? 'northwest' : 'center',
223                                 @cmds,
224                                 -resize => "$xyres^", -extent => $xyres,
225                                 '-strip', -quality => '60%', -interlace => 'plane',
226                                 $thumbpath
227                         );
228                         eval {
229                                 require IPC::Run;
230                                 my $output;
231                                 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
232                                         or die $output ||
233                                                 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
234                         } or Alert([
235                                 "Thumbnail image not generated",
236                                 "Failed to convert source image.",
237                         ], "@cmds\n$@");
238                 }
239                 else {
240                         unlink $thumbpath;
241                 }
242         }
243 }}
244 else {
245         $row->{lang} //= $user->{editlang}->[0];
246         $row->{$_} = $get{$_} for keys %get;
247         $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
248 }
249
250 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
251
252 package Shiar_Sheet::FormRow {
253         use PLP::Functions 'EscapeHTML';
254
255         sub input {
256                 my ($row, $col, $attr) = @_;
257                 my $val = $row->{$col} // '';
258                 my $html = '';
259                 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
260
261                 if (my $options = $attr->{-select}) {
262                         $options = $options->(@_) if ref $options eq 'CODE';
263                         $options->{$val} //= "unknown ($val)";  # preserve current
264                         return (
265                                 sprintf('<select id="%s" name="%1$s">', $col),
266                                 (map { sprintf('<option value="%s"%s>%s</option>',
267                                         $_, $val eq $_ && ' selected', $options->{$_}
268                                 ) } sort keys %{$options}),
269                                 '</select>',
270                         );
271                 }
272                 elsif ($attr->{type} eq 'checkbox') {
273                         $html .= ' checked' if $val;
274                         return sprintf(
275                                 join('',
276                                         '<label>',
277                                         '<input name="%1$s" value="0" type="hidden" />',
278                                         '<input id="%s" name="%1$s" value="1"%s>',
279                                         ' %s</label>',
280                                 ), $col, $html, $attr->{-label}
281                         );
282                 }
283                 else {
284                         my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
285                         return (
286                                 (map {
287                                         sprintf('<label for="%s">%s</label>', $col, $_)
288                                 } $attr->{-label} // ()),
289                                 $multiple ? '<span class="inline multiinput">' : (),
290                                 (map {
291                                         sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
292                                 } ref $val eq 'ARRAY' ? @{$val} : ()),
293                                 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
294                                         $col, $multiple ? '' : EscapeHTML($val), $html
295                                 ),
296                                 $multiple ? '</span>' : (),
297                                 (map {
298                                         sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
299                                                 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
300                                 } grep { -e } $row->imagepath($col)),
301                         );
302                 }
303         }
304
305         sub imagepath {
306                 my ($row, $col) = @_;
307                 return "data/word/org/$row->{id}.jpg"   if $col eq 'source';
308                 return "data/word/en/$row->{id}.jpg"  if $col eq 'thumb';
309                 return;
310         }
311 }
312 bless $row, 'Shiar_Sheet::FormRow';
313 :>
314 <h1>Words <:= $title :></h1>
315
316 <div class="inline">
317
318 <form action="?" method="post">
319 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
320 <ul>
321 <:
322 for my $col (@wordcols) {
323         my $info = $wordcol{$col} or next;
324         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
325         my $title = ref $attr ? delete $attr->{-label} : $attr;
326         printf '<li><label for="%s">%s</label><p>', $col, $title;
327                 printf '<span class=inline>';
328                 print $row->input($col => $attr);
329                 print $row->input($_ => delete $wordcol{$_}) for @span;
330                 print '</span>';
331         say '</p></li>';
332 }
333
334 if (not $row->{ref}) {
335         printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
336                 'trans', 'Translations';
337         my @children = !$row->{id} ? () :
338                 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
339         while (my ($lang, $val) = each %fields) {
340                 $lang =~ s/^trans-// or next;
341                 push @children, { lang => $lang, form => $val };
342         }
343         my %existing = map { $_->{lang} => 1 } $row, @children;
344         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
345
346         for my $ref (@children) {
347                 printf(
348                         '<li><label for="%s" title="%3$s">%s </label>',
349                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
350                 );
351                 printf(
352                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
353                         '<input id="%s" name="%1$s" value="%3$s" />',
354                         "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
355                 );
356         }
357         say '</ul></div></li>';
358 }
359 :>
360 </ul>
361 <p>
362         <input type="submit" value="Save" />
363         <input type="submit" value="New" formaction="/writer?copy=cat" />
364 </p>
365 </form>
366
367 <:
368 if ($row->{id}) {
369 :>
370 <section id="nav">
371 <h2>Hierarchy</h2>
372
373 <:
374 say '<ul>';
375 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
376 while (my $ref = $parents->hash) {
377         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
378 }
379 say "<li><strong>$row->{form}</strong></li>";
380 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
381 while (my $ref = $children->hash) {
382         printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
383 }
384 :>
385 <li><form action="/writer">
386         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
387         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
388         <input type="submit" value="Add" />
389 </form></li>
390 </ul>
391 </section>
392 <:
393 }
394 :>
395 </div>