cd2e2bf1d6369529ad52a1186dcb14792ea82f2f
[sheet.git] / writer.plp
1 <(common.inc.plp)><:
2
3 Html({
4         title => 'words cheat sheet admin',
5         version => '1.0',
6         nocache => 1,
7         raw => <<'EOT',
8 <link rel="stylesheet" type="text/css" media="all" href="/editor.css" />
9 <script src="/writer.js"></script>
10 EOT
11 });
12
13 use List::Util qw( pairs pairkeys );
14 use Shiar_Sheet::FormRow;
15 use JSON;
16
17 my $db = eval {
18         require Shiar_Sheet::DB;
19         Shiar_Sheet::DB->connect;
20 } or Abort('Database error', 501, $@);
21
22 my $user = eval {
23         my $rootpath = ($ENV{REQUEST_URI} // '/writer') =~ s{(?<!^)/.+}{}r;
24         if (defined $post{username}) {
25                 $cookie{login} = EncodeURI(join ':', @post{qw( username pass )});
26         }
27         elsif (exists $fields{logout}) {
28                 require CGI::Cookie;
29                 if (AddCookie(CGI::Cookie->new(
30                         -name    => 'login',
31                         -value   => '',
32                         -path    => $rootpath,
33                         -expires => 'now',
34                 )->as_string)) {
35                         delete $cookie{login};
36                         die "Logged out as requested\n";
37                 }
38                 Alert("Failed to log out", "Login cookie could not be removed.");
39         }
40
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";
46
47         eval {
48                 require CGI::Cookie;
49                 my $httpcookie = CGI::Cookie->new(
50                         -name    => 'login',
51                         -value   => join(':', @{$found}{qw( username pass )}),
52                         -path    => $rootpath,
53                 ) or die "prepared object is empty\n";
54                 AddCookie($httpcookie->as_string);
55         } or Abort(["Unable to create login cookie", $@], 403);
56
57         return $found;
58 } or do {
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'},
66         );
67         say '<li><input type="submit" value="Login" /></li>';
68         say '</ul></form>';
69         exit;
70 };
71
72 my %lang = (
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'],
79 );
80 my @wordcols = pairkeys
81 my %wordcol = (
82         lang    => {-label => 'Language', -select => {
83                 map { $_ => "@{$lang{$_}}" } keys %lang
84         }},
85         cat     => [{-label => 'Category'}, 'ref'],
86         ref     => {-label => 'Reference'},
87         prio    => [
88                 {-label => 'Level', -select => sub {
89                         my ($row) = @_;
90                         my @enum = qw[ essential basic common distinctive optional invisible ];
91                         return {
92                                 ('' => 'parent') x (defined $row->{ref}),
93                                 map { $_ => $enum[$_] } 0 .. $#enum
94                         };
95                 }},
96                 'cover', 'grade',
97         ],
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";
105         }},
106         convert => {-label => 'Convert options', -json => 'image', -multiple => 1, -src => sub {
107                 return "data/word/en/$_[0]->{id}.jpg";
108         }},
109         story   => {-label => 'Story', type => 'textarea', hidden => 'hidden'},
110 );
111
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;
120         say "</ul>\n";
121         exit;
122 }
123
124 my ($find) = map {{id => $_}} $fields{id} || $Request || ();
125 my $row;
126 if ($find) {
127         $row = $db->select(word => '*', $find)->hash
128                 or Abort("Word not found", 404);
129 }
130
131 if (exists $get{copy}) {
132         $row = {%{$row}{ qw(prio lang cat) }};
133 }
134 elsif (defined $post{form}) {{
135         sub parseinput {
136                 return if not length $_[0];
137                 require Encode;
138                 return Encode::decode_utf8($_[0]);
139         }
140
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}) {
148                         defined $val and
149                         $row->{$jsoncol}->{$col} = $val;  # hash will be encoded
150                 }
151                 else {
152                         $row->{$col} = $val;
153                 }
154         }
155         my $imagecol = $row->{image};  # backup image subcolumns
156         ref $_ eq 'HASH' and $_ = encode_json($_) for values %{$row};
157
158         if (!$row->{form}) {
159                 if ($row->{ref} ne 'delete') {
160                         Alert("Empty title",
161                                 "Confirm removal by setting <em>Reference</em> to <q>delete</q>."
162                         );
163                 }
164                 else {
165                         $db->delete(word => $find);
166                         Alert("Entry removed");
167                 }
168                 next;
169         }
170
171         eval {
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);
177                 $row = $query->hash;
178         } or do {
179                 Alert("Entry could not be saved", $@);
180                 next;
181         };
182
183         eval {
184                 while (my ($lang, $val) = each %post) {
185                         my $field = $lang;
186                         $lang =~ s/^trans-// or next;
187                         $val = parseinput($val) or next;
188                         my %subrow = (
189                                 ref   => $row->{id},
190                                 lang  => $lang,
191                                 form  => $val,
192                                 prio  => undef,
193                         );
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};
198                 }
199                 return 1;
200         } or Alert('Error creating translation entries', $@);
201
202         require Shiar_Sheet::ImagePrep;
203         my $image = Shiar_Sheet::ImagePrep->new($wordcol{source}->{-src}->($row));
204         my $reimage = eval {
205                 ($imagecol->{source} // '') ne ($replace->{source} // '') or return;
206                 $image->download($imagecol->{source});
207         };
208         !$@ or Alert(["Source image not found", $@]);
209
210         $reimage ||= $row->{image} ~~ $replace->{image};  # different source
211         $reimage ||= $row->{cover} ~~ $replace->{cover};  # resize
212         $reimage++ if $fields{rethumb};  # force refresh
213         if ($reimage) {
214                 eval {
215                         $image->convert($wordcol{convert}->{-src}->($row), $imagecol->{convert});
216                 } or do {
217                         my ($warn, @details) = ref $@ ? @{$@} : $@;
218                         Alert([ "Thumbnail image not generated", $warn ], @details);
219                 };
220         }
221 }}
222 else {
223         $row->{lang} //= $user->{editlang}->[0];
224         $row->{$_} = $get{$_} for keys %get;
225         $row->{prio} = defined $row->{ref} ? undef : 1 unless exists $row->{prio};
226 }
227
228 eval {
229         my $imagerow = $row->{image} && decode_json(delete $row->{image}) || {};
230         while (my ($col, $val) = each %{$imagerow}) {
231                 $row->{$col} = $val;
232         }
233         1;
234 } or Alert("Error decoding image metadata", $@);
235
236 my $title = $row->{id} ? "entry <small>#$row->{id}</small>" : 'new entry';
237 bless $row, 'Shiar_Sheet::FormRow';
238 :>
239 <h1>Words <:= $title :></h1>
240
241 <div class="inline">
242
243 <form action="?" method="post">
244 <input id="id" name="id" value="<:= $row->{id} // '' :>" type="hidden" />
245 <ul>
246 <:
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);
259                 }
260                 print $row->input($_ => delete $wordcol{$_}) for @span;
261                 print '</span>';
262         say '</p></li>';
263 }
264
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 };
273         }
274         my %existing = map { $_->{lang} => 1 } $row, @children;
275         $existing{$_} or push @children, { lang => $_ } for @{$user->{editlang}};
276
277         for my $ref (@children) {
278                 printf(
279                         '<li><label for="%s" title="%3$s">%s </label>',
280                         "trans-$ref->{lang}", @{$lang{ $ref->{lang} }}, # flag, name
281                 );
282                 printf(
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} // ''),
286                 );
287         }
288         say '</ul></div></li>';
289 }
290 :>
291 </ul>
292 <p>
293         <input type="submit" value="Save" />
294         <input type="submit" value="New" formaction="/writer?copy=cat" />
295 </p>
296 </form>
297
298 <:
299 if ($row->{id}) {
300 :>
301 <section id="nav">
302 <h2>Hierarchy</h2>
303
304 <:
305 say '<ul>';
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});
309 }
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});
314 }
315 :>
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" />
320 </form></li>
321 </ul>
322 </section>
323 <:
324 }
325 :>
326 </div>