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},
102 if (my $search = $fields{q}) {
103 my %filter = (form => {ilike => '%'.$search.'%'});
104 my $results = $db->select(word => '*', \%filter);
105 say '<h1>Search</h1><ul>';
106 printf("<li><small>%s</small> %s %s</li>\n",
107 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
108 sprintf('<img src="/%s" style="height:3ex; width:auto" />', Shiar_Sheet::FormRow::imagepath($_ => 'thumb')) x defined $_->{thumb}
109 ) for $results->hashes;
114 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
117 $row = $db->select(word => '*', $find)->hash
118 or Abort("Word not found", 404);
121 if (exists $get{copy}) {
122 $row = {%{$row}{ qw(prio lang cat) }};
124 elsif (defined $post{form}) {{
126 return if not length $_[0];
128 return Encode::decode_utf8($_[0]);
133 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
134 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
135 scalar parseinput($post{$_})
139 if ($row->{ref} ne 'delete') {
141 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
145 $db->delete(word => $find);
146 Alert("Entry removed");
152 my %res = (returning => '*');
153 $row->{creator} = $user->{id} unless $find;
154 $row->{updated} = ['now()'];
155 my $query = $find ? $db->update(word => $row, $find, \%res) :
156 $db->insert(word => $row, \%res);
159 Alert("Entry could not be saved", $@);
164 while (my ($lang, $val) = each %post) {
166 $lang =~ s/^trans-// or next;
167 $val = parseinput($val) or next;
174 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
175 $db->insert(word => \%subrow);
176 delete $fields{$field};
179 } or Alert('Error creating translation entries', $@);
181 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
183 ($row->{source} // '') ne ($replace->{source} // '') or return;
184 # copy changed remote url to local file
185 unlink $imgpath if -e $imgpath;
186 my $download = $row->{source} or return 1;
187 require LWP::UserAgent;
188 my $ua = LWP::UserAgent->new;
190 my $status = $ua->mirror($download, $imgpath);
192 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
194 !$@ or Alert(["Source image not found", $@]);
196 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
197 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
198 $reimage++ if $fields{rethumb}; # force refresh
200 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
203 my $xyres = $row->{cover} ? '600x400' : '300x200';
204 my @cmds = @{ $row->{thumb} // [] };
205 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
206 # replace option by permillage crop
207 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
208 splice @cmds, $cmdarg, 2, (
209 -set => 'option:distort:viewport' => sprintf(
210 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
211 ($dim[2] || 1) - $dim[0], # width = x2 - x1
212 ($dim[3] || 1) - $dim[1], # height = y2 - y1
213 @dim[0, 1] # offset = x1,y1
215 -distort => SRT => 0, # noop transform to apply viewport
221 -delete => '1--1', -background => 'white',
222 -gravity => @cmds ? 'northwest' : 'center',
224 -resize => "$xyres^", -extent => $xyres,
225 '-strip', -quality => '60%', -interlace => 'plane',
231 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
233 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
235 "Thumbnail image not generated",
236 "Failed to convert source image.",
245 $row->{lang} //= $user->{editlang}->[0];
246 $row->{$_} = $get{$_} for keys %get;
247 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
250 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
252 package Shiar_Sheet::FormRow {
253 use PLP::Functions 'EscapeHTML';
256 my ($row, $col, $attr) = @_;
257 my $val = $row->{$col} // '';
259 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
261 if (my $options = $attr->{-select}) {
262 $options = $options->(@_) if ref $options eq 'CODE';
263 $options->{$val} //= "unknown ($val)"; # preserve current
265 sprintf('<select id="%s" name="%1$s">', $col),
266 (map { sprintf('<option value="%s"%s>%s</option>',
267 $_, $val eq $_ && ' selected', $options->{$_}
268 ) } sort keys %{$options}),
272 elsif ($attr->{type} eq 'checkbox') {
273 $html .= ' checked' if $val;
277 '<input name="%1$s" value="0" type="hidden" />',
278 '<input id="%s" name="%1$s" value="1"%s>',
280 ), $col, $html, $attr->{-label}
284 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
287 sprintf('<label for="%s">%s</label>', $col, $_)
288 } $attr->{-label} // ()),
289 $multiple ? '<span class="inline multiinput">' : (),
291 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
292 } ref $val eq 'ARRAY' ? @{$val} : ()),
293 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
294 $col, $multiple ? '' : EscapeHTML($val), $html
296 $multiple ? '</span>' : (),
298 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
299 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
300 } grep { -e } $row->imagepath($col)),
306 my ($row, $col) = @_;
307 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
308 return "data/word/en/$row->{id}.jpg" if $col eq 'thumb';
312 bless $row, 'Shiar_Sheet::FormRow';
314 <h1>Words <:= $title :></h1>
318 <form action="?" method="post">
319 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
322 for my $col (@wordcols) {
323 my $info = $wordcol{$col} or next;
324 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
325 my $title = ref $attr ? delete $attr->{-label} : $attr;
326 printf '<li><label for="%s">%s</label><p>', $col, $title;
327 printf '<span class=inline>';
328 print $row->input($col => $attr);
329 print $row->input($_ => delete $wordcol{$_}) for @span;
334 if (not $row->{ref}) {
335 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
336 'trans', 'Translations';
337 my @children = !$row->{id} ? () :
338 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
339 while (my ($lang, $val) = each %fields) {
340 $lang =~ s/^trans-// or next;
341 push @children, { lang => $lang, form => $val };
343 my %existing = map { $_->{lang} => 1 } $row, @children;
344 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
346 for my $ref (@children) {
348 '<li><label for="%s" title="%3$s">%s </label>',
349 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
352 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
353 '<input id="%s" name="%1$s" value="%3$s" />',
354 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
357 say '</ul></div></li>';
362 <input type="submit" value="Save" />
363 <input type="submit" value="New" formaction="/writer?copy=cat" />
375 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
376 while (my $ref = $parents->hash) {
377 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
379 say "<li><strong>$row->{form}</strong></li>";
380 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
381 while (my $ref = $children->hash) {
382 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
385 <li><form action="/writer">
386 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
387 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
388 <input type="submit" value="Add" />