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