1 package stemmaweb::Controller::Root;
3 use namespace::autoclean;
7 use XML::LibXML::XPathContext;
10 BEGIN { extends 'Catalyst::Controller' }
13 # Sets the actions in this controller to be registered with no prefix
14 # so they function identically to actions created in MyApp.pm
16 __PACKAGE__->config(namespace => '');
20 stemmaweb::Controller::Root - Root Controller for stemmaweb
24 Serves up the main container pages.
30 The root page (/). Serves the main container page, from which the various
31 components will be loaded.
35 sub index :Path :Args(0) {
36 my ( $self, $c ) = @_;
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');
42 $c->stash->{template} = 'index.tt';
47 A general overview/documentation page for the site.
51 sub about :Local :Args(0) {
53 $c->stash->{template} = 'about.tt';
58 A dispatcher for documentation of various aspects of the application.
62 sub help :Local :Args(1) {
63 my( $self, $c, $topic ) = @_;
64 $c->stash->{template} = "$topic.tt";
67 =head1 Elements of index page
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.
77 sub directory :Local :Args(0) {
79 my $m = $c->model('Directory');
80 # Is someone logged in?
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;
89 # List public (i.e. readonly) texts separately from any user (i.e.
90 # full access) texts that exist. Admin users therefore have nothing
92 my @plist = grep { !$usertexts{$_->{id}} } $m->traditionlist('public');
93 $c->stash->{publictexts} = \@plist;
94 $c->stash->{template} = 'directory.tt';
97 =head1 AJAX methods for traditions and their properties
103 language: <language>,
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.
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;
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( $ext ) = $upload->filename =~ /\.(\w+)$/;
131 'file' => $upload->tempname
136 if( $ext eq 'xml' ) {
138 # Parse the XML to see which flavor it is.
139 my $parser = XML::LibXML->new();
142 $doc = $parser->parse_file( $newopts{'file'} );
144 $errmsg = "XML file parsing error: $err";
147 if( $doc->documentElement->nodeName eq 'graphml' ) {
149 } elsif( $doc->documentElement->nodeName ne 'TEI' ) {
150 $errmsg = 'Unrecognized XML type ' . $doc->documentElement->nodeName;
152 my $xpc = XML::LibXML::XPathContext->new( $doc->documentElement );
153 my $venc = $xpc->findvalue( '/TEI/teiHeader/encodingDesc/variantEncoding/attribute::method' );
154 if( $venc && $venc eq 'double-end-point' ) {
161 # Try the relevant XML parsing option.
163 delete $newopts{'file'};
164 $newopts{'xmlobj'} = $doc;
166 $tradition = Text::Tradition->new( %newopts, 'input' => $type );
167 } catch ( Text::Tradition::Error $e ) {
168 $errmsg = $e->message;
170 $errmsg = "Unexpected parsing error: $e";
173 } elsif( $ext =~ /^(txt|csv|xls(x)?)$/ ) {
174 # If it's Excel we need to pass excel => $ext;
175 # otherwise we need to pass sep_char => [record separator].
176 if( $ext =~ /xls/ ) {
177 $newopts{'excel'} = $ext;
179 $newopts{'sep_char'} = $ext eq 'txt' ? "\t" : ',';
182 $tradition = Text::Tradition->new(
184 'input' => 'Tabular',
186 } catch ( Text::Tradition::Error $e ) {
187 $errmsg = $e->message;
189 $errmsg = "Unexpected parsing error: $e";
192 # Error unless we have a recognized filename extension
193 return _json_error( $c, 403, "Unrecognized file type extension $ext" );
196 # Save the tradition if we have it, and return its data or else the
197 # error that occurred trying to make it.
199 return _json_error( $c, 500, "Error parsing tradition .$ext file: $errmsg" );
200 } elsif( !$tradition ) {
201 return _json_error( $c, 500, "No error caught but tradition not created" );
204 my $m = $c->model('Directory');
205 $user->add_tradition( $tradition );
206 my $id = $c->model('Directory')->store( $tradition );
207 $c->model('Directory')->store( $user );
208 $c->stash->{'result'} = { 'id' => $id, 'name' => $tradition->name };
209 $c->forward('View::JSON');
214 GET /textinfo/$textid
215 POST /textinfo/$textid,
217 language: $new_language,
219 owner: $new_userid } # only admin users can update the owner
221 Returns information about a particular text.
225 sub textinfo :Local :Args(1) {
226 my( $self, $c, $textid ) = @_;
227 my $tradition = $c->model('Directory')->tradition( $textid );
228 ## Have to keep users in the same scope as tradition
231 unless( $tradition ) {
232 return _json_error( $c, 404, "No tradition with ID $textid" );
234 my $ok = _check_permission( $c, $tradition );
236 if( $c->req->method eq 'POST' ) {
237 return _json_error( $c, 403,
238 'You do not have permission to update this tradition' )
239 unless $ok eq 'full';
240 my $params = $c->request->parameters;
241 # Handle changes to owner-accessible parameters
242 my $m = $c->model('Directory');
244 # Handle name param - easy
245 if( exists $params->{name} ) {
246 my $newname = delete $params->{name};
247 unless( $tradition->name eq $newname ) {
249 $tradition->name( $newname );
252 return _json_error( $c, 500, "Error setting name to $newname: $@" );
256 # Handle language param, making Default => null
257 my $langval = delete $params->{language} || 'Default';
259 unless( $tradition->language eq $langval || !$tradition->can('language') ) {
261 $tradition->language( $langval );
264 return _json_error( $c, 500, "Error setting language to $langval: $@" );
269 my $ispublic = $tradition->public;
270 if( delete $params->{'public'} ) { # if it's any true value...
271 $tradition->public( 1 );
272 $changed = 1 unless $ispublic;
273 } else { # the checkbox was unchecked, ergo it should not be public
274 $tradition->public( 0 );
275 $changed = 1 if $ispublic;
278 # Handle ownership change
279 if( exists $params->{'owner'} ) {
280 # Only admins can update user / owner
281 my $newownerid = delete $params->{'owner'};
282 if( $tradition->has_user && !$tradition->user ) {
283 $tradition->clear_user;
285 unless( !$newownerid ||
286 ( $tradition->has_user && $tradition->user->email eq $newownerid ) ) {
287 unless( $c->user->get_object->is_admin ) {
288 return _json_error( $c, 403,
289 "Only admin users can change tradition ownership" );
291 $newuser = $m->find_user({ email => $newownerid });
293 return _json_error( $c, 500, "No such user " . $newownerid );
295 if( $tradition->has_user ) {
296 $olduser = $tradition->user;
297 $olduser->remove_tradition( $tradition );
299 $newuser->add_tradition( $tradition );
303 # TODO check for rogue parameters
304 if( scalar keys %$params ) {
305 my $rogueparams = join( ', ', keys %$params );
306 return _json_error( $c, 403, "Request parameters $rogueparams not recognized" );
308 # If we safely got to the end, then write to the database.
309 $m->save( $tradition ) if $changed;
310 $m->save( $newuser ) if $newuser;
313 # Now return the current textinfo, whether GET or successful POST.
316 name => $tradition->name,
317 public => $tradition->public || 0,
318 owner => $tradition->user ? $tradition->user->email : undef,
319 witnesses => [ map { $_->sigil } $tradition->witnesses ],
321 ## TODO Make these into callbacks in the other controllers maybe?
322 if( $tradition->can('language') ) {
323 $textinfo->{'language'} = $tradition->language;
325 if( $tradition->can('stemweb_jobid') ) {
326 $textinfo->{'stemweb_jobid'} = $tradition->stemweb_jobid || 0;
328 my @stemmasvg = map { _stemma_info( $_ ) } $tradition->stemmata;
329 $textinfo->{stemmata} = \@stemmasvg;
330 $c->stash->{'result'} = $textinfo;
331 $c->forward('View::JSON');
336 GET /variantgraph/$textid
338 Returns the variant graph for the text specified at $textid, in SVG form.
342 sub variantgraph :Local :Args(1) {
343 my( $self, $c, $textid ) = @_;
344 my $tradition = $c->model('Directory')->tradition( $textid );
345 unless( $tradition ) {
346 return _json_error( $c, 404, "No tradition with ID $textid" );
348 my $ok = _check_permission( $c, $tradition );
351 my $collation = $tradition->collation;
352 $c->stash->{'result'} = $collation->as_svg;
353 $c->forward('View::SVG');
357 my( $stemma, $sid ) = @_;
358 my $ssvg = $stemma->as_svg();
361 name => $stemma->identifier,
362 directed => _json_bool( !$stemma->is_undirected ),
365 $sinfo->{stemmaid} = $sid;
370 ## TODO Separate stemma manipulation functionality into its own controller.
374 GET /stemma/$textid/$stemmaseq
375 POST /stemma/$textid/$stemmaseq, { 'dot' => $dot_string }
377 Returns an SVG representation of the given stemma hypothesis for the text.
378 If the URL is called with POST, the stemma at $stemmaseq will be altered
379 to reflect the definition in $dot_string. If $stemmaseq is 'n', a new
380 stemma will be added.
384 sub stemma :Local :Args(2) {
385 my( $self, $c, $textid, $stemmaid ) = @_;
386 my $m = $c->model('Directory');
387 my $tradition = $m->tradition( $textid );
388 unless( $tradition ) {
389 return _json_error( $c, 404, "No tradition with ID $textid" );
391 my $ok = _check_permission( $c, $tradition );
394 $c->stash->{'result'} = '';
396 if( $c->req->method eq 'POST' ) {
397 if( $ok eq 'full' ) {
398 my $dot = $c->request->body_params->{'dot'};
399 # Graph::Reader::Dot does not handle bare unicode. We get around this
400 # by wrapping all words in double quotes, as long as they aren't already
401 # wrapped, and as long as they aren't the initial '(di)?graph .*'.
403 my @dlines = split( "\n", $dot );
406 unless( /^(di)?graph/ ) { # Skip the first line
407 s/(?<!")\b(\w+)\b(?!")/"$1"/g;
411 # $dot =~ s/(?<!")\b(?!(?:digraph|stemma)\b)(\w+)\b(?!")/"$1"/g;
413 print STDERR "$dot\n";
415 if( $stemmaid eq 'n' ) {
416 # We are adding a new stemma.
417 $stemmaid = $tradition->stemma_count;
418 $stemma = $tradition->add_stemma( 'dot' => $dot );
419 } elsif( $stemmaid !~ /^\d+$/ ) {
420 return _json_error( $c, 403, "Invalid stemma ID specification $stemmaid" );
421 } elsif( $stemmaid < $tradition->stemma_count ) {
422 # We are updating an existing stemma.
423 $stemma = $tradition->stemma( $stemmaid );
424 $stemma->alter_graph( $dot );
426 # Unrecognized stemma ID
427 return _json_error( $c, 404, "No stemma at index $stemmaid, cannot update" );
429 } catch ( Text::Tradition::Error $e ) {
430 return _json_error( $c, 500, $e->message );
432 $m->store( $tradition );
434 # No permissions to update the stemma
435 return _json_error( $c, 403,
436 'You do not have permission to update stemmata for this tradition' );
440 # For a GET or a successful POST request, return the SVG representation
441 # of the stemma in question, if any.
442 if( !$stemma && $tradition->stemma_count > $stemmaid ) {
443 $stemma = $tradition->stemma( $stemmaid );
445 # What was requested, XML or JSON?
446 my $return_view = 'SVG';
447 if( my $accept_header = $c->req->header('Accept') ) {
448 $c->log->debug( "Received Accept header: $accept_header" );
449 foreach my $type ( split( /,\s*/, $accept_header ) ) {
450 # If we were first asked for XML, return SVG
451 last if $type =~ /^(application|text)\/xml$/;
452 # If we were first asked for JSON, return JSON
453 if( $type eq 'application/json' ) {
454 $return_view = 'JSON';
459 if( $return_view eq 'SVG' ) {
460 $c->stash->{'result'} = $stemma->as_svg();
461 $c->forward('View::SVG');
463 $c->stash->{'result'} = { _stemma_info( $stemma, $stemmaid ) };
464 $c->forward('View::JSON');
470 GET /stemmadot/$textid/$stemmaseq
472 Returns the 'dot' format representation of the current stemma hypothesis.
476 sub stemmadot :Local :Args(2) {
477 my( $self, $c, $textid, $stemmaid ) = @_;
478 my $m = $c->model('Directory');
479 my $tradition = $m->tradition( $textid );
480 unless( $tradition ) {
481 return _json_error( $c, 404, "No tradition with ID $textid" );
483 my $ok = _check_permission( $c, $tradition );
485 my $stemma = $tradition->stemma( $stemmaid );
487 return _json_error( $c, 404, "Tradition $textid has no stemma ID $stemmaid" );
489 # Get the dot and transmute its line breaks to literal '|n'
490 $c->stash->{'result'} = { 'dot' => $stemma->editable( { linesep => '|n' } ) };
491 $c->forward('View::JSON');
496 POST /stemmaroot/$textid/$stemmaseq, { root: <root node ID> }
498 Orients the given stemma so that the given node is the root (archetype). Returns the
499 information structure for the new stemma.
503 sub stemmaroot :Local :Args(2) {
504 my( $self, $c, $textid, $stemmaid ) = @_;
505 my $m = $c->model('Directory');
506 my $tradition = $m->tradition( $textid );
507 unless( $tradition ) {
508 return _json_error( $c, 404, "No tradition with ID $textid" );
510 my $ok = _check_permission( $c, $tradition );
511 if( $ok eq 'full' ) {
512 my $stemma = $tradition->stemma( $stemmaid );
514 $stemma->root_graph( $c->req->param('root') );
515 $m->save( $tradition );
516 } catch( Text::Tradition::Error $e ) {
517 return _json_error( $c, 400, $e->message );
519 return _json_error( $c, 500, "Error re-rooting stemma: $@" );
521 $c->stash->{'result'} = _stemma_info( $stemma );
522 $c->forward('View::JSON');
524 return _json_error( $c, 403,
525 'You do not have permission to update stemmata for this tradition' );
531 GET /download/$textid
533 Returns the full XML definition of the tradition and its stemmata, if any.
537 sub download :Local :Args(1) {
538 my( $self, $c, $textid ) = @_;
539 my $tradition = $c->model('Directory')->tradition( $textid );
540 unless( $tradition ) {
541 return _json_error( $c, 404, "No tradition with ID $textid" );
543 my $ok = _check_permission( $c, $tradition );
546 $c->stash->{'result'} = $tradition->collation->as_graphml();
547 } catch( Text::Tradition::Error $e ) {
548 return _json_error( $c, 500, $e->message );
550 $c->forward('View::GraphML');
557 # Helper to check what permission, if any, the active user has for
558 # the given tradition
559 sub _check_permission {
560 my( $c, $tradition ) = @_;
561 my $user = $c->user_exists ? $c->user->get_object : undef;
563 return 'full' if ( $user->is_admin ||
564 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
566 # Text doesn't belong to us, so maybe it's public?
567 return 'readonly' if $tradition->public;
569 # ...nope. Forbidden!
570 return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
573 # Helper to throw a JSON exception
575 my( $c, $code, $errmsg ) = @_;
576 $c->response->status( $code );
577 $c->stash->{'result'} = { 'error' => $errmsg };
578 $c->forward('View::JSON');
583 return $_[0] ? JSON::true : JSON::false;
588 Standard 404 error page
593 my ( $self, $c ) = @_;
594 $c->response->body( 'Page not found' );
595 $c->response->status(404);
600 Attempt to render a view, if needed.
604 sub end : ActionClass('RenderView') {}
612 This library is free software. You can redistribute it and/or modify
613 it under the same terms as Perl itself.
617 __PACKAGE__->meta->make_immutable;