4 title => 'words cheat sheet admin',
8 <link rel="stylesheet" type="text/css" media="all" href="/editor.css" />
9 <script src="/writer.js"></script>
13 use List::Util qw( pairs pairkeys );
16 require Shiar_Sheet::DB;
17 Shiar_Sheet::DB->connect;
18 } or Abort('Database error', 501, $@);
21 if (defined $post{username}) {
22 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
24 elsif (exists $fields{logout}) {
26 if (AddCookie(CGI::Cookie->new(
32 delete $cookie{login};
33 die "Logged out as requested\n";
35 Alert("Failed to log out", "Login cookie could not be removed.");
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";
46 my $httpcookie = CGI::Cookie->new(
48 -value => join(':', @{$found}{qw( username pass )}),
50 ) or die "prepared object is empty\n";
51 AddCookie($httpcookie->as_string);
52 } or Abort(["Unable to create login cookie", $@], 403);
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'},
64 say '<li><input type="submit" value="Login" /></li>';
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 la => ["\N{PUSHPIN}", 'latin'],
76 my @wordcols = pairkeys
78 lang => {-label => 'Language', -select => {
79 map { $_ => "@{$lang{$_}}" } keys %lang
81 cat => [{-label => 'Category'}, 'ref'],
82 ref => {-label => 'Reference'},
84 {-label => 'Level', -select => sub {
86 my @enum = qw[ essential basic common distinctive optional invisible ];
88 ('' => 'parent') x (defined $row->{ref}),
89 map { $_ => $enum[$_] } 0 .. $#enum
94 cover => {-label => 'Highlighted', type => 'checkbox'},
95 grade => {-label => 'Order', type => 'number'},
96 form => {-label => 'Title'},
97 alt => {-label => 'Synonyms', -multiple => 1},
98 wptitle => {-label => 'Wikipedia'},
99 source => {-label => 'Image'},
100 thumb => {-label => 'Convert options', -multiple => 1},
103 if (my $search = $fields{q}) {
104 my %filter = (form => {ilike => '%'.$search.'%'});
105 my $results = $db->select(word => '*', \%filter);
106 say '<h1>Search</h1><ul>';
107 printf("<li><small>%s</small> %s %s</li>\n",
108 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
109 sprintf('<img src="/%s" style="height:3ex; width:auto" />', Shiar_Sheet::FormRow::imagepath($_ => 'thumb')) x defined $_->{thumb}
110 ) for $results->hashes;
115 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
118 $row = $db->select(word => '*', $find)->hash
119 or Abort("Word not found", 404);
122 if (exists $get{copy}) {
123 $row = {%{$row}{ qw(prio lang cat) }};
125 elsif (defined $post{form}) {{
127 return if not length $_[0];
129 return Encode::decode_utf8($_[0]);
134 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
135 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
136 scalar parseinput($post{$_})
140 if ($row->{ref} ne 'delete') {
142 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
146 $db->delete(word => $find);
147 Alert("Entry removed");
153 my %res = (returning => '*');
154 $row->{creator} = $user->{id} unless $find;
155 $row->{updated} = ['now()'];
156 my $query = $find ? $db->update(word => $row, $find, \%res) :
157 $db->insert(word => $row, \%res);
160 Alert("Entry could not be saved", $@);
165 while (my ($lang, $val) = each %post) {
167 $lang =~ s/^trans-// or next;
168 $val = parseinput($val) or next;
175 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
176 $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
177 $db->insert(word => \%subrow);
178 delete $fields{$field};
181 } or Alert('Error creating translation entries', $@);
183 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
185 ($row->{source} // '') ne ($replace->{source} // '') or return;
186 # copy changed remote url to local file
187 unlink $imgpath if -e $imgpath;
188 my $download = $row->{source} or return 1;
189 require LWP::UserAgent;
190 my $ua = LWP::UserAgent->new;
192 my $status = $ua->mirror($download, $imgpath);
194 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
196 !$@ or Alert(["Source image not found", $@]);
198 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
199 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
200 $reimage++ if $fields{rethumb}; # force refresh
202 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
205 my $xyres = $row->{cover} ? '600x400' : '300x200';
206 my @cmds = @{ $row->{thumb} // [] };
207 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
208 # replace option by permillage crop
209 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
210 splice @cmds, $cmdarg, 2, (
211 -set => 'option:distort:viewport' => sprintf(
212 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
213 ($dim[2] || 1) - $dim[0], # width = x2 - x1
214 ($dim[3] || 1) - $dim[1], # height = y2 - y1
215 @dim[0, 1] # offset = x1,y1
217 -distort => SRT => 0, # noop transform to apply viewport
223 -delete => '1--1', -background => 'white',
224 -gravity => defined $row->{thumb} ? 'northwest' : 'center',
226 -resize => "$xyres^", -extent => $xyres,
227 '-strip', -quality => '60%', -interlace => 'plane',
233 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
235 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
237 "Thumbnail image not generated",
238 "Failed to convert source image.",
247 $row->{lang} //= $user->{editlang}->[0];
248 $row->{$_} = $get{$_} for keys %get;
249 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
252 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
254 package Shiar_Sheet::FormRow {
255 use PLP::Functions 'EscapeHTML';
258 my ($row, $col, $attr) = @_;
259 my $val = $row->{$col} // '';
261 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
263 if (my $options = $attr->{-select}) {
264 $options = $options->(@_) if ref $options eq 'CODE';
265 $options->{$val} //= "unknown ($val)"; # preserve current
267 sprintf('<select id="%s" name="%1$s">', $col),
268 (map { sprintf('<option value="%s"%s>%s</option>',
269 $_, $val eq $_ && ' selected', $options->{$_}
270 ) } sort keys %{$options}),
274 elsif ($attr->{type} eq 'checkbox') {
275 $html .= ' checked' if $val;
279 '<input name="%1$s" value="0" type="hidden" />',
280 '<input id="%s" name="%1$s" value="1"%s>',
282 ), $col, $html, $attr->{-label}
286 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
289 sprintf('<label for="%s">%s</label>', $col, $_)
290 } $attr->{-label} // ()),
291 $multiple ? '<span class="inline multiinput">' : (),
293 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
294 } ref $val eq 'ARRAY' ? @{$val} : ()),
295 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
296 $col, $multiple ? '' : EscapeHTML($val), $html
298 $multiple ? '</span>' : (),
300 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
301 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
302 } grep { -e } $row->imagepath($col)),
308 my ($row, $col) = @_;
309 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
310 return "data/word/en/$row->{id}.jpg" if $col eq 'thumb';
314 bless $row, 'Shiar_Sheet::FormRow';
316 <h1>Words <:= $title :></h1>
320 <form action="?" method="post">
321 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
324 for my $col (@wordcols) {
325 my $info = $wordcol{$col} or next;
326 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
327 my $title = ref $attr ? delete $attr->{-label} : $attr;
328 printf '<li><label for="%s">%s</label><p>', $col, $title;
329 printf '<span class=inline>';
330 print $row->input($col => $attr);
331 print $row->input($_ => delete $wordcol{$_}) for @span;
336 if (not $row->{ref}) {
337 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
338 'trans', 'Translations';
339 my @children = !$row->{id} ? () :
340 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
341 while (my ($lang, $val) = each %fields) {
342 $lang =~ s/^trans-// or next;
343 push @children, { lang => $lang, form => $val };
345 my %existing = map { $_->{lang} => 1 } $row, @children;
346 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
348 for my $ref (@children) {
350 '<li><label for="%s" title="%3$s">%s </label>',
351 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
354 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
355 '<input id="%s" name="%1$s" value="%3$s" />',
356 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
359 say '</ul></div></li>';
364 <input type="submit" value="Save" />
365 <input type="submit" value="New" formaction="/writer?copy=cat" />
377 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
378 while (my $ref = $parents->hash) {
379 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
381 say "<li><strong>$row->{form}</strong></li>";
382 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
383 while (my $ref = $children->hash) {
384 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
387 <li><form action="/writer">
388 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
389 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
390 <input type="submit" value="Add" />