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