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