Allow setting text direction.
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Root.pm
1 package stemmaweb::Controller::Root;
2 use Moose;
3 use namespace::autoclean;
4 use JSON qw ();
5 use TryCatch;
6 use XML::LibXML;
7 use XML::LibXML::XPathContext;
8
9
10 BEGIN { extends 'Catalyst::Controller' }
11
12 #
13 # Sets the actions in this controller to be registered with no prefix
14 # so they function identically to actions created in MyApp.pm
15 #
16 __PACKAGE__->config(namespace => '');
17
18 =head1 NAME
19
20 stemmaweb::Controller::Root - Root Controller for stemmaweb
21
22 =head1 DESCRIPTION
23
24 Serves up the main container pages.
25
26 =head1 URLs
27
28 =head2 index
29
30 The root page (/).  Serves the main container page, from which the various
31 components will be loaded.
32
33 =cut
34
35 sub index :Path :Args(0) {
36     my ( $self, $c ) = @_;
37
38         # Are we being asked to load a text immediately? If so 
39         if( $c->req->param('withtradition') ) {
40                 $c->stash->{'withtradition'} = $c->req->param('withtradition');
41         }
42     $c->stash->{template} = 'index.tt';
43 }
44
45 =head2 about
46
47 A general overview/documentation page for the site.
48
49 =cut
50
51 sub about :Local :Args(0) {
52         my( $self, $c ) = @_;
53         $c->stash->{template} = 'about.tt';
54 }
55
56 =head2 help/*
57
58 A dispatcher for documentation of various aspects of the application.
59
60 =cut
61
62 sub help :Local :Args(1) {
63         my( $self, $c, $topic ) = @_;
64         $c->stash->{template} = "$topic.tt";
65 }
66
67 =head1 Elements of index page
68
69 =head2 directory
70
71  GET /directory
72
73 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.
74
75 =cut
76
77 sub directory :Local :Args(0) {
78         my( $self, $c ) = @_;
79     my $m = $c->model('Directory');
80     # Is someone logged in?
81     my %usertexts;
82     if( $c->user_exists ) {
83         my $user = $c->user->get_object;
84         my @list = $m->traditionlist( $user );
85         map { $usertexts{$_->{id}} = 1 } @list;
86                 $c->stash->{usertexts} = \@list;
87                 $c->stash->{is_admin} = 1 if $user->is_admin;
88         }
89         # List public (i.e. readonly) texts separately from any user (i.e.
90         # full access) texts that exist. Admin users therefore have nothing
91         # in this list.
92         my @plist = grep { !$usertexts{$_->{id}} } $m->traditionlist('public');
93         $c->stash->{publictexts} = \@plist;
94         $c->stash->{template} = 'directory.tt';
95 }
96
97 =head1 AJAX methods for traditions and their properties
98
99 =head2 newtradition
100
101  POST /newtradition,
102         { name: <name>,
103           language: <language>,
104           public: <is_public>,
105           file: <fileupload> }
106  
107 Creates a new tradition belonging to the logged-in user, with the given name
108 and the collation given in the uploaded file. The file type is indicated via
109 the filename extension (.csv, .txt, .xls, .xlsx, .xml). Returns the ID and 
110 name of the new tradition.
111  
112 =cut
113
114 sub newtradition :Local :Args(0) {
115         my( $self, $c ) = @_;
116         return _json_error( $c, 403, 'Cannot save a tradition without being logged in' )
117                 unless $c->user_exists;
118
119         my $user = $c->user->get_object;
120         # Grab the file upload, check its name/extension, and call the
121         # appropriate parser(s).
122         my $upload = $c->request->upload('file');
123         my $name = $c->request->param('name') || 'Uploaded tradition';
124         my $lang = $c->request->param( 'language' ) || 'Default';
125         my $public = $c->request->param( 'public' ) ? 1 : undef;
126         my $direction = $c->request->param('direction') || 'LR';
127
128         my( $ext ) = $upload->filename =~ /\.(\w+)$/;
129         my %newopts = (
130                 'name' => $name,
131                 'language' => $lang,
132                 'public' => $public,
133                 'file' => $upload->tempname,
134                 'direction' => $direction,
135                 );
136
137         my $tradition;
138         my $errmsg;
139         if( $ext eq 'xml' ) {
140                 my $type;
141                 # Parse the XML to see which flavor it is.
142                 my $parser = XML::LibXML->new();
143                 my $doc;
144                 try {
145                         $doc = $parser->parse_file( $newopts{'file'} );
146                 } catch( $err ) {
147                         $errmsg = "XML file parsing error: $err";
148                 }
149                 if( $doc ) {
150                         if( $doc->documentElement->nodeName eq 'graphml' ) {
151                                 $type = 'CollateX';
152                         } elsif( $doc->documentElement->nodeName ne 'TEI' ) {
153                                 $errmsg = 'Unrecognized XML type ' . $doc->documentElement->nodeName;
154                         } else {
155                                 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
156                                 my $venc = $xpc->findvalue( '/TEI/teiHeader/encodingDesc/variantEncoding/attribute::method' );
157                                 if( $venc && $venc eq 'double-end-point' ) {
158                                         $type = 'CTE';
159                                 } else {
160                                         $type = 'TEI';
161                                 }
162                         }
163                 }
164                 # Try the relevant XML parsing option.
165                 if( $type ) {
166                         delete $newopts{'file'};
167                         $newopts{'xmlobj'} = $doc;
168                         try {
169                                 $tradition = Text::Tradition->new( %newopts, 'input' => $type );
170                         } catch ( Text::Tradition::Error $e ) {
171                                 $errmsg = $e->message;
172                         } catch ( $e ) {
173                                 $errmsg = "Unexpected parsing error: $e";
174                         }
175                 }
176         } elsif( $ext =~ /^(txt|csv|xls(x)?)$/ ) {
177                 # If it's Excel we need to pass excel => $ext;
178                 # otherwise we need to pass sep_char => [record separator].
179                 if( $ext =~ /xls/ ) {
180                         $newopts{'excel'} = $ext;
181                 } else {
182                         $newopts{'sep_char'} = $ext eq 'txt' ? "\t" : ',';
183                 }
184                 try {
185                         $tradition = Text::Tradition->new( 
186                                 %newopts,
187                                 'input' => 'Tabular',
188                                 );
189                 } catch ( Text::Tradition::Error $e ) {
190                         $errmsg = $e->message;
191                 } catch ( $e ) {
192                         $errmsg = "Unexpected parsing error: $e";
193                 }
194         } else {
195                 # Error unless we have a recognized filename extension
196                 return _json_error( $c, 403, "Unrecognized file type extension $ext" );
197         }
198         
199         # Save the tradition if we have it, and return its data or else the
200         # error that occurred trying to make it.
201         if( $errmsg ) {
202                 return _json_error( $c, 500, "Error parsing tradition .$ext file: $errmsg" );
203         } elsif( !$tradition ) {
204                 return _json_error( $c, 500, "No error caught but tradition not created" );
205         }
206
207         my $m = $c->model('Directory');
208         $user->add_tradition( $tradition );
209         my $id = $c->model('Directory')->store( $tradition );
210         $c->model('Directory')->store( $user );
211         $c->stash->{'result'} = { 'id' => $id, 'name' => $tradition->name };
212         $c->forward('View::JSON');
213 }
214
215 =head2 textinfo
216
217  GET /textinfo/$textid
218  POST /textinfo/$textid, 
219         { name: $new_name, 
220           language: $new_language,
221           public: $is_public, 
222           owner: $new_userid } # only admin users can update the owner
223  
224 Returns information about a particular text.
225
226 =cut
227
228 sub textinfo :Local :Args(1) {
229         my( $self, $c, $textid ) = @_;
230         my $tradition = $c->model('Directory')->tradition( $textid );
231         ## Have to keep users in the same scope as tradition
232         my $newuser;
233         my $olduser;
234         unless( $tradition ) {
235                 return _json_error( $c, 404, "No tradition with ID $textid" );
236         }       
237         my $ok = _check_permission( $c, $tradition );
238         return unless $ok;
239         if( $c->req->method eq 'POST' ) {
240                 return _json_error( $c, 403, 
241                         'You do not have permission to update this tradition' ) 
242                         unless $ok eq 'full';
243                 my $params = $c->request->parameters;
244                 # Handle changes to owner-accessible parameters
245                 my $m = $c->model('Directory');
246                 my $changed;
247                 # Handle name param - easy
248                 if( exists $params->{name} ) {
249                         my $newname = delete $params->{name};
250                         unless( $tradition->name eq $newname ) {
251                                 try {
252                                         $tradition->name( $newname );
253                                         $changed = 1;
254                                 } catch {
255                                         return _json_error( $c, 500, "Error setting name to $newname: $@" );
256                                 }
257                         }
258                 }
259                 # Handle language param, making Default => null
260                 my $langval = delete $params->{language} || 'Default';
261                 
262                 unless( $tradition->language eq $langval || !$tradition->can('language') ) {
263                         try {
264                                 $tradition->language( $langval );
265                                 $changed = 1;
266                         } catch {
267                                 return _json_error( $c, 500, "Error setting language to $langval: $@" );
268                         }
269                 }
270
271                 # Handle our boolean
272                 my $ispublic = $tradition->public;
273                 if( delete $params->{'public'} ) {  # if it's any true value...
274                         $tradition->public( 1 );
275                         $changed = 1 unless $ispublic;
276                 } else {  # the checkbox was unchecked, ergo it should not be public
277                         $tradition->public( 0 );
278                         $changed = 1 if $ispublic;
279                 }
280                 
281                 # Handle ownership change
282                 if( exists $params->{'owner'} ) {
283                         # Only admins can update user / owner
284                         my $newownerid = delete $params->{'owner'};
285                         if( $tradition->has_user && !$tradition->user ) {
286                                 $tradition->clear_user;
287                         }
288                         unless( !$newownerid || 
289                                 ( $tradition->has_user && $tradition->user->email eq $newownerid ) ) {
290                                 unless( $c->user->get_object->is_admin ) {
291                                         return _json_error( $c, 403, 
292                                                 "Only admin users can change tradition ownership" );
293                                 }
294                                 $newuser = $m->find_user({ email => $newownerid });
295                                 unless( $newuser ) {
296                                         return _json_error( $c, 500, "No such user " . $newownerid );
297                                 }
298                                 if( $tradition->has_user ) {
299                                         $olduser = $tradition->user;
300                                         $olduser->remove_tradition( $tradition );
301                                 }
302                                 $newuser->add_tradition( $tradition );
303                                 $changed = 1;
304                         }
305                 }
306                 # TODO check for rogue parameters
307                 if( scalar keys %$params ) {
308                         my $rogueparams = join( ', ', keys %$params );
309                         return _json_error( $c, 403, "Request parameters $rogueparams not recognized" );
310                 }
311                 # If we safely got to the end, then write to the database.
312                 $m->save( $tradition ) if $changed;
313                 $m->save( $newuser ) if $newuser;               
314         }
315
316         # Now return the current textinfo, whether GET or successful POST.
317         my $textinfo = {
318                 textid => $textid,
319                 name => $tradition->name,
320                 public => $tradition->public || 0,
321                 owner => $tradition->user ? $tradition->user->email : undef,
322                 witnesses => [ map { $_->sigil } $tradition->witnesses ],
323                 # TODO Send them all with appropriate parameters so that the
324                 # client side can choose what to display.
325                 reltypes => [ map { $_->name } grep { !$_->is_weak && $_->is_colocation }
326                         $tradition->collation->relationship_types ]
327         };
328         ## TODO Make these into callbacks in the other controllers maybe?
329         if( $tradition->can('language') ) {
330                 $textinfo->{'language'} = $tradition->language;
331         }
332         if( $tradition->can('stemweb_jobid') ) {
333                 $textinfo->{'stemweb_jobid'} = $tradition->stemweb_jobid || 0;
334         }
335         my @stemmasvg = map { _stemma_info( $_ ) } $tradition->stemmata;
336         $textinfo->{stemmata} = \@stemmasvg;
337         $c->stash->{'result'} = $textinfo;
338         $c->forward('View::JSON');
339 }
340
341 =head2 variantgraph
342
343  GET /variantgraph/$textid
344  
345 Returns the variant graph for the text specified at $textid, in SVG form.
346
347 =cut
348
349 sub variantgraph :Local :Args(1) {
350         my( $self, $c, $textid ) = @_;
351         my $tradition = $c->model('Directory')->tradition( $textid );
352         unless( $tradition ) {
353                 return _json_error( $c, 404, "No tradition with ID $textid" );
354         }       
355         my $ok = _check_permission( $c, $tradition );
356         return unless $ok;
357
358         my $collation = $tradition->collation;
359         $c->stash->{'result'} = $collation->as_svg;
360         $c->forward('View::SVG');
361 }
362
363 sub _stemma_info {
364         my( $stemma, $sid ) = @_;
365         my $ssvg = $stemma->as_svg();
366         $ssvg =~ s/\n/ /mg;
367         my $sinfo = {
368                 name => $stemma->identifier, 
369                 directed => _json_bool( !$stemma->is_undirected ),
370                 svg => $ssvg }; 
371         if( $sid ) {
372                 $sinfo->{stemmaid} = $sid;
373         }
374         return $sinfo;
375 }
376
377 ## TODO Separate stemma manipulation functionality into its own controller.
378         
379 =head2 stemma
380
381  GET /stemma/$textid/$stemmaseq
382  POST /stemma/$textid/$stemmaseq, { 'dot' => $dot_string }
383
384 Returns an SVG representation of the given stemma hypothesis for the text.  
385 If the URL is called with POST, the stemma at $stemmaseq will be altered
386 to reflect the definition in $dot_string. If $stemmaseq is 'n', a new
387 stemma will be added.
388
389 =cut
390
391 sub stemma :Local :Args(2) {
392         my( $self, $c, $textid, $stemmaid ) = @_;
393         my $m = $c->model('Directory');
394         my $tradition = $m->tradition( $textid );
395         unless( $tradition ) {
396                 return _json_error( $c, 404, "No tradition with ID $textid" );
397         }       
398         my $ok = _check_permission( $c, $tradition );
399         return unless $ok;
400
401         $c->stash->{'result'} = '';
402         my $stemma;
403         if( $c->req->method eq 'POST' ) {
404                 if( $ok eq 'full' ) {
405                         my $dot = $c->request->body_params->{'dot'};
406                         try {
407                                 if( $stemmaid eq 'n' ) {
408                                         # We are adding a new stemma.
409                                         $stemmaid = $tradition->stemma_count;
410                                         $stemma = $tradition->add_stemma( 'dot' => $dot );
411                                 } elsif( $stemmaid !~ /^\d+$/ ) {
412                                         return _json_error( $c, 403, "Invalid stemma ID specification $stemmaid" );
413                                 } elsif( $stemmaid < $tradition->stemma_count ) {
414                                         # We are updating an existing stemma.
415                                         $stemma = $tradition->stemma( $stemmaid );
416                                         $stemma->alter_graph( $dot );
417                                 } else {
418                                         # Unrecognized stemma ID
419                                         return _json_error( $c, 404, "No stemma at index $stemmaid, cannot update" );
420                                 }
421                         } catch ( Text::Tradition::Error $e ) {
422                                 return _json_error( $c, 500, $e->message );
423                         }
424                         $m->store( $tradition );
425                 } else {
426                         # No permissions to update the stemma
427                         return _json_error( $c, 403, 
428                                 'You do not have permission to update stemmata for this tradition' );
429                 }
430         }
431         
432         # For a GET or a successful POST request, return the SVG representation
433         # of the stemma in question, if any.
434         if( !$stemma && $tradition->stemma_count > $stemmaid ) {
435                 $stemma = $tradition->stemma( $stemmaid );
436         }
437         # What was requested, XML or JSON?
438         my $return_view = 'SVG';
439         if( my $accept_header = $c->req->header('Accept') ) {
440                 $c->log->debug( "Received Accept header: $accept_header" );
441                 foreach my $type ( split( /,\s*/, $accept_header ) ) {
442                         # If we were first asked for XML, return SVG
443                         last if $type =~ /^(application|text)\/xml$/;
444                         # If we were first asked for JSON, return JSON
445                         if( $type eq 'application/json' ) {
446                                 $return_view = 'JSON';
447                                 last;
448                         }
449                 }
450         }
451         if( $return_view eq 'SVG' ) {
452                 $c->stash->{'result'} = $stemma->as_svg();
453                 $c->forward('View::SVG');
454         } else { # JSON
455                 $c->stash->{'result'} = _stemma_info( $stemma, $stemmaid );
456                 $c->forward('View::JSON');
457         }
458 }
459
460 =head2 stemmadot
461
462  GET /stemmadot/$textid/$stemmaseq
463  
464 Returns the 'dot' format representation of the current stemma hypothesis.
465
466 =cut
467
468 sub stemmadot :Local :Args(2) {
469         my( $self, $c, $textid, $stemmaid ) = @_;
470         my $m = $c->model('Directory');
471         my $tradition = $m->tradition( $textid );
472         unless( $tradition ) {
473                 return _json_error( $c, 404, "No tradition with ID $textid" );
474         }       
475         my $ok = _check_permission( $c, $tradition );
476         return unless $ok;
477         my $stemma = $tradition->stemma( $stemmaid );
478         unless( $stemma ) {
479                 return _json_error( $c, 404, "Tradition $textid has no stemma ID $stemmaid" );
480         }
481         # Get the dot and transmute its line breaks to literal '|n'
482         $c->stash->{'result'} = { 'dot' =>  $stemma->editable( { linesep => '|n' } ) };
483         $c->forward('View::JSON');
484 }
485
486 =head2 stemmaroot
487
488  POST /stemmaroot/$textid/$stemmaseq, { root: <root node ID> }
489
490 Orients the given stemma so that the given node is the root (archetype). Returns the 
491 information structure for the new stemma.
492
493 =cut 
494
495 sub stemmaroot :Local :Args(2) {
496         my( $self, $c, $textid, $stemmaid ) = @_;
497         my $m = $c->model('Directory');
498         my $tradition = $m->tradition( $textid );
499         unless( $tradition ) {
500                 return _json_error( $c, 404, "No tradition with ID $textid" );
501         }       
502         my $ok = _check_permission( $c, $tradition );
503         if( $ok eq 'full' ) {
504                 my $stemma = $tradition->stemma( $stemmaid );
505                 try {
506                         $stemma->root_graph( $c->req->param('root') );
507                         $m->save( $tradition );
508                 } catch( Text::Tradition::Error $e ) {
509                         return _json_error( $c, 400, $e->message );
510                 } catch {
511                         return _json_error( $c, 500, "Error re-rooting stemma: $@" );
512                 }
513                 $c->stash->{'result'} = _stemma_info( $stemma );
514                 $c->forward('View::JSON');
515         } else {
516                 return _json_error( $c, 403,  
517                                 'You do not have permission to update stemmata for this tradition' );
518         }
519 }
520
521 =head2 download
522
523  GET /download/$textid/$format
524  
525 Returns a file for download of the tradition in the requested format.
526  
527 =cut
528
529 sub download :Local :Args(2) {
530         my( $self, $c, $textid, $format ) = @_;
531         my $tradition = $c->model('Directory')->tradition( $textid );
532         unless( $tradition ) {
533                 return _json_error( $c, 404, "No tradition with ID $textid" );
534         }
535         my $ok = _check_permission( $c, $tradition );
536         return unless $ok;
537
538         my $outmethod = "as_" . lc( $format );
539         my $view = "View::$format";
540         $c->stash->{'name'} = $tradition->name();
541         $c->stash->{'download'} = 1;
542         my @outputargs;
543         if( $format eq 'SVG' ) {
544                 # Send the list of colors through to the backend.
545                 # TODO Think of some way not to hard-code this.
546                 push( @outputargs, { 'show_relations' => 'all',
547                         'graphcolors' => [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", 
548                                 "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ] } );
549         }
550         try {
551                 $c->stash->{'result'} = $tradition->collation->$outmethod( @outputargs );
552         } catch( Text::Tradition::Error $e ) {
553                 return _json_error( $c, 500, $e->message );
554         }
555         $c->forward( $view );
556 }
557
558 ####################
559 ### Helper functions
560 ####################
561
562 # Helper to check what permission, if any, the active user has for
563 # the given tradition
564 sub _check_permission {
565         my( $c, $tradition ) = @_;
566     my $user = $c->user_exists ? $c->user->get_object : undef;
567     if( $user ) {
568         return 'full' if ( $user->is_admin || 
569                 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
570     }
571         # Text doesn't belong to us, so maybe it's public?
572         return 'readonly' if $tradition->public;
573
574         # ...nope. Forbidden!
575         return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
576 }
577
578 # Helper to throw a JSON exception
579 sub _json_error {
580         my( $c, $code, $errmsg ) = @_;
581         $c->response->status( $code );
582         $c->stash->{'result'} = { 'error' => $errmsg };
583         $c->forward('View::JSON');
584         return 0;
585 }
586
587 sub _json_bool {
588         return $_[0] ? JSON::true : JSON::false;
589 }
590
591 =head2 default
592
593 Standard 404 error page
594
595 =cut
596
597 sub default :Path {
598     my ( $self, $c ) = @_;
599     $c->response->body( 'Page not found' );
600     $c->response->status(404);
601 }
602
603 =head2 end
604
605 Attempt to render a view, if needed.
606
607 =cut
608
609 sub end : ActionClass('RenderView') {}
610
611 =head1 AUTHOR
612
613 Tara L Andrews
614
615 =head1 LICENSE
616
617 This library is free software. You can redistribute it and/or modify
618 it under the same terms as Perl itself.
619
620 =cut
621
622 __PACKAGE__->meta->make_immutable;
623
624 1;