5957b1a9b6a9541bb75b4a162d9190d3a5bf0c60
[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[ essential basic common distinctive optional invisible ];
94                         return {
95                                 ('' => 'parent') x (defined $row->{ref}),
96                                 map { $_ => $enum[$_] } 0 .. $#enum
97                         };
98                 }},
99                 'cover', 'grade',
100         ],
101         cover   => {-label => 'Highlighted', type => 'checkbox'},
102         grade   => {-label => 'Order', type => 'number'},
103         form    => {-label => 'Title'},
104         alt     => {-label => 'Synonyms', -multiple => 1},
105         wptitle => {-label => 'Wikipedia'},
106         source  => {-label => 'Image', -json => 'image', -src => sub {
107                 return "data/word/org/$_[0]->{id}.jpg";
108         }},
109         convert => {-label => 'Convert options', -json => 'image', -multiple => 1, -src => sub {
110                 return "data/word/en/$_[0]->{id}.jpg";
111         }},
112         story   => {-label => 'Story', type => 'textarea', hidden => 'hidden'},
113 );
114
115 if (my $search = $fields{q}) {
116         my %filter = $search eq '^' ? (cat => undef, ref => undef) :
117                 (form => {ilike => '%'.parseinput($search).'%'});
118         my $results = $db->select(word => '*', \%filter);
119         say '<h1>Search</h1><ul>';
120         printf("<li><small>%s</small> %s %s</li>\n",
121                 $_->{id}, showlink($_->{form}, "$editorurl/$_->{id}"),
122                 sprintf('<img src="/%s" style="height:3ex; width:auto" />', $wordcol{convert}->{-src}->($_)) x defined $_->{image}
123         ) for $results->hashes;
124         say "</ul>\n";
125         exit;
126 }
127
128 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
129 my $row;
130 if ($find) {
131         $row = $db->select(word => '*', $find)->hash
132                 or Abort("Word not found", 404);
133 }
134
135 if (exists $get{copy}) {
136         $row = {%{$row}{ qw(prio lang cat) }};
137 }
138 elsif (defined $post{form}) {{
139         sub parseinput {
140                 return if not length $_[0];
141                 require Encode;
142                 return Encode::decode_utf8($_[0]);
143         }
144
145         my $replace = $row;  # currently stored
146         $row = {};  # proposed update
147         while (my ($col, $colinfo) = each %wordcol) {
148                 ref $colinfo eq 'HASH' or $colinfo = {};
149                 my @val = map { parseinput($_) } $post{'@'.$col}->@*;
150                 my $val = $colinfo->{-multiple} && @val ? \@val : $val[-1];
151                 if (my $jsoncol = $colinfo->{-json}) {
152                         defined $val and
153                         $row->{$jsoncol}->{$col} = $val;  # hash will be encoded
154                 }
155                 else {
156                         $row->{$col} = $val;
157                 }
158         }
159         my $imagecol = $row->{image};  # backup image subcolumns
160         ref $_ eq 'HASH' and $_ = encode_json($_) for values %{$row};
161
162         if (!$row->{form} and $row->{lang}) {
163                 if ($row->{ref} ne 'delete') {
164                         Alert("Empty title",
165                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
166                         );
167                 }
168                 else {
169                         $db->delete(word => $find);
170                         Alert("Entry removed");
171                 }
172                 next;
173         }
174
175         eval {
176                 my %res = (returning => '*');
177                 $row->{creator} = $user->{id} unless $find;
178                 $row->{updated} = ['now()'];
179                 my $query = $find ? $db->update(word => $row, $find, \%res) :
180                         $db->insert(word => $row, \%res);
181                 $row = $query->hash;
182         } or do {
183                 Alert("Entry could not be saved", $@);
184                 next;
185         };
186
187         eval {
188                 while (my ($lang, $val) = each %post) {
189                         my $field = $lang;
190                         $lang =~ s/^trans-// or next;
191                         $val = parseinput($val) or next;
192                         my %subrow = (
193                                 ref   => $row->{id},
194                                 lang  => $lang,
195                                 form  => $val,
196                                 prio  => undef,
197                         );
198                         $subrow{wptitle} = $1 if $subrow{form} =~ s/\h*\[(.*)\]$//; # [Link] shorthand
199                         $subrow{alt} = [split m{/}, $1] if $subrow{form} =~ s{/(\S.*)}{}; # /alternates shorthand
200                         $db->insert(word => \%subrow);
201                         delete $fields{$field};
202                 }
203                 return 1;
204         } or Alert('Error creating translation entries', $@);
205
206         require Shiar_Sheet::ImagePrep;
207         my $image = Shiar_Sheet::ImagePrep->new($wordcol{source}->{-src}->($row));
208         my $reimage = eval {
209                 ($imagecol->{source} // '') ne ($replace->{source} // '') or return;
210                 $image->download($imagecol->{source});
211         };
212         !$@ or Alert(["Source image not found", $@]);
213
214         $reimage ||= $row->{image} ~~ $replace->{image};  # different source
215         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
216         $reimage++ if $fields{rethumb};  # force refresh
217         if ($reimage) {
218                 eval {
219                         $image->convert($wordcol{convert}->{-src}->($row), $imagecol->{convert});
220                 } or do {
221                         my ($warn, @details) = ref $@ ? @{$@} : $@;
222                         Alert([ "Thumbnail image not generated", $warn ], @details);
223                 };
224         }
225 }}
226 else {
227         $row->{lang} //= $user->{editlang}->[0] unless exists $row->{lang};
228         $row->{$_} = $get{$_} for keys %get;
229         $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
230 }
231
232 eval {
233         my $imagerow = $row->{image} && JSON->new->decode(delete $row->{image}) || {};
234         while (my ($col, $val) = each %{$imagerow}) {
235                 $row->{$col} = $val;
236         }
237         1;
238 } or Alert("Error decoding image metadata", $@);
239
240 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
241 bless $row, 'Shiar_Sheet::FormRow';
242 :>
243 <h1>Words <:= $title :></h1>
244
245 <div class="inline">
246
247 <form action="?" method="post">
248 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
249 <ul>
250 <:
251 for my $col (@wordcols) {
252         my $info = $wordcol{$col} or next;
253         my ($attr, @span) = ref $info eq 'ARRAY' ? @{$info} : $info;
254         next if delete $attr->{hidden} and not $row->{$col};
255         my $title = ref $attr ? delete $attr->{-label} : $attr;
256         printf '<li><label for="%s">%s</label><p>', $col, $title;
257                 printf '<span class=inline>';
258                 print $row->input($col => $attr);
259                 if (my $imgsrc = $attr->{-src}) {
260                         printf('<img id="%spreview" src="/%s" alt="%s"%s />',
261                                 $col, $_, $row->{form}, $col eq 'source' && ' hidden'
262                         ) for grep { -e } $imgsrc->($row);
263                 }
264                 print $row->input($_ => delete $wordcol{$_}) for @span;
265                 print '</span>';
266         say '</p></li>';
267 }
268
269 if (not $row->{ref}) {
270         printf '<li><label for="%s">%s</label><div><ul class="inline multiinput" id="%1$s">',
271                 'trans', 'Translations';
272         my @children = !$row->{id} ? () :
273                 $db->select(word => '*', {ref => $row->{id}}, 'lang, id')->hashes;
274         while (my ($lang, $val) = each %fields) {
275                 $lang =~ s/^trans-// or next;
276                 push @children, { lang => $lang, form => $val };
277         }
278         my %existing = map { $_->{lang} => 1 } $row, @children;
279         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
280
281         for my $ref (@children) {
282                 printf(
283                         '<li><label for="%s" title="%3$s">%s </label>',
284                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
285                 );
286                 printf(
287                         $ref->{id} ? '<a id="%s" href="%s">%s</a></li>' :
288                         '<input id="%s" name="%1$s" value="%3$s" />',
289                         "trans-$ref->{lang}", "$editorurl/$ref->{id}", Entity($ref->{form} // ''),
290                 );
291         }
292         say '</ul></div></li>';
293 }
294 :>
295 </ul>
296 <p>
297         <input type="submit" value="Save" />
298         <input type="submit" value="New" formaction="<:= $editorurl :>?copy=cat" />
299 </p>
300 </form>
301
302 <:
303 if ($row->{id}) {
304 :>
305 <section id="nav">
306 <h2>Hierarchy</h2>
307
308 <:
309 say '<ul>';
310 my $parents = $db->select(word => '*', [{id => $row->{cat}}, {id => $row->{ref}}]);
311 while (my $ref = $parents->hash) {
312         printf '<li><a href="%s/%d">%s</a></li>', $editorurl, $ref->{id}, Entity($ref->{form});
313 }
314 say "<li><strong>$_</strong></li>" for Entity($row->{form});
315 my $children = $db->select(word => '*', {cat => $row->{id}, ref => undef}, 'grade, id');
316 while (my $ref = $children->hash) {
317         printf '<li><a href="%s/%d">%s</a></li>', $editorurl, $ref->{id}, Entity($ref->{form});
318 }
319 :>
320 <li><form action="<:= $editorurl :>">
321         <input type="hidden" name="cat" value="<:= $row->{id} :>" />
322         <input type="hidden" name="lang" value="<:= $row->{lang} :>" />
323         <input type="submit" value="Add" />
324 </form></li>
325 </ul>
326 </section>
327 <:
328 }
329 :>
330 </div>