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}", 'русский'],
75 my @wordcols = pairkeys
77 lang => {-label => 'Language', -select => {
78 map { $_ => "@{$lang{$_}}" } keys %lang
80 cat => [{-label => 'Category'}, 'ref'],
81 ref => {-label => 'Reference'},
83 {-label => 'Level', -select => sub {
85 my @enum = qw[ essential basic common distinctive optional invisible ];
87 ('' => 'parent') x (defined $row->{ref}),
88 map { $_ => $enum[$_] } 0 .. $#enum
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},
101 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
105 $row = $db->select(word => '*', $find)->hash
106 or Abort("Word not found", 404);
109 if (exists $get{copy}) {
110 $row = {%{$row}{ qw(prio lang cat) }};
112 elsif (defined $post{form}) {{
114 return if not length $_[0];
116 return Encode::decode_utf8($_[0]);
121 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
122 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
123 scalar parseinput($post{$_})
127 if ($row->{ref} ne 'delete') {
129 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
133 $db->delete(word => $find);
134 Alert("Entry removed");
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);
147 Alert("Entry could not be saved", $@);
152 while (my ($lang, $val) = each %post) {
154 $lang =~ s/^trans-// or next;
155 $val = parseinput($val) or next;
162 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
163 $db->insert(word => \%subrow);
164 delete $fields{$field};
167 } or Alert('Error creating translation entries', $@);
169 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
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;
178 my $status = $ua->mirror($download, $imgpath);
180 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
182 !$@ or Alert(["Source image not found", $@]);
184 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
185 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
186 $reimage++ if $fields{rethumb}; # force refresh
188 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
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
203 -distort => SRT => 0, # noop transform to apply viewport
209 -delete => '1--1', -background => 'white',
210 -gravity => @cmds ? 'northwest' : 'center',
212 -resize => "$xyres^", -extent => $xyres,
213 '-strip', -quality => '60%', -interlace => 'plane',
219 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
221 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
223 "Thumbnail image not generated",
224 "Failed to convert source image.",
233 $row->{lang} //= $user->{editlang}->[0];
234 $row->{$_} = $get{$_} for keys %get;
235 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
238 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
240 package Shiar_Sheet::FormRow {
241 use PLP::Functions 'EscapeHTML';
244 my ($row, $col, $attr) = @_;
245 my $val = $row->{$col} // '';
247 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
249 if (my $options = $attr->{-select}) {
250 $options = $options->(@_) if ref $options eq 'CODE';
251 $options->{$val} //= "unknown ($val)"; # preserve current
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}),
260 elsif ($attr->{type} eq 'checkbox') {
261 $html .= ' checked' if $val;
265 '<input name="%1$s" value="0" type="hidden" />',
266 '<input id="%s" name="%1$s" value="1"%s>',
268 ), $col, $html, $attr->{-label}
272 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
275 sprintf('<label for="%s">%s</label>', $col, $_)
276 } $attr->{-label} // ()),
277 $multiple ? '<span class="inline multiinput">' : (),
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
284 $multiple ? '</span>' : (),
286 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
287 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
288 } grep { -e } $row->imagepath($col)),
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';
300 bless $row, 'Shiar_Sheet::FormRow';
302 <h1>Words <:= $title :></h1>
306 <form action="?" method="post">
307 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
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;
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 };
331 my %existing = map { $_->{lang} => 1 } $row, @children;
332 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
334 for my $ref (@children) {
336 '<li><label for="%s" title="%3$s">%s </label>',
337 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
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} // ''),
345 say '</ul></div></li>';
350 <input type="submit" value="Save" />
351 <input type="submit" value="New" formaction="/writer?copy=cat" />
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});
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});
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" />