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 my $rootpath = ($ENV{REQUEST_URI} // '/writer') =~ s{(?<!^)/.+}{}r;
22 if (defined $post{username}) {
23 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
25 elsif (exists $fields{logout}) {
27 if (AddCookie(CGI::Cookie->new(
33 delete $cookie{login};
34 die "Logged out as requested\n";
36 Alert("Failed to log out", "Login cookie could not be removed.");
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";
47 my $httpcookie = CGI::Cookie->new(
49 -value => join(':', @{$found}{qw( username pass )}),
51 ) or die "prepared object is empty\n";
52 AddCookie($httpcookie->as_string);
53 } or Abort(["Unable to create login cookie", $@], 403);
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'},
65 say '<li><input type="submit" value="Login" /></li>';
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'],
77 my @wordcols = pairkeys
79 lang => {-label => 'Language', -select => {
80 map { $_ => "@{$lang{$_}}" } keys %lang
82 cat => [{-label => 'Category'}, 'ref'],
83 ref => {-label => 'Reference'},
85 {-label => 'Level', -select => sub {
87 my @enum = qw[ essential basic common distinctive optional invisible ];
89 ('' => 'parent') x (defined $row->{ref}),
90 map { $_ => $enum[$_] } 0 .. $#enum
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'},
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;
117 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
120 $row = $db->select(word => '*', $find)->hash
121 or Abort("Word not found", 404);
124 if (exists $get{copy}) {
125 $row = {%{$row}{ qw(prio lang cat) }};
127 elsif (defined $post{form}) {{
129 return if not length $_[0];
131 return Encode::decode_utf8($_[0]);
136 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
137 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
138 scalar parseinput($post{$_})
142 if ($row->{ref} ne 'delete') {
144 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
148 $db->delete(word => $find);
149 Alert("Entry removed");
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);
162 Alert("Entry could not be saved", $@);
167 while (my ($lang, $val) = each %post) {
169 $lang =~ s/^trans-// or next;
170 $val = parseinput($val) or next;
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};
183 } or Alert('Error creating translation entries', $@);
185 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
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;
194 my $status = $ua->mirror($download, $imgpath);
196 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
198 !$@ or Alert(["Source image not found", $@]);
200 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
201 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
202 $reimage++ if $fields{rethumb}; # force refresh
204 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
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
219 -distort => SRT => 0, # noop transform to apply viewport
225 -delete => '1--1', -background => 'white',
226 -gravity => defined $row->{thumb} ? 'northwest' : 'center',
228 -resize => "$xyres^", -extent => $xyres,
229 '-strip', -quality => '60%', -interlace => 'plane',
235 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
237 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
239 "Thumbnail image not generated",
240 "Failed to convert source image.",
249 $row->{lang} //= $user->{editlang}->[0];
250 $row->{$_} = $get{$_} for keys %get;
251 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
254 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
256 package Shiar_Sheet::FormRow {
257 use PLP::Functions 'EscapeHTML';
260 my ($row, $col, $attr) = @_;
261 my $val = $row->{$col} // '';
263 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
265 if (my $options = $attr->{-select}) {
266 $options = $options->(@_) if ref $options eq 'CODE';
267 $options->{$val} //= "unknown ($val)"; # preserve current
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}),
276 elsif ($attr->{type} eq 'textarea') {
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)
286 elsif ($attr->{type} eq 'checkbox') {
287 $html .= ' checked' if $val;
291 '<input name="%1$s" value="0" type="hidden" />',
292 '<input id="%s" name="%1$s" value="1"%s>',
294 ), $col, $html, $attr->{-label}
298 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
301 sprintf('<label for="%s">%s</label>', $col, $_)
302 } $attr->{-label} // ()),
303 $multiple ? '<span class="inline multiinput">' : (),
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
310 $multiple ? '</span>' : (),
312 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
313 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
314 } grep { -e } $row->imagepath($col)),
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';
326 bless $row, 'Shiar_Sheet::FormRow';
328 <h1>Words <:= $title :></h1>
332 <form action="?" method="post">
333 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
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;
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 };
357 my %existing = map { $_->{lang} => 1 } $row, @children;
358 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
360 for my $ref (@children) {
362 '<li><label for="%s" title="%3$s">%s </label>',
363 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
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} // ''),
371 say '</ul></div></li>';
376 <input type="submit" value="Save" />
377 <input type="submit" value="New" formaction="/writer?copy=cat" />
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});
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});
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" />