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