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