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 );
14 use Shiar_Sheet::FormRow;
18 require Shiar_Sheet::DB;
19 Shiar_Sheet::DB->connect;
20 } or Abort('Database error', 501, $@);
23 my $rootpath = ($ENV{REQUEST_URI} // '/writer') =~ s{(?<!^)/.+}{}r;
24 if (defined $post{username}) {
25 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
27 elsif (exists $fields{logout}) {
29 if (AddCookie(CGI::Cookie->new(
35 delete $cookie{login};
36 die "Logged out as requested\n";
38 Alert("Failed to log out", "Login cookie could not be removed.");
41 my $cookiedata = $cookie{login} or return;
42 my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
43 my %rowmatch = (username => $name, pass => $key);
44 my $found = $db->select(login => '*', \%rowmatch)->hash
45 or die "Invalid user or password\n";
49 my $httpcookie = CGI::Cookie->new(
51 -value => join(':', @{$found}{qw( username pass )}),
53 ) or die "prepared object is empty\n";
54 AddCookie($httpcookie->as_string);
55 } or Abort(["Unable to create login cookie", $@], 403);
59 say '<h1>Login to edit words</h1>';
60 Alert('Access denied', $@) if $@;
61 say '<form action="?" method="post" class="inline"><ul>';
62 my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
63 say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
64 username => {-label => 'User name'},
65 pass => {-label => 'Password', type => 'password'},
67 say '<li><input type="submit" value="Login" /></li>';
73 nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
74 en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
75 eo => ['<span style="color:green">★</span>', 'esperanto'],
76 ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
77 zh => ["\N{REGIONAL INDICATOR SYMBOL LETTER C}\N{REGIONAL INDICATOR SYMBOL LETTER N}", '中文'],
78 la => ["\N{PUSHPIN}", 'latin'],
80 my @wordcols = pairkeys
82 lang => {-label => 'Language', -select => {
83 map { $_ => "@{$lang{$_}}" } keys %lang
85 cat => [{-label => 'Category'}, 'ref'],
86 ref => {-label => 'Reference'},
88 {-label => 'Level', -select => sub {
90 my @enum = qw[ essential basic common distinctive optional invisible ];
92 ('' => 'parent') x (defined $row->{ref}),
93 map { $_ => $enum[$_] } 0 .. $#enum
98 cover => {-label => 'Highlighted', type => 'checkbox'},
99 grade => {-label => 'Order', type => 'number'},
100 form => {-label => 'Title'},
101 alt => {-label => 'Synonyms', -multiple => 1},
102 wptitle => {-label => 'Wikipedia'},
103 source => {-label => 'Image', -json => 'image', -src => sub {
104 return "data/word/org/$_[0]->{id}.jpg";
106 convert => {-label => 'Convert options', -json => 'image', -multiple => 1, -src => sub {
107 return "data/word/en/$_[0]->{id}.jpg";
109 story => {-label => 'Story', type => 'textarea', hidden => 'hidden'},
112 if (my $search = $fields{q}) {
113 my %filter = (form => {ilike => '%'.$search.'%'});
114 my $results = $db->select(word => '*', \%filter);
115 say '<h1>Search</h1><ul>';
116 printf("<li><small>%s</small> %s %s</li>\n",
117 $_->{id}, showlink($_->{form}, "/writer/$_->{id}"),
118 sprintf('<img src="/%s" style="height:3ex; width:auto" />', $wordcol{convert}->{-src}->($_)) x defined $_->{image}
119 ) for $results->hashes;
124 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
127 $row = $db->select(word => '*', $find)->hash
128 or Abort("Word not found", 404);
131 if (exists $get{copy}) {
132 $row = {%{$row}{ qw(prio lang cat) }};
134 elsif (defined $post{form}) {{
136 return if not length $_[0];
138 return Encode::decode_utf8($_[0]);
141 my $replace = $row; # currently stored
142 $row = {}; # proposed update
143 while (my ($col, $colinfo) = each %wordcol) {
144 ref $colinfo eq 'HASH' or $colinfo = {};
145 my @val = map { parseinput($_) } $post{'@'.$col}->@*;
146 my $val = $colinfo->{-multiple} && @val ? \@val : $val[-1];
147 if (my $jsoncol = $colinfo->{-json}) {
149 $row->{$jsoncol}->{$col} = $val; # hash will be encoded
155 my $imagecol = $row->{image}; # backup image subcolumns
156 ref $_ eq 'HASH' and $_ = encode_json($_) for values %{$row};
159 if ($row->{ref} ne 'delete') {
161 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
165 $db->delete(word => $find);
166 Alert("Entry removed");
172 my %res = (returning => '*');
173 $row->{creator} = $user->{id} unless $find;
174 $row->{updated} = ['now()'];
175 my $query = $find ? $db->update(word => $row, $find, \%res) :
176 $db->insert(word => $row, \%res);
179 Alert("Entry could not be saved", $@);
184 while (my ($lang, $val) = each %post) {
186 $lang =~ s/^trans-// or next;
187 $val = parseinput($val) or next;
194 $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
195 $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
196 $db->insert(word => \%subrow);
197 delete $fields{$field};
200 } or Alert('Error creating translation entries', $@);
202 require Shiar_Sheet::ImagePrep;
203 my $image = Shiar_Sheet::ImagePrep->new($wordcol{source}->{-src}->($row));
205 ($imagecol->{source} // '') ne ($replace->{source} // '') or return;
206 $image->download($imagecol->{source});
208 !$@ or Alert(["Source image not found", $@]);
210 $reimage ||= $row->{image} ~~ $replace->{image}; # different source
211 $reimage ||= $row->{cover} ~~ $replace->{cover}; # resize
212 $reimage++ if $fields{rethumb}; # force refresh
215 $image->convert($wordcol{convert}->{-src}->($row), $imagecol->{convert});
217 my ($warn, @details) = ref $@ ? @{$@} : $@;
218 Alert([ "Thumbnail image not generated", $warn ], @details);
223 $row->{lang} //= $user->{editlang}->[0];
224 $row->{$_} = $get{$_} for keys %get;
225 $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
229 my $imagerow = $row->{image} && decode_json(delete $row->{image}) || {};
230 while (my ($col, $val) = each %{$imagerow}) {
234 } or Alert("Error decoding image metadata", $@);
236 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
237 bless $row, 'Shiar_Sheet::FormRow';
239 <h1>Words <:= $title :></h1>
243 <form action="?" method="post">
244 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
247 for my $col (@wordcols) {
248 my $info = $wordcol{$col} or next;
249 my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
250 next if delete $attr->{hidden} and not $row->{$col};
251 my $title = ref $attr ? delete $attr->{-label} : $attr;
252 printf '<li><label for="%s">%s</label><p>', $col, $title;
253 printf '<span class=inline>';
254 print $row->input($col => $attr);
255 if (my $imgsrc = $attr->{-src}) {
256 printf('<img id="%spreview" src="/%s" alt="%s"%s />',
257 $col, $_, $row->{form}, $col eq 'source' && ' hidden'
258 ) for grep { -e } $imgsrc->($row);
260 print $row->input($_ => delete $wordcol{$_}) for @span;
265 if (not $row->{ref}) {
266 printf '<li><label for="%s">%s</label><div><ul class="inline" id="%1$s">',
267 'trans', 'Translations';
268 my @children = !$row->{id} ? () :
269 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
270 while (my ($lang, $val) = each %fields) {
271 $lang =~ s/^trans-// or next;
272 push @children, { lang => $lang, form => $val };
274 my %existing = map { $_->{lang} => 1 } $row, @children;
275 $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
277 for my $ref (@children) {
279 '<li><label for="%s" title="%3$s">%s </label>',
280 "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
283 $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
284 '<input id="%s" name="%1$s" value="%3$s" />',
285 "trans-$ref->{lang}", "/writer/$ref->{id}", Entity($ref->{form} // ''),
288 say '</ul></div></li>';
293 <input type="submit" value="Save" />
294 <input type="submit" value="New" formaction="/writer?copy=cat" />
306 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
307 while (my $ref = $parents->hash) {
308 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
310 say "<li><strong>$_</strong></li>" for Entity($row->{form});
311 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
312 while (my $ref = $children->hash) {
313 printf '<li><a href="/writer/%d">%s</a></li>', $ref->{id}, Entity($ref->{form});
316 <li><form action="/writer">
317 <input type="hidden" name="cat" value="<:= $row->{id} :>" />
318 <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
319 <input type="submit" value="Add" />