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 zh => ["\N{REGIONAL INDICATOR SYMBOL LETTER C}\N{REGIONAL INDICATOR SYMBOL LETTER N}", '中文'],
76 la => ["\N{PUSHPIN}", 'latin'],
78 my @wordcols = pairkeys
80 lang => {-label => 'Language', -select => {
81 map { $_ => "@{$lang{$_}}" } keys %lang
83 cat => [{-label => 'Category'}, 'ref'],
84 ref => {-label => 'Reference'},
86 {-label => 'Level', -select => sub {
88 my @enum = qw[ essential basic common distinctive optional invisible ];
90 ('' => 'parent') x (defined $row->{ref}),
91 map { $_ => $enum[$_] } 0 .. $#enum
96 cover => {-label => 'Highlighted', type => 'checkbox'},
97 grade => {-label => 'Order', type => 'number'},
98 form => {-label => 'Title'},
99 alt => {-label => 'Synonyms', -multiple => 1},
100 wptitle => {-label => 'Wikipedia'},
101 source => {-label => 'Image'},
102 thumb => {-label => 'Convert options', -multiple => 1},
103 story => {-label => 'Story', type => 'textarea'},
106 if (my $search = $fields{q}) {
107 my %filter = (form => {ilike => '%'.$search.'%'});
108 my $results = $db->select(word => '*', \%filter);
109 say '<h1>Search</h1><ul>';
110 printf("<li><small>%s</small> %s %s</li>\n",
111 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
112 sprintf('<img src="/%s" style="height:3ex; width:auto" />', Shiar_Sheet::FormRow::imagepath($_ => 'thumb')) x defined $_->{thumb}
113 ) for $results->hashes;
118 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
121 $row = $db->select(word => '*', $find)->hash
122 or Abort("Word not found", 404);
125 if (exists $get{copy}) {
126 $row = {%{$row}{ qw(prio lang cat) }};
128 elsif (defined $post{form}) {{
130 return if not length $_[0];
132 return Encode::decode_utf8($_[0]);
137 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
138 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
139 scalar parseinput($post{$_})
143 if ($row->{ref} ne 'delete') {
145 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
149 $db->delete(word => $find);
150 Alert("Entry removed");
156 my %res = (returning => '*');
157 $row->{creator} = $user->{id} unless $find;
158 $row->{updated} = ['now()'];
159 my $query = $find ? $db->update(word => $row, $find, \%res) :
160 $db->insert(word => $row, \%res);
163 Alert("Entry could not be saved", $@);
168 while (my ($lang, $val) = each %post) {
170 $lang =~ s/^trans-// or next;
171 $val = parseinput($val) or next;
178 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
179 $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
180 $db->insert(word => \%subrow);
181 delete $fields{$field};
184 } or Alert('Error creating translation entries', $@);
186 my $imgpath = Shiar_Sheet::FormRow::imagepath($row, 'source');
188 ($row->{source} // '') ne ($replace->{source} // '') or return;
189 # copy changed remote url to local file
190 unlink $imgpath if -e $imgpath;
191 my $download = $row->{source} or return 1;
192 require LWP::UserAgent;
193 my $ua = LWP::UserAgent->new;
195 my $status = $ua->mirror($download, $imgpath);
197 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
199 !$@ or Alert(["Source image not found", $@]);
201 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
202 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
203 $reimage++ if $fields{rethumb}; # force refresh
205 my $thumbpath = Shiar_Sheet::FormRow::imagepath($row => 'thumb');
208 my $xyres = $row->{cover} ? '600x400' : '300x200';
209 my @cmds = @{ $row->{thumb} // [] };
210 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
211 # replace option by permillage crop
212 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
213 splice @cmds, $cmdarg, 2, (
214 -set => 'option:distort:viewport' => sprintf(
215 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
216 ($dim[2] || 1) - $dim[0], # width = x2 - x1
217 ($dim[3] || 1) - $dim[1], # height = y2 - y1
218 @dim[0, 1] # offset = x1,y1
220 -distort => SRT => 0, # noop transform to apply viewport
226 -delete => '1--1', -background => 'white',
227 -gravity => defined $row->{thumb} ? 'northwest' : 'center',
229 -resize => "$xyres^", -extent => $xyres,
230 '-strip', -quality => '60%', -interlace => 'plane',
236 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
238 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
240 "Thumbnail image not generated",
241 "Failed to convert source image.",
250 $row->{lang} //= $user->{editlang}->[0];
251 $row->{$_} = $get{$_} for keys %get;
252 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
255 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
257 package Shiar_Sheet::FormRow {
258 use PLP::Functions 'EscapeHTML';
261 my ($row, $col, $attr) = @_;
262 my $val = $row->{$col} // '';
264 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
266 if (my $options = $attr->{-select}) {
267 $options = $options->(@_) if ref $options eq 'CODE';
268 $options->{$val} //= "unknown ($val)"; # preserve current
270 sprintf('<select id="%s" name="%1$s">', $col),
271 (map { sprintf('<option value="%s"%s>%s</option>',
272 $_, $val eq $_ && ' selected', $options->{$_}
273 ) } sort keys %{$options}),
277 elsif ($attr->{type} eq 'textarea') {
280 sprintf('<label for="%s">%s</label>', $col, $_)
281 } $attr->{-label} // ()),
282 sprintf('<textarea id="%s" name="%1$s"%s>%s</textarea>',
283 $col, $html, EscapeHTML($val)
287 elsif ($attr->{type} eq 'checkbox') {
288 $html .= ' checked' if $val;
292 '<input name="%1$s" value="0" type="hidden" />',
293 '<input id="%s" name="%1$s" value="1"%s>',
295 ), $col, $html, $attr->{-label}
299 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
302 sprintf('<label for="%s">%s</label>', $col, $_)
303 } $attr->{-label} // ()),
304 $multiple ? '<span class="inline multiinput">' : (),
306 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
307 } ref $val eq 'ARRAY' ? @{$val} : ()),
308 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
309 $col, $multiple ? '' : EscapeHTML($val), $html
311 $multiple ? '</span>' : (),
313 sprintf '<img id="%spreview" src="/%s" alt="%s"%s />',
314 $col, $_, $row->{form}, $col eq 'source' ? ' hidden' : '';
315 } grep { -e } $row->imagepath($col)),
321 my ($row, $col) = @_;
322 return "data/word/org/$row->{id}.jpg" if $col eq 'source';
323 return "data/word/en/$row->{id}.jpg" if $col eq 'thumb';
327 bless $row, 'Shiar_Sheet::FormRow';
329 <h1>Words <:= $title :></h1>
333 <form action="?" method="post">
334 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
337 for my $col (@wordcols) {
338 my $info = $wordcol{$col} or next;
339 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
340 my $title = ref $attr ? delete $attr->{-label} : $attr;
341 printf '<li><label for="%s">%s</label><p>', $col, $title;
342 printf '<span class=inline>';
343 print $row->input($col => $attr);
344 print $row->input($_ => delete $wordcol{$_}) for @span;
349 if (not $row->{ref}) {
350 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
351 'trans', 'Translations';
352 my @children = !$row->{id} ? () :
353 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
354 while (my ($lang, $val) = each %fields) {
355 $lang =~ s/^trans-// or next;
356 push @children, { lang => $lang, form => $val };
358 my %existing = map { $_->{lang} => 1 } $row, @children;
359 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
361 for my $ref (@children) {
363 '<li><label for="%s" title="%3$s">%s </label>',
364 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
367 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
368 '<input id="%s" name="%1$s" value="%3$s" />',
369 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
372 say '</ul></div></li>';
377 <input type="submit" value="Save" />
378 <input type="submit" value="New" formaction="/writer?copy=cat" />
390 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
391 while (my $ref = $parents->hash) {
392 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
394 say "<li><strong>$_</strong></li>" for Entity($row->{form});
395 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
396 while (my $ref = $children->hash) {
397 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
400 <li><form action="/writer">
401 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
402 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
403 <input type="submit" value="Add" />