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 );
17 'DBI:Pg:dbname=sheet;host=localhost', 'sheetadmin', 'fairuse',
18 ) or die "database not configured\n";
20 DBIx::Simple->new(@dbinfo[0..2], {
24 } or Abort('Database error', 501, $@);
25 $db->abstract->{array_datatypes}++;
28 if (defined $post{username}) {
29 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
31 elsif (exists $fields{logout}) {
33 if (AddCookie(CGI::Cookie->new(
39 delete $cookie{login};
40 die "Logged out as requested\n";
42 Alert("Failed to log out", "Login cookie could not be removed.");
45 my $cookiedata = $cookie{login} or return;
46 my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
47 my %rowmatch = (username => $name, pass => $key);
48 my $found = $db->select(login => '*', \%rowmatch)->hash
49 or die "Invalid user or password\n";
53 my $httpcookie = CGI::Cookie->new(
55 -value => join(':', @{$found}{qw( username pass )}),
57 ) or die "prepared object is empty\n";
58 AddCookie($httpcookie->as_string);
59 } or Abort(["Unable to create login cookie", $@], 403);
63 say '<h1>Login to edit words</h1>';
64 Alert('Access denied', $@) if $@;
65 say '<form action="?" method="post" class="inline"><ul>';
66 my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
67 say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
68 username => {-label => 'User name'},
69 pass => {-label => 'Password', type => 'password'},
71 say '<li><input type="submit" value="Login" /></li>';
77 nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
78 en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
79 eo => ['<span style="color:green">★</span>', 'esperanto'],
80 ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
82 my @wordcols = pairkeys
84 lang => {-label => 'Language', -select => {
85 map { $_ => "@{$lang{$_}}" } keys %lang
87 cat => [{-label => 'Category'}, 'ref'],
88 ref => {-label => 'Reference'},
90 {-label => 'Level', -select => sub {
92 my @enum = qw[ essential basic common distinctive optional invisible ];
94 ('' => 'parent') x (defined $row->{ref}),
95 map { $_ => $enum[$_] } 0 .. $#enum
100 cover => {-label => 'Highlighted', type => 'checkbox'},
101 grade => {-label => 'Order', type => 'number'},
102 form => {-label => 'Title'},
103 alt => {-label => 'Synonyms', -multiple => 1},
104 wptitle => {-label => 'Wikipedia'},
105 source => {-label => 'Image'},
106 thumb => {-label => 'Convert options', -multiple => 1},
108 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
112 $row = $db->select(word => '*', $find)->hash
113 or Abort("Word not found", 404);
116 if (exists $get{copy}) {
117 $row = {%{$row}{ qw(prio lang cat) }};
119 elsif (defined $post{form}) {{
121 return if not length $_[0];
123 return Encode::decode_utf8($_[0]);
128 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
129 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
130 scalar parseinput($post{$_})
134 if ($row->{ref} ne 'delete') {
136 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
140 $db->delete(word => $find);
141 Alert("Entry removed");
147 my %res = (returning => '*');
148 $row->{creator} = $user->{id} unless $find;
149 $row->{updated} = ['now()'];
150 my $query = $find ? $db->update(word => $row, $find, \%res) :
151 $db->insert(word => $row, \%res);
154 Alert("Entry could not be saved", $@);
159 while (my ($lang, $val) = each %post) {
161 $lang =~ s/^trans-// or next;
162 $val = parseinput($val) or next;
169 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
170 $db->insert(word => \%subrow);
171 delete $fields{$field};
174 } or Alert('Error creating translation entries', $@);
176 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
178 ($row->{source} // '') ne ($replace->{source} // '') or return;
179 # copy changed remote url to local file
180 unlink $imgpath if -e $imgpath;
181 my $download = $row->{source} or return 1;
182 require LWP::UserAgent;
183 my $ua = LWP::UserAgent->new;
185 my $status = $ua->mirror($download, $imgpath);
187 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
189 !$@ or Alert(["Source image not found", $@]);
191 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
192 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
193 $reimage++ if $fields{rethumb}; # force refresh
195 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
198 my $xyres = $row->{cover} ? '600x400' : '300x200';
199 my @cmds = @{ $row->{thumb} // [] };
200 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
201 # replace option by permillage crop
202 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
203 splice @cmds, $cmdarg, 2, (
204 -set => 'option:distort:viewport' => sprintf(
205 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
206 ($dim[2] || 1) - $dim[0], # width = x2 - x1
207 ($dim[3] || 1) - $dim[1], # height = y2 - y1
208 @dim[0, 1] # offset = x1,y1
210 -distort => SRT => 0, # noop transform to apply viewport
216 -delete => '1--1', -background => 'white',
217 -gravity => @cmds ? 'northwest' : 'center',
219 -resize => "$xyres^", -extent => $xyres,
220 '-strip', -quality => '60%', -interlace => 'plane',
226 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
228 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
230 "Thumbnail image not generated",
231 "Failed to convert source image.",
240 $row->{lang} //= $user->{editlang}->[0];
241 $row->{$_} = $get{$_} for keys %get;
242 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
245 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
247 package Shiar_Sheet::FormRow {
248 use PLP::Functions 'EscapeHTML';
251 my ($row, $col, $attr) = @_;
252 my $val = $row->{$col} // '';
254 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
256 if (my $options = $attr->{-select}) {
257 $options = $options->(@_) if ref $options eq 'CODE';
258 $options->{$val} //= "unknown ($val)"; # preserve current
260 sprintf('<select id="%s" name="%1$s">', $col),
261 (map { sprintf('<option value="%s"%s>%s</option>',
262 $_, $val eq $_ && ' selected', $options->{$_}
263 ) } sort keys %{$options}),
267 elsif ($attr->{type} eq 'checkbox') {
268 $html .= ' checked' if $val;
272 '<input name="%1$s" value="0" type="hidden" />',
273 '<input id="%s" name="%1$s" value="1"%s>',
275 ), $col, $html, $attr->{-label}
279 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
282 sprintf('<label for="%s">%s</label>', $col, $_)
283 } $attr->{-label} // ()),
284 $multiple ? '<span class="inline multiinput">' : (),
286 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
287 } ref $val eq 'ARRAY' ? @{$val} : ()),
288 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
289 $col, $multiple ? '' : EscapeHTML($val), $html
291 $multiple ? '</span>' : (),
293 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
294 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
295 } grep { -e } $row->imagepath($col)),
301 my ($row, $col) = @_;
302 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
303 return "data/word/en/$row->{id}.jpg" if $col eq 'thumb';
307 bless $row, 'Shiar_Sheet::FormRow';
309 <h1>Words <:= $title :></h1>
313 <form action="?" method="post">
314 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
317 for my $col (@wordcols) {
318 my $info = $wordcol{$col} or next;
319 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
320 my $title = ref $attr ? delete $attr->{-label} : $attr;
321 printf '<li><label for="%s">%s</label><p>', $col, $title;
322 printf '<span class=inline>';
323 print $row->input($col => $attr);
324 print $row->input($_ => delete $wordcol{$_}) for @span;
329 if (not $row->{ref}) {
330 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
331 'trans', 'Translations';
332 my @children = !$row->{id} ? () :
333 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
334 while (my ($lang, $val) = each %fields) {
335 $lang =~ s/^trans-// or next;
336 push @children, { lang => $lang, form => $val };
338 my %existing = map { $_->{lang} => 1 } $row, @children;
339 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
341 for my $ref (@children) {
343 '<li><label for="%s" title="%3$s">%s </label>',
344 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
347 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
348 '<input id="%s" name="%1$s" value="%3$s" />',
349 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
352 say '</ul></div></li>';
357 <input type="submit" value="Save" />
358 <input type="submit" value="New" formaction="/writer?copy=cat" />
370 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
371 while (my $ref = $parents->hash) {
372 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
374 say "<li><strong>$row->{form}</strong></li>";
375 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
376 while (my $ref = $children->hash) {
377 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
380 <li><form action="/writer">
381 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
382 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
383 <input type="submit" value="Add" />