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', -src => sub {
102 return "data/word/org/$_[0]->{id}.jpg";
104 thumb => {-label => 'Convert options', -multiple => 1, -src => sub {
105 return "data/word/en/$_[0]->{id}.jpg";
107 story => {-label => 'Story', type => 'textarea'},
110 if (my $search = $fields{q}) {
111 my %filter = (form => {ilike => '%'.$search.'%'});
112 my $results = $db->select(word => '*', \%filter);
113 say '<h1>Search</h1><ul>';
114 printf("<li><small>%s</small> %s %s</li>\n",
115 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
116 sprintf('<img src="/%s" style="height:3ex; width:auto" />', $wordcol{thumb}->{-src}->($_)) x defined $_->{thumb}
117 ) for $results->hashes;
122 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
125 $row = $db->select(word => '*', $find)->hash
126 or Abort("Word not found", 404);
129 if (exists $get{copy}) {
130 $row = {%{$row}{ qw(prio lang cat) }};
132 elsif (defined $post{form}) {{
134 return if not length $_[0];
136 return Encode::decode_utf8($_[0]);
141 ref $wordcol{$_} eq 'HASH' && $wordcol{$_}->{-multiple} ?
142 [ map { parseinput($_) } $post{'@'.$_}->@* ] :
143 scalar parseinput($post{$_})
147 if ($row->{ref} ne 'delete') {
149 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
153 $db->delete(word => $find);
154 Alert("Entry removed");
160 my %res = (returning => '*');
161 $row->{creator} = $user->{id} unless $find;
162 $row->{updated} = ['now()'];
163 my $query = $find ? $db->update(word => $row, $find, \%res) :
164 $db->insert(word => $row, \%res);
167 Alert("Entry could not be saved", $@);
172 while (my ($lang, $val) = each %post) {
174 $lang =~ s/^trans-// or next;
175 $val = parseinput($val) or next;
182 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
183 $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
184 $db->insert(word => \%subrow);
185 delete $fields{$field};
188 } or Alert('Error creating translation entries', $@);
190 my $imgpath = $wordcol{source}->{-src}->($row);
192 ($row->{source} // '') ne ($replace->{source} // '') or return;
193 # copy changed remote url to local file
194 unlink $imgpath if -e $imgpath;
195 my $download = $row->{source} or return 1;
196 require LWP::UserAgent;
197 my $ua = LWP::UserAgent->new;
199 my $status = $ua->mirror($download, $imgpath);
201 or die "Download from <q>$download</q> failed: ".$status->status_line."\n";
203 !$@ or Alert(["Source image not found", $@]);
205 $reimage ||= $row->{thumb} ~~ $replace->{thumb}; # different convert
206 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
207 $reimage++ if $fields{rethumb}; # force refresh
210 my $thumbpath = $wordcol{thumb}->{-src}->($row);
212 my $xyres = $row->{cover} ? '600x400' : '300x200';
213 my @cmds = @{ $row->{thumb} // [] };
214 if (my ($cmdarg) = grep { $cmds[$_] eq '-area' } 0 .. $#cmds) {
215 # replace option by permillage crop
216 my @dim = map { $_ / 1000 } split /\D/, $cmds[$cmdarg + 1];
217 splice @cmds, $cmdarg, 2, (
218 -set => 'option:distort:viewport' => sprintf(
219 '%%[fx:w*%s]x%%[fx:h*%s]+%%[fx:w*%s]+%%[fx:h*%s]',
220 ($dim[2] || 1) - $dim[0], # width = x2 - x1
221 ($dim[3] || 1) - $dim[1], # height = y2 - y1
222 @dim[0, 1] # offset = x1,y1
224 -distort => SRT => 0, # noop transform to apply viewport
230 -delete => '1--1', -background => 'white',
231 -gravity => defined $row->{thumb} ? 'northwest' : 'center',
233 -resize => "$xyres^", -extent => $xyres,
234 '-strip', -quality => '60%', -interlace => 'plane',
240 IPC::Run::run(\@cmds, '<' => \undef, '>&' => \$output)
242 ($? & 127 ? "signal $?" : "error code ".($? >> 8))."\n";
244 "Thumbnail image not generated",
245 "Failed to convert source image.",
254 $row->{lang} //= $user->{editlang}->[0];
255 $row->{$_} = $get{$_} for keys %get;
256 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
259 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
261 package Shiar_Sheet::FormRow {
262 use PLP::Functions 'EscapeHTML';
265 my ($row, $col, $attr) = @_;
266 my $val = $row->{$col} // '';
268 $html .= qq( $_="$attr->{$_}") for sort grep {!/^-/} keys %{$attr // {}};
270 if (my $options = $attr->{-select}) {
271 $options = $options->(@_) if ref $options eq 'CODE';
272 $options->{$val} //= "unknown ($val)"; # preserve current
274 sprintf('<select id="%s" name="%1$s">', $col),
275 (map { sprintf('<option value="%s"%s>%s</option>',
276 $_, $val eq $_ && ' selected', $options->{$_}
277 ) } sort keys %{$options}),
281 elsif ($attr->{type} eq 'textarea') {
284 sprintf('<label for="%s">%s</label>', $col, $_)
285 } $attr->{-label} // ()),
286 sprintf('<textarea id="%s" name="%1$s"%s>%s</textarea>',
287 $col, $html, EscapeHTML($val)
291 elsif ($attr->{type} eq 'checkbox') {
292 $html .= ' checked' if $val;
296 '<input name="%1$s" value="0" type="hidden" />',
297 '<input id="%s" name="%1$s" value="1"%s>',
299 ), $col, $html, $attr->{-label}
303 my $multiple = ref $val eq 'ARRAY' || $attr->{-multiple};
306 sprintf('<label for="%s">%s</label>', $col, $_)
307 } $attr->{-label} // ()),
308 $multiple ? '<span class="inline multiinput">' : (),
310 sprintf('<input name="%s" value="%s" />', $col, EscapeHTML($_))
311 } ref $val eq 'ARRAY' ? @{$val} : ()),
312 sprintf('<input id="%s" name="%1$s" value="%s"%s />',
313 $col, $multiple ? '' : EscapeHTML($val), $html
315 $multiple ? '</span>' : (),
320 bless $row, 'Shiar_Sheet::FormRow';
322 <h1>Words <:= $title :></h1>
326 <form action="?" method="post">
327 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
330 for my $col (@wordcols) {
331 my $info = $wordcol{$col} or next;
332 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
333 my $title = ref $attr ? delete $attr->{-label} : $attr;
334 printf '<li><label for="%s">%s</label><p>', $col, $title;
335 printf '<span class=inline>';
336 print $row->input($col => $attr);
337 if (my $imgsrc = $attr->{-src}) {
338 printf('<img id="%spreview" src="/%s" alt="%s"%s />',
339 $col, $_, $row->{form}, $col eq 'source' && ' hidden'
340 ) for grep { -e } $imgsrc->($row);
342 print $row->input($_ => delete $wordcol{$_}) for @span;
347 if (not $row->{ref}) {
348 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
349 'trans', 'Translations';
350 my @children = !$row->{id} ? () :
351 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
352 while (my ($lang, $val) = each %fields) {
353 $lang =~ s/^trans-// or next;
354 push @children, { lang => $lang, form => $val };
356 my %existing = map { $_->{lang} => 1 } $row, @children;
357 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
359 for my $ref (@children) {
361 '<li><label for="%s" title="%3$s">%s </label>',
362 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
365 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
366 '<input id="%s" name="%1$s" value="%3$s" />',
367 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
370 say '</ul></div></li>';
375 <input type="submit" value="Save" />
376 <input type="submit" value="New" formaction="/writer?copy=cat" />
388 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
389 while (my $ref = $parents->hash) {
390 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
392 say "<li><strong>$_</strong></li>" for Entity($row->{form});
393 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
394 while (my $ref = $children->hash) {
395 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
398 <li><form action="/writer">
399 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
400 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
401 <input type="submit" value="Add" />