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