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},
104 if (my $search = $fields{q}) {
105 my %filter = (form => {ilike => '%'.$search.'%'});
106 my $results = $db->select(word => '*', \%filter);
107 say '<h1>Search</h1><ul>';
108 printf("<li><small>%s</small> %s %s</li>\n",
109 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
110 sprintf('<img src="/%s" style="height:3ex; width:auto" />', Shiar_Sheet::FormRow::imagepath($_ => 'thumb')) x defined $_->{thumb}
111 ) for $results->hashes;
116 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
119 $row = $db->select(word => '*', $find)->hash
120 or Abort("Word not found", 404);
123 if (exists $get{copy}) {
124 $row = {%{$row}{ qw(prio lang cat) }};
126 elsif (defined $post{form}) {{
128 return if not length $_[0];
130 return Encode::decode_utf8($_[0]);
135 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
136 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
137 scalar parseinput($post{$_})
141 if ($row->{ref} ne 'delete') {
143 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
147 $db->delete(word => $find);
148 Alert("Entry removed");
154 my %res = (returning => '*');
155 $row->{creator} = $user->{id} unless $find;
156 $row->{updated} = ['now()'];
157 my $query = $find ? $db->update(word => $row, $find, \%res) :
158 $db->insert(word => $row, \%res);
161 Alert("Entry could not be saved", $@);
166 while (my ($lang, $val) = each %post) {
168 $lang =~ s/^trans-// or next;
169 $val = parseinput($val) or next;
176 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
177 $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
178 $db->insert(word => \%subrow);
179 delete $fields{$field};
182 } or Alert('Error creating translation entries', $@);
184 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
186 ($row->{source} // '') ne ($replace->{source} // '') or return;
187 # copy changed remote url to local file
188 unlink $imgpath if -e $imgpath;
189 my $download = $row->{source} or return 1;
190 require LWP::UserAgent;
191 my $ua = LWP::UserAgent->new;
193 my $status = $ua->mirror($download, $imgpath);
195 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
197 !$@ or Alert(["Source image not found", $@]);
199 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
200 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
201 $reimage++ if $fields{rethumb}; # force refresh
203 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
206 my $xyres = $row->{cover} ? '600x400' : '300x200';
207 my @cmds = @{ $row->{thumb} // [] };
208 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
209 # replace option by permillage crop
210 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
211 splice @cmds, $cmdarg, 2, (
212 -set => 'option:distort:viewport' => sprintf(
213 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
214 ($dim[2] || 1) - $dim[0], # width = x2 - x1
215 ($dim[3] || 1) - $dim[1], # height = y2 - y1
216 @dim[0, 1] # offset = x1,y1
218 -distort => SRT => 0, # noop transform to apply viewport
224 -delete => '1--1', -background => 'white',
225 -gravity => defined $row->{thumb} ? 'northwest' : 'center',
227 -resize => "$xyres^", -extent => $xyres,
228 '-strip', -quality => '60%', -interlace => 'plane',
234 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
236 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
238 "Thumbnail image not generated",
239 "Failed to convert source image.",
248 $row->{lang} //= $user->{editlang}->[0];
249 $row->{$_} = $get{$_} for keys %get;
250 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
253 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
255 package Shiar_Sheet::FormRow {
256 use PLP::Functions 'EscapeHTML';
259 my ($row, $col, $attr) = @_;
260 my $val = $row->{$col} // '';
262 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
264 if (my $options = $attr->{-select}) {
265 $options = $options->(@_) if ref $options eq 'CODE';
266 $options->{$val} //= "unknown ($val)"; # preserve current
268 sprintf('<select id="%s" name="%1$s">', $col),
269 (map { sprintf('<option value="%s"%s>%s</option>',
270 $_, $val eq $_ && ' selected', $options->{$_}
271 ) } sort keys %{$options}),
275 elsif ($attr->{type} eq 'checkbox') {
276 $html .= ' checked' if $val;
280 '<input name="%1$s" value="0" type="hidden" />',
281 '<input id="%s" name="%1$s" value="1"%s>',
283 ), $col, $html, $attr->{-label}
287 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
290 sprintf('<label for="%s">%s</label>', $col, $_)
291 } $attr->{-label} // ()),
292 $multiple ? '<span class="inline multiinput">' : (),
294 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
295 } ref $val eq 'ARRAY' ? @{$val} : ()),
296 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
297 $col, $multiple ? '' : EscapeHTML($val), $html
299 $multiple ? '</span>' : (),
301 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
302 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
303 } grep { -e } $row->imagepath($col)),
309 my ($row, $col) = @_;
310 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
311 return "data/word/en/$row->{id}.jpg" if $col eq 'thumb';
315 bless $row, 'Shiar_Sheet::FormRow';
317 <h1>Words <:= $title :></h1>
321 <form action="?" method="post">
322 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
325 for my $col (@wordcols) {
326 my $info = $wordcol{$col} or next;
327 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
328 my $title = ref $attr ? delete $attr->{-label} : $attr;
329 printf '<li><label for="%s">%s</label><p>', $col, $title;
330 printf '<span class=inline>';
331 print $row->input($col => $attr);
332 print $row->input($_ => delete $wordcol{$_}) for @span;
337 if (not $row->{ref}) {
338 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
339 'trans', 'Translations';
340 my @children = !$row->{id} ? () :
341 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
342 while (my ($lang, $val) = each %fields) {
343 $lang =~ s/^trans-// or next;
344 push @children, { lang => $lang, form => $val };
346 my %existing = map { $_->{lang} => 1 } $row, @children;
347 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
349 for my $ref (@children) {
351 '<li><label for="%s" title="%3$s">%s </label>',
352 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
355 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
356 '<input id="%s" name="%1$s" value="%3$s" />',
357 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
360 say '</ul></div></li>';
365 <input type="submit" value="Save" />
366 <input type="submit" value="New" formaction="/writer?copy=cat" />
378 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
379 while (my $ref = $parents->hash) {
380 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
382 say "<li><strong>$row->{form}</strong></li>";
383 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
384 while (my $ref = $children->hash) {
385 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
388 <li><form action="/writer">
389 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
390 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
391 <input type="submit" value="Add" />