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