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