bugfix for xml upload parsing
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Root.pm
1 package stemmaweb::Controller::Root;
2 use Moose;
3 use namespace::autoclean;
4 use Text::Tradition::Analysis qw/ run_analysis /;
5 use TryCatch;
6
7
8 BEGIN { extends 'Catalyst::Controller' }
9
10 #
11 # Sets the actions in this controller to be registered with no prefix
12 # so they function identically to actions created in MyApp.pm
13 #
14 __PACKAGE__->config(namespace => '');
15
16 =head1 NAME
17
18 stemmaweb::Controller::Root - Root Controller for stemmaweb
19
20 =head1 DESCRIPTION
21
22 Serves up the main container pages.
23
24 =head1 URLs
25
26 =head2 index
27
28 The root page (/).  Serves the main container page, from which the various
29 components will be loaded.
30
31 =cut
32
33 sub index :Path :Args(0) {
34     my ( $self, $c ) = @_;
35
36         # Are we being asked to load a text immediately? If so 
37         if( $c->req->param('withtradition') ) {
38                 $c->stash->{'withtradition'} = $c->req->param('withtradition');
39         }
40     $c->stash->{template} = 'index.tt';
41 }
42
43 =head2 about
44
45 A general overview/documentation page for the site.
46
47 =cut
48
49 sub about :Local :Args(0) {
50         my( $self, $c ) = @_;
51         $c->stash->{template} = 'about.tt';
52 }
53
54 =head1 Elements of index page
55
56 =head2 directory
57
58  GET /directory
59
60 Serves a snippet of HTML that lists the available texts.  This returns texts belonging to the logged-in user if any, otherwise it returns all public texts.
61
62 =cut
63
64 sub directory :Local :Args(0) {
65         my( $self, $c ) = @_;
66     my $m = $c->model('Directory');
67     # Is someone logged in?
68     my %usertexts;
69     if( $c->user_exists ) {
70         my $user = $c->user->get_object;
71         my @list = $m->traditionlist( $user );
72         map { $usertexts{$_->{id}} = 1 } @list;
73                 $c->stash->{usertexts} = \@list;
74                 $c->stash->{is_admin} = 1 if $user->is_admin;
75         }
76         # List public (i.e. readonly) texts separately from any user (i.e.
77         # full access) texts that exist. Admin users therefore have nothing
78         # in this list.
79         my @plist = grep { !$usertexts{$_->{id}} } $m->traditionlist('public');
80         $c->stash->{publictexts} = \@plist;
81         $c->stash->{template} = 'directory.tt';
82 }
83
84 =head1 AJAX methods for traditions and their properties
85
86 =head2 newtradition
87
88  POST /newtradition,
89         { name: <name>,
90           language: <language>,
91           public: <is_public>,
92           file: <fileupload> }
93  
94 Creates a new tradition belonging to the logged-in user, with the given name
95 and the collation given in the uploaded file. The file type is indicated via
96 the filename extension (.csv, .txt, .xls, .xlsx, .xml). Returns the ID and 
97 name of the new tradition.
98  
99 =cut
100
101 sub newtradition :Local :Args(0) {
102         my( $self, $c ) = @_;
103         return _json_error( $c, 403, 'Cannot save a tradition without being logged in' )
104                 unless $c->user_exists;
105
106         my $user = $c->user->get_object;
107         # Grab the file upload, check its name/extension, and call the
108         # appropriate parser(s).
109         my $upload = $c->request->upload('file');
110         my $name = $c->request->param('name') || 'Uploaded tradition';
111         my $lang = $c->request->param( 'language' ) || 'Default';
112         my $public = $c->request->param( 'public' ) ? 1 : undef;
113         my( $ext ) = $upload->filename =~ /\.(\w+)$/;
114         my %newopts = (
115                 'name' => $name,
116                 'language' => $lang,
117                 'public' => $public,
118                 'file' => $upload->tempname
119                 );
120
121         my $tradition;
122         my $errmsg;
123         if( $ext eq 'xml' ) {
124                 # Try the different XML parsing options to see if one works.
125                 foreach my $type ( qw/ CollateX CTE TEI / ) {
126                         try {
127                                 $tradition = Text::Tradition->new( %newopts, 'input' => $type );
128                         } catch ( Text::Tradition::Error $e ) {
129                                 $errmsg = $e->message;
130                         } catch {
131                                 $errmsg = "Unexpected parsing error";
132                         }
133                         if( $tradition ) {
134                                 $errmsg = undef;
135                                 last;
136                         }
137                 }
138         } elsif( $ext =~ /^(txt|csv|xls(x)?)$/ ) {
139                 # If it's Excel we need to pass excel => $ext;
140                 # otherwise we need to pass sep_char => [record separator].
141                 if( $ext =~ /xls/ ) {
142                         $newopts{'excel'} = $ext;
143                 } else {
144                         $newopts{'sep_char'} = $ext eq 'txt' ? "\t" : ',';
145                 }
146                 try {
147                         $tradition = Text::Tradition->new( 
148                                 %newopts,
149                                 'input' => 'Tabular',
150                                 );
151                 } catch ( Text::Tradition::Error $e ) {
152                         $errmsg = $e->message;
153                 } catch {
154                         $errmsg = "Unexpected parsing error";
155                 }
156         } else {
157                 # Error unless we have a recognized filename extension
158                 return _json_error( $c, 403, "Unrecognized file type extension $ext" );
159         }
160         
161         # Save the tradition if we have it, and return its data or else the
162         # error that occurred trying to make it.
163         if( $errmsg ) {
164                 return _json_error( $c, 500, "Error parsing tradition .$ext file: $errmsg" );
165         } elsif( !$tradition ) {
166                 return _json_error( $c, 500, "No error caught but tradition not created" );
167         }
168
169         my $m = $c->model('Directory');
170         $user->add_tradition( $tradition );
171         my $id = $c->model('Directory')->store( $tradition );
172         $c->model('Directory')->store( $user );
173         $c->stash->{'result'} = { 'id' => $id, 'name' => $tradition->name };
174         $c->forward('View::JSON');
175 }
176
177 =head2 textinfo
178
179  GET /textinfo/$textid
180  POST /textinfo/$textid, 
181         { name: $new_name, 
182           language: $new_language,
183           public: $is_public, 
184           owner: $new_userid } # only admin users can update the owner
185  
186 Returns information about a particular text.
187
188 =cut
189
190 sub textinfo :Local :Args(1) {
191         my( $self, $c, $textid ) = @_;
192         my $tradition = $c->model('Directory')->tradition( $textid );
193         unless( $tradition ) {
194                 return _json_error( $c, 404, "No tradition with ID $textid" );
195         }       
196         my $ok = _check_permission( $c, $tradition );
197         return unless $ok;
198         if( $c->req->method eq 'POST' ) {
199                 return _json_error( $c, 403, 
200                         'You do not have permission to update this tradition' ) 
201                         unless $ok eq 'full';
202                 my $params = $c->request->parameters;
203                 # Handle changes to owner-accessible parameters
204                 my $m = $c->model('Directory');
205                 my $changed;
206                 # Handle name param - easy
207                 if( exists $params->{name} ) {
208                         my $newname = delete $params->{name};
209                         unless( $tradition->name eq $newname ) {
210                                 try {
211                                         $tradition->name( $newname );
212                                         $changed = 1;
213                                 } catch {
214                                         return _json_error( $c, 500, "Error setting name to $newname" );
215                                 }
216                         }
217                 }
218                 # Handle language param, making Default => null
219                 my $langval = delete $params->{language} || 'Default';
220                 unless( $tradition->language eq $langval ) {
221                         try {
222                                 $tradition->language( $langval );
223                                 $changed = 1;
224                         } catch {
225                                 return _json_error( $c, 500, "Error setting language to $langval" );
226                         }
227                 }
228
229                 # Handle our boolean
230                 my $ispublic = $tradition->public;
231                 if( delete $params->{'public'} ) {  # if it's any true value...
232                         $tradition->public( 1 );
233                         $changed = 1 unless $ispublic;
234                 } else {  # the checkbox was unchecked, ergo it should not be public
235                         $tradition->public( 0 );
236                         $changed = 1 if $ispublic;
237                 }
238                 
239                 # Handle ownership change
240                 my $newuser;
241                 if( exists $params->{'owner'} ) {
242                         # Only admins can update user / owner
243                         my $newownerid = delete $params->{'owner'};
244                         unless( !$newownerid || 
245                                 ( $tradition->has_user && $tradition->user->id eq $newownerid ) ) {
246                                 unless( $c->user->get_object->is_admin ) {
247                                         return _json_error( $c, 403, 
248                                                 "Only admin users can change tradition ownership" );
249                                 }
250                                 $newuser = $m->find_user({ username => $newownerid });
251                                 unless( $newuser ) {
252                                         return _json_error( $c, 500, "No such user " . $newownerid );
253                                 }
254                                 $newuser->add_tradition( $tradition );
255                                 $changed = 1;
256                         }
257                 }
258                 # TODO check for rogue parameters
259                 if( scalar keys %$params ) {
260                         my $rogueparams = join( ', ', keys %$params );
261                         return _json_error( $c, 403, "Request parameters $rogueparams not recognized" );
262                 }
263                 # If we safely got to the end, then write to the database.
264                 $m->save( $tradition ) if $changed;
265                 $m->save( $newuser ) if $newuser;               
266         }
267
268         # Now return the current textinfo, whether GET or successful POST.
269         my $textinfo = {
270                 textid => $textid,
271                 name => $tradition->name,
272                 language => $tradition->language,
273                 public => $tradition->public,
274                 owner => $tradition->user ? $tradition->user->id : undef,
275                 witnesses => [ map { $_->sigil } $tradition->witnesses ],
276         };
277         my @stemmasvg = map { $_->as_svg() } $tradition->stemmata;
278         map { $_ =~ s/\n/ /mg } @stemmasvg;
279         $textinfo->{stemmata} = \@stemmasvg;
280         $c->stash->{'result'} = $textinfo;
281         $c->forward('View::JSON');
282 }
283
284 =head2 variantgraph
285
286  GET /variantgraph/$textid
287  
288 Returns the variant graph for the text specified at $textid, in SVG form.
289
290 =cut
291
292 sub variantgraph :Local :Args(1) {
293         my( $self, $c, $textid ) = @_;
294         my $tradition = $c->model('Directory')->tradition( $textid );
295         unless( $tradition ) {
296                 return _json_error( $c, 404, "No tradition with ID $textid" );
297         }       
298         my $ok = _check_permission( $c, $tradition );
299         return unless $ok;
300
301         my $collation = $tradition->collation;
302         $c->stash->{'result'} = $collation->as_svg;
303         $c->forward('View::SVG');
304 }
305         
306 =head2 stemma
307
308  GET /stemma/$textid/$stemmaseq
309  POST /stemma/$textid/$stemmaseq, { 'dot' => $dot_string }
310
311 Returns an SVG representation of the given stemma hypothesis for the text.  
312 If the URL is called with POST, the stemma at $stemmaseq will be altered
313 to reflect the definition in $dot_string. If $stemmaseq is 'n', a new
314 stemma will be added.
315
316 =cut
317
318 sub stemma :Local :Args(2) {
319         my( $self, $c, $textid, $stemmaid ) = @_;
320         my $m = $c->model('Directory');
321         my $tradition = $m->tradition( $textid );
322         unless( $tradition ) {
323                 return _json_error( $c, 404, "No tradition with ID $textid" );
324         }       
325         my $ok = _check_permission( $c, $tradition );
326         return unless $ok;
327
328         $c->stash->{'result'} = '';
329         my $stemma;
330         if( $c->req->method eq 'POST' ) {
331                 if( $ok eq 'full' ) {
332                         my $dot = $c->request->body_params->{'dot'};
333                         try {
334                                 if( $stemmaid eq 'n' ) {
335                                         # We are adding a new stemma.
336                                         $stemmaid = $tradition->stemma_count;
337                                         $stemma = $tradition->add_stemma( 'dot' => $dot );
338                                 } elsif( $stemmaid !~ /^\d+$/ ) {
339                                         return _json_error( $c, 403, "Invalid stemma ID specification $stemmaid" );
340                                 } elsif( $stemmaid < $tradition->stemma_count ) {
341                                         # We are updating an existing stemma.
342                                         $stemma = $tradition->stemma( $stemmaid );
343                                         $stemma->alter_graph( $dot );
344                                 } else {
345                                         # Unrecognized stemma ID
346                                         return _json_error( $c, 404, "No stemma at index $stemmaid, cannot update" );
347                                 }
348                         } catch ( Text::Tradition::Error $e ) {
349                                 return _json_error( $c, 500, $e->message );
350                         }
351                         $m->store( $tradition );
352                 } else {
353                         # No permissions to update the stemma
354                         return _json_error( $c, 403, 
355                                 'You do not have permission to update stemmata for this tradition' );
356                 }
357         }
358         
359         # For a GET or a successful POST request, return the SVG representation
360         # of the stemma in question, if any.
361         if( !$stemma && $tradition->stemma_count > $stemmaid ) {
362                 $stemma = $tradition->stemma( $stemmaid );
363         }
364         my $stemma_xml = $stemma ? $stemma->as_svg() : '';
365         # What was requested, XML or JSON?
366         my $return_view = 'SVG';
367         if( my $accept_header = $c->req->header('Accept') ) {
368                 $c->log->debug( "Received Accept header: $accept_header" );
369                 foreach my $type ( split( /,\s*/, $accept_header ) ) {
370                         # If we were first asked for XML, return SVG
371                         last if $type =~ /^(application|text)\/xml$/;
372                         # If we were first asked for JSON, return JSON
373                         if( $type eq 'application/json' ) {
374                                 $return_view = 'JSON';
375                                 last;
376                         }
377                 }
378         }
379         if( $return_view eq 'SVG' ) {
380                 $c->stash->{'result'} = $stemma_xml;
381                 $c->forward('View::SVG');
382         } else { # JSON
383                 $stemma_xml =~ s/\n/ /mg;
384                 $c->stash->{'result'} = { 'stemmaid' => $stemmaid, 'stemmasvg' => $stemma_xml };
385                 $c->forward('View::JSON');
386         }
387 }
388
389 =head2 stemmadot
390
391  GET /stemmadot/$textid/$stemmaseq
392  
393 Returns the 'dot' format representation of the current stemma hypothesis.
394
395 =cut
396
397 sub stemmadot :Local :Args(2) {
398         my( $self, $c, $textid, $stemmaid ) = @_;
399         my $m = $c->model('Directory');
400         my $tradition = $m->tradition( $textid );
401         unless( $tradition ) {
402                 return _json_error( $c, 404, "No tradition with ID $textid" );
403         }       
404         my $ok = _check_permission( $c, $tradition );
405         return unless $ok;
406         my $stemma = $tradition->stemma( $stemmaid );
407         unless( $stemma ) {
408                 return _json_error( $c, 404, "Tradition $textid has no stemma ID $stemmaid" );
409         }
410         # Get the dot and transmute its line breaks to literal '|n'
411         $c->stash->{'result'} = { 'dot' =>  $stemma->editable( { linesep => '|n' } ) };
412         $c->forward('View::JSON');
413 }
414
415 ####################
416 ### Helper functions
417 ####################
418
419 # Helper to check what permission, if any, the active user has for
420 # the given tradition
421 sub _check_permission {
422         my( $c, $tradition ) = @_;
423     my $user = $c->user_exists ? $c->user->get_object : undef;
424     if( $user ) {
425         return 'full' if ( $user->is_admin || 
426                 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
427     }
428         # Text doesn't belong to us, so maybe it's public?
429         return 'readonly' if $tradition->public;
430
431         # ...nope. Forbidden!
432         return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
433 }
434
435 # Helper to throw a JSON exception
436 sub _json_error {
437         my( $c, $code, $errmsg ) = @_;
438         $c->response->status( $code );
439         $c->stash->{'result'} = { 'error' => $errmsg };
440         $c->forward('View::JSON');
441         return 0;
442 }
443
444 =head2 default
445
446 Standard 404 error page
447
448 =cut
449
450 sub default :Path {
451     my ( $self, $c ) = @_;
452     $c->response->body( 'Page not found' );
453     $c->response->status(404);
454 }
455
456 =head2 end
457
458 Attempt to render a view, if needed.
459
460 =cut
461
462 sub end : ActionClass('RenderView') {}
463
464 =head1 AUTHOR
465
466 Tara L Andrews
467
468 =head1 LICENSE
469
470 This library is free software. You can redistribute it and/or modify
471 it under the same terms as Perl itself.
472
473 =cut
474
475 __PACKAGE__->meta->make_immutable;
476
477 1;