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