word/edit: remap/rename priority levels
[sheet.git] / word / edit.plp
1 <(../common.inc.plp)><:
2
3 my $editorurl = '/word/edit';
4 s{\Aedit(/|\z)}{} for $Request // ();
5
6 Html({
7         title => 'words cheat sheet admin',
8         version => '1.0',
9         nocache => 1,
10         raw => <<'EOT',
11 <link rel="stylesheet" type="text/css" media="all" href="/word/editor.css" />
12 <script src="/word/editor.js"></script>
13 EOT
14 });
15
16 use List::Util qw( pairs pairkeys );
17 use Shiar_Sheet::FormRow;
18 use JSON;
19
20 my $db = eval {
21         require Shiar_Sheet::DB;
22         Shiar_Sheet::DB->connect;
23 } or Abort('Database error', 501, $@);
24
25 my $user = eval {
26         if (defined $post{username}) {
27                 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
28         }
29         elsif (exists $fields{logout}) {
30                 require CGI::Cookie;
31                 if (AddCookie(CGI::Cookie->new(
32                         -name    => 'login',
33                         -value   => '',
34                         -path    => $editorurl,
35                         -expires => 'now',
36                 )->as_string)) {
37                         delete $cookie{login};
38                         die "Logged out as requested\n";
39                 }
40                 Alert("Failed to log out", "Login cookie could not be removed.");
41         }
42
43         my $cookiedata = $cookie{login} or return;
44         my ($name, $key) = split /[:\v]/, DecodeURI($cookiedata);
45         my %rowmatch = (username => $name, pass => $key);
46         my $found = $db->select(login => '*', \%rowmatch)->hash
47                 or die "Invalid user or password\n";
48
49         eval {
50                 require CGI::Cookie;
51                 my $httpcookie = CGI::Cookie->new(
52                         -name    => 'login',
53                         -value   => join(':', @{$found}{qw( username pass )}),
54                         -path    => $editorurl,
55                 ) or die "prepared object is empty\n";
56                 AddCookie($httpcookie->as_string);
57         } or Abort(["Unable to create login cookie", $@], 403);
58
59         return $found;
60 } or do {
61         say '<h1>Login to edit words</h1>';
62         Alert('Access denied', $@) if $@;
63         say '<form action="?" method="post" class="inline"><ul>';
64         my $loginform = bless {%post}, 'Shiar_Sheet::FormRow';
65         say '<li>', $loginform->input(@{$_}), '</li>' for pairs (
66                 username => {-label => 'User name'},
67                 pass     => {-label => 'Password', type => 'password'},
68         );
69         say '<li><input type="submit" value="Login" /></li>';
70         say '</ul></form>';
71         exit;
72 };
73
74 my %lang = (
75         '' => ['(reference)'],
76         nl => ["\N{REGIONAL INDICATOR SYMBOL LETTER N}\N{REGIONAL INDICATOR SYMBOL LETTER L}", 'nederlands'],
77         en => ["\N{REGIONAL INDICATOR SYMBOL LETTER G}\N{REGIONAL INDICATOR SYMBOL LETTER B}", 'english'],
78         eo => [qq'<span style="color:green">\N{BLACK STAR}</span>', 'esperanto'],
79         ru => ["\N{REGIONAL INDICATOR SYMBOL LETTER R}\N{REGIONAL INDICATOR SYMBOL LETTER U}", 'русский'],
80         zh => ["\N{REGIONAL INDICATOR SYMBOL LETTER C}\N{REGIONAL INDICATOR SYMBOL LETTER N}", '中文'],
81         la => ["\N{PUSHPIN}", 'latin'],
82 );
83 my @wordcols = pairkeys
84 my %wordcol = (
85         lang    => {-label => 'Language', -select => {
86                 map { $_ => "@{$lang{$_}}" } keys %lang
87         }},
88         cat     => [{-label => 'Category'}, 'ref'],
89         ref     => {-label => 'Reference'},
90         prio    => [
91                 {-label => 'Level', -select => sub {
92                         my ($row) = @_;
93                         my @enum = qw[
94                                 essential ubiquitous basic common distinctive specialised rare invisible
95                         ];
96                         return {
97                                 ('' => 'parent') x (defined $row->{ref}),
98                                 map { $_ => $enum[$_] } 0 .. $#enum
99                         };
100                 }},
101                 'cover', 'grade',
102         ],
103         cover   => {-label => 'Highlighted', type => 'checkbox'},
104         grade   => {-label => 'Order', type => 'number'},
105         form    => {-label => 'Title'},
106         alt     => {-label => 'Synonyms', -multiple => 1},
107         wptitle => {-label => 'Wikipedia'},
108         source  => {-label => 'Image', -json => 'image', -src => sub {
109                 return "data/word/org/$_[0]->{id}.jpg";
110         }},
111         convert => {-label => 'Convert options', -json => 'image', -multiple => 1, -src => sub {
112                 return "data/word/en/$_[0]->{id}.jpg";
113         }},
114         story   => {-label => 'Story', type => 'textarea', hidden => 'hidden'},
115 );
116
117 if (my $search = $fields{q}) {
118         my %filter = $search eq '^' ? (cat => undef, ref => undef) :
119                 (form => {ilike => '%'.parseinput($search).'%'});
120         my $results = $db->select(word => '*', \%filter);
121         say '<h1>Search</h1><ul>';
122         printf("<li><small>%s</small> %s %s</li>\n",
123                 $_->{id}, showlink($_->{form}, "$editorurl/$_->{id}"),
124                 sprintf('<img src="/%s" style="height:3ex; width:auto" />', $wordcol{convert}->{-src}->($_)) x defined $_->{image}
125         ) for $results->hashes;
126         say "</ul>\n";
127         exit;
128 }
129
130 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
131 my $row;
132 if ($find) {
133         $row = $db->select(word => '*', $find)->hash
134                 or Abort("Word not found", 404);
135 }
136
137 if (exists $get{copy}) {
138         $row = {%{$row}{ qw(prio lang cat) }};
139 }
140 elsif (defined $post{form}) {{
141         sub parseinput {
142                 return if not length $_[0];
143                 require Encode;
144                 return Encode::decode_utf8($_[0]);
145         }
146
147         my $replace = $row;  # currently stored
148         $row = {};  # proposed update
149         while (my ($col, $colinfo) = each %wordcol) {
150                 ref $colinfo eq 'HASH' or $colinfo = {};
151                 my @val = map { parseinput($_) } $post{'@'.$col}->@*;
152                 my $val = $colinfo->{-multiple} && @val ? \@val : $val[-1];
153                 if (my $jsoncol = $colinfo->{-json}) {
154                         defined $val and
155                         $row->{$jsoncol}->{$col} = $val;  # hash will be encoded
156                 }
157                 else {
158                         $row->{$col} = $val;
159                 }
160         }
161         my $imagecol = $row->{image};  # backup image subcolumns
162         ref $_ eq 'HASH' and $_ = encode_json($_) for values %{$row};
163
164         if (!$row->{form} and $row->{lang}) {
165                 if ($row->{ref} ne 'delete') {
166                         Alert("Empty title",
167                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
168                         );
169                 }
170                 else {
171                         $db->delete(word => $find);
172                         Alert("Entry removed");
173                 }
174                 next;
175         }
176
177         eval {
178                 my %res = (returning => '*');
179                 $row->{creator} = $user->{id} unless $find;
180                 $row->{updated} = ['now()'];
181                 my $query = $find ? $db->update(word => $row, $find, \%res) :
182                         $db->insert(word => $row, \%res);
183                 $row = $query->hash;
184         } or do {
185                 Alert("Entry could not be saved", $@);
186                 next;
187         };
188
189         eval {
190                 while (my ($lang, $val) = each %post) {
191                         my $field = $lang;
192                         $lang =~ s/^trans-// or next;
193                         $val = parseinput($val) or next;
194                         my %subrow = (
195                                 ref   => $row->{id},
196                                 lang  => $lang,
197                                 form  => $val,
198                                 prio  => undef,
199                         );
200                         $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
201                         $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
202                         $db->insert(word => \%subrow);
203                         delete $fields{$field};
204                 }
205                 return 1;
206         } or Alert('Error creating translation entries', $@);
207
208         require Shiar_Sheet::ImagePrep;
209         my $image = Shiar_Sheet::ImagePrep->new($wordcol{source}->{-src}->($row));
210         my $reimage = eval {
211                 ($imagecol->{source} // '') ne ($replace->{source} // '') or return;
212                 $image->download($imagecol->{source});
213         };
214         !$@ or Alert(["Source image not found", $@]);
215
216         $reimage ||= $row->{image} ~~ $replace->{image};  # different source
217         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
218         $reimage++ if $fields{rethumb};  # force refresh
219         if ($reimage) {
220                 eval {
221                         $image->convert($wordcol{convert}->{-src}->($row), $imagecol->{convert});
222                 } or do {
223                         my ($warn, @details) = ref $@ ? @{$@} : $@;
224                         Alert([ "Thumbnail image not generated", $warn ], @details);
225                 };
226         }
227 }}
228 else {
229         $row->{lang} //= $user->{editlang}->[0] unless exists $row->{lang};
230         $row->{$_} = $get{$_} for keys %get;
231         $row->{prio} = defined $row->{ref} ? undef : 4 unless exists $row->{prio};
232 }
233
234 eval {
235         my $imagerow = $row->{image} && JSON->new->decode(delete $row->{image}) || {};
236         while (my ($col, $val) = each %{$imagerow}) {
237                 $row->{$col} = $val;
238         }
239         1;
240 } or Alert("Error decoding image metadata", $@);
241
242 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
243 bless $row, 'Shiar_Sheet::FormRow';
244 :>
245 <h1>Words <:= $title :></h1>
246
247 <div class="inline">
248
249 <form action="?" method="post">
250 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
251 <ul>
252 <:
253 for my $col (@wordcols) {
254         my $info = $wordcol{$col} or next;
255         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
256         next if delete $attr->{hidden} and not $row->{$col};
257         my $title = ref $attr ? delete $attr->{-label} : $attr;
258         printf '<li><label for="%s">%s</label><p>', $col, $title;
259                 printf '<span class=inline>';
260                 print $row->input($col => $attr);
261                 if (my $imgsrc = $attr->{-src}) {
262                         printf('<img id="%spreview" src="/%s" alt="%s"%s />',
263                                 $col, $_, $row->{form}, $col eq 'source' && ' hidden'
264                         ) for grep { -e } $imgsrc->($row);
265                 }
266                 print $row->input($_ => delete $wordcol{$_}) for @span;
267                 print '</span>';
268         say '</p></li>';
269 }
270
271 if (not $row->{ref}) {
272         printf '<li><label for="%s">%s</label><div><ul class="inline multiinput" id="%1$s">',
273                 'trans', 'Translations';
274         my @children = !$row->{id} ? () :
275                 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
276         while (my ($lang, $val) = each %fields) {
277                 $lang =~ s/^trans-// or next;
278                 push @children, { lang => $lang, form => $val };
279         }
280         my %existing = map { $_->{lang} => 1 } $row, @children;
281         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
282
283         for my $ref (@children) {
284                 printf(
285                         '<li><label for="%s" title="%3$s">%s </label>',
286                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
287                 );
288                 printf(
289                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
290                         '<input id="%s" name="%1$s" value="%3$s" />',
291                         "trans-$ref->{lang}", "$editorurl/$ref->{id}", Entity($ref->{form} // ''),
292                 );
293         }
294         say '</ul></div></li>';
295 }
296 :>
297 </ul>
298 <p>
299         <input type="submit" value="Save" />
300         <input type="submit" value="New" formaction="<:= $editorurl :>?copy=cat" />
301 </p>
302 </form>
303
304 <:
305 if ($row->{id}) {
306 :>
307 <section id="nav">
308 <h2>Hierarchy</h2>
309
310 <:
311 say '<ul>';
312 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
313 while (my $ref = $parents->hash) {
314         printf '<li><a href="%s/%d">%s</a></li>', $editorurl, $ref->{id}, Entity($ref->{form});
315 }
316 say "<li><strong>$_</strong></li>" for Entity($row->{form});
317 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
318 while (my $ref = $children->hash) {
319         printf '<li><a href="%s/%d">%s</a></li>', $editorurl, $ref->{id}, Entity($ref->{form});
320 }
321 :>
322 <li><form action="<:= $editorurl :>">
323         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
324         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
325         <input type="submit" value="Add" />
326 </form></li>
327 </ul>
328 </section>
329 <:
330 }
331 :>
332 </div>