check for language module in root before relying on it
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Root.pm
CommitLineData
b8a92065 1package stemmaweb::Controller::Root;
2use Moose;
3use namespace::autoclean;
4use Text::Tradition::Analysis qw/ run_analysis /;
41279a86 5use TryCatch;
b8a92065 6
7
8BEGIN { 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
18stemmaweb::Controller::Root - Root Controller for stemmaweb
19
20=head1 DESCRIPTION
21
22Serves up the main container pages.
23
24=head1 URLs
25
26=head2 index
27
28The root page (/). Serves the main container page, from which the various
29components will be loaded.
30
31=cut
32
33sub index :Path :Args(0) {
34 my ( $self, $c ) = @_;
35
c655153c 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 }
b8a92065 40 $c->stash->{template} = 'index.tt';
41}
42
3f9d7ae5 43=head2 about
44
45A general overview/documentation page for the site.
46
47=cut
48
49sub about :Local :Args(0) {
50 my( $self, $c ) = @_;
51 $c->stash->{template} = 'about.tt';
52}
53
b8a92065 54=head1 Elements of index page
55
56=head2 directory
57
58 GET /directory
59
70ccaf75 60Serves 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.
b8a92065 61
62=cut
70ccaf75 63
b8a92065 64sub directory :Local :Args(0) {
65 my( $self, $c ) = @_;
66 my $m = $c->model('Directory');
69799996 67 # Is someone logged in?
98a45925 68 my %usertexts;
69799996 69 if( $c->user_exists ) {
70 my $user = $c->user->get_object;
98a45925 71 my @list = $m->traditionlist( $user );
72 map { $usertexts{$_->{id}} = 1 } @list;
73 $c->stash->{usertexts} = \@list;
69799996 74 $c->stash->{is_admin} = 1 if $user->is_admin;
75 }
98a45925 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;
b8a92065 81 $c->stash->{template} = 'directory.tt';
82}
83
75354c3a 84=head1 AJAX methods for traditions and their properties
fb6e49b3 85
75354c3a 86=head2 newtradition
87
88 POST /newtradition,
89 { name: <name>,
90 language: <language>,
91 public: <is_public>,
2ece58b3 92 file: <fileupload> }
fb6e49b3 93
75354c3a 94Creates a new tradition belonging to the logged-in user, with the given name
95and the collation given in the uploaded file. The file type is indicated via
96the filename extension (.csv, .txt, .xls, .xlsx, .xml). Returns the ID and
97name of the new tradition.
98
99=cut
100
101sub 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).
2ece58b3 109 my $upload = $c->request->upload('file');
75354c3a 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;
2ece58b3 113 my( $ext ) = $upload->filename =~ /\.(\w+)$/;
75354c3a 114 my %newopts = (
115 'name' => $name,
116 'language' => $lang,
117 'public' => $public,
2ece58b3 118 'file' => $upload->tempname
75354c3a 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 }
699ab7ea 133 if( $tradition ) {
134 $errmsg = undef;
135 last;
136 }
75354c3a 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
2bfac197 158 return _json_error( $c, 403, "Unrecognized file type extension $ext" );
75354c3a 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
186Returns information about a particular text.
fb6e49b3 187
188=cut
189
75354c3a 190sub textinfo :Local :Args(1) {
fb6e49b3 191 my( $self, $c, $textid ) = @_;
98a45925 192 my $tradition = $c->model('Directory')->tradition( $textid );
6978962f 193 ## Have to keep users in the same scope as tradition
194 my $newuser;
195 my $olduser;
75354c3a 196 unless( $tradition ) {
2bfac197 197 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 198 }
41279a86 199 my $ok = _check_permission( $c, $tradition );
200 return unless $ok;
75354c3a 201 if( $c->req->method eq 'POST' ) {
202 return _json_error( $c, 403,
203 'You do not have permission to update this tradition' )
204 unless $ok eq 'full';
205 my $params = $c->request->parameters;
206 # Handle changes to owner-accessible parameters
207 my $m = $c->model('Directory');
208 my $changed;
ce1c5863 209 # Handle name param - easy
210 if( exists $params->{name} ) {
211 my $newname = delete $params->{name};
212 unless( $tradition->name eq $newname ) {
213 try {
214 $tradition->name( $newname );
75354c3a 215 $changed = 1;
ce1c5863 216 } catch {
217 return _json_error( $c, 500, "Error setting name to $newname" );
75354c3a 218 }
219 }
220 }
ce1c5863 221 # Handle language param, making Default => null
222 my $langval = delete $params->{language} || 'Default';
ed2aaedb 223
224 unless( $tradition->language eq $langval || !$tradition->can('language') ) {
ce1c5863 225 try {
226 $tradition->language( $langval );
227 $changed = 1;
228 } catch {
229 return _json_error( $c, 500, "Error setting language to $langval" );
230 }
231 }
232
75354c3a 233 # Handle our boolean
ce1c5863 234 my $ispublic = $tradition->public;
75354c3a 235 if( delete $params->{'public'} ) { # if it's any true value...
236 $tradition->public( 1 );
ce1c5863 237 $changed = 1 unless $ispublic;
238 } else { # the checkbox was unchecked, ergo it should not be public
239 $tradition->public( 0 );
240 $changed = 1 if $ispublic;
75354c3a 241 }
ce1c5863 242
243 # Handle ownership change
75354c3a 244 if( exists $params->{'owner'} ) {
245 # Only admins can update user / owner
246 my $newownerid = delete $params->{'owner'};
4f849eea 247 unless( !$newownerid ||
6978962f 248 ( $tradition->has_user && $tradition->user->email eq $newownerid ) ) {
75354c3a 249 unless( $c->user->get_object->is_admin ) {
250 return _json_error( $c, 403,
251 "Only admin users can change tradition ownership" );
252 }
6978962f 253 $newuser = $m->find_user({ email => $newownerid });
75354c3a 254 unless( $newuser ) {
ce1c5863 255 return _json_error( $c, 500, "No such user " . $newownerid );
75354c3a 256 }
6978962f 257 if( $tradition->has_user ) {
258 $olduser = $tradition->user;
259 $olduser->remove_tradition( $tradition );
260 }
75354c3a 261 $newuser->add_tradition( $tradition );
262 $changed = 1;
263 }
264 }
265 # TODO check for rogue parameters
266 if( scalar keys %$params ) {
267 my $rogueparams = join( ', ', keys %$params );
268 return _json_error( $c, 403, "Request parameters $rogueparams not recognized" );
269 }
270 # If we safely got to the end, then write to the database.
271 $m->save( $tradition ) if $changed;
272 $m->save( $newuser ) if $newuser;
273 }
41279a86 274
75354c3a 275 # Now return the current textinfo, whether GET or successful POST.
276 my $textinfo = {
277 textid => $textid,
278 name => $tradition->name,
ed2aaedb 279 #language => $tradition->language,
e0b90236 280 public => $tradition->public || 0,
2ece58b3 281 owner => $tradition->user ? $tradition->user->email : undef,
75354c3a 282 witnesses => [ map { $_->sigil } $tradition->witnesses ],
283 };
ed2aaedb 284 if( $tradition->can('language') ) {
285 $textinfo->{'language'} = $tradition->language;
286 }
2923ebb1 287 my @stemmasvg = map { $_->as_svg() } $tradition->stemmata;
75354c3a 288 map { $_ =~ s/\n/ /mg } @stemmasvg;
289 $textinfo->{stemmata} = \@stemmasvg;
290 $c->stash->{'result'} = $textinfo;
291 $c->forward('View::JSON');
fb6e49b3 292}
b8a92065 293
75354c3a 294=head2 variantgraph
b8a92065 295
75354c3a 296 GET /variantgraph/$textid
297
298Returns the variant graph for the text specified at $textid, in SVG form.
b8a92065 299
300=cut
301
75354c3a 302sub variantgraph :Local :Args(1) {
b8a92065 303 my( $self, $c, $textid ) = @_;
98a45925 304 my $tradition = $c->model('Directory')->tradition( $textid );
75354c3a 305 unless( $tradition ) {
2bfac197 306 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 307 }
41279a86 308 my $ok = _check_permission( $c, $tradition );
309 return unless $ok;
310
98a45925 311 my $collation = $tradition->collation;
75354c3a 312 $c->stash->{'result'} = $collation->as_svg;
313 $c->forward('View::SVG');
b8a92065 314}
75354c3a 315
b8a92065 316=head2 stemma
317
75354c3a 318 GET /stemma/$textid/$stemmaseq
319 POST /stemma/$textid/$stemmaseq, { 'dot' => $dot_string }
b8a92065 320
75354c3a 321Returns an SVG representation of the given stemma hypothesis for the text.
322If the URL is called with POST, the stemma at $stemmaseq will be altered
323to reflect the definition in $dot_string. If $stemmaseq is 'n', a new
324stemma will be added.
b8a92065 325
326=cut
327
75354c3a 328sub stemma :Local :Args(2) {
41279a86 329 my( $self, $c, $textid, $stemmaid ) = @_;
b8a92065 330 my $m = $c->model('Directory');
331 my $tradition = $m->tradition( $textid );
75354c3a 332 unless( $tradition ) {
2bfac197 333 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 334 }
41279a86 335 my $ok = _check_permission( $c, $tradition );
336 return unless $ok;
337
41279a86 338 $c->stash->{'result'} = '';
75354c3a 339 my $stemma;
340 if( $c->req->method eq 'POST' ) {
341 if( $ok eq 'full' ) {
41279a86 342 my $dot = $c->request->body_params->{'dot'};
75354c3a 343 try {
344 if( $stemmaid eq 'n' ) {
345 # We are adding a new stemma.
3f7346b1 346 $stemmaid = $tradition->stemma_count;
75354c3a 347 $stemma = $tradition->add_stemma( 'dot' => $dot );
2bfac197 348 } elsif( $stemmaid !~ /^\d+$/ ) {
349 return _json_error( $c, 403, "Invalid stemma ID specification $stemmaid" );
75354c3a 350 } elsif( $stemmaid < $tradition->stemma_count ) {
351 # We are updating an existing stemma.
352 $stemma = $tradition->stemma( $stemmaid );
353 $stemma->alter_graph( $dot );
354 } else {
355 # Unrecognized stemma ID
2bfac197 356 return _json_error( $c, 404, "No stemma at index $stemmaid, cannot update" );
75354c3a 357 }
358 } catch ( Text::Tradition::Error $e ) {
359 return _json_error( $c, 500, $e->message );
360 }
41279a86 361 $m->store( $tradition );
75354c3a 362 } else {
363 # No permissions to update the stemma
364 return _json_error( $c, 403,
365 'You do not have permission to update stemmata for this tradition' );
41279a86 366 }
b8a92065 367 }
75354c3a 368
369 # For a GET or a successful POST request, return the SVG representation
370 # of the stemma in question, if any.
75354c3a 371 if( !$stemma && $tradition->stemma_count > $stemmaid ) {
372 $stemma = $tradition->stemma( $stemmaid );
373 }
2923ebb1 374 my $stemma_xml = $stemma ? $stemma->as_svg() : '';
ce1c5863 375 # What was requested, XML or JSON?
376 my $return_view = 'SVG';
377 if( my $accept_header = $c->req->header('Accept') ) {
378 $c->log->debug( "Received Accept header: $accept_header" );
379 foreach my $type ( split( /,\s*/, $accept_header ) ) {
380 # If we were first asked for XML, return SVG
381 last if $type =~ /^(application|text)\/xml$/;
382 # If we were first asked for JSON, return JSON
383 if( $type eq 'application/json' ) {
384 $return_view = 'JSON';
385 last;
386 }
387 }
388 }
389 if( $return_view eq 'SVG' ) {
390 $c->stash->{'result'} = $stemma_xml;
391 $c->forward('View::SVG');
392 } else { # JSON
393 $stemma_xml =~ s/\n/ /mg;
394 $c->stash->{'result'} = { 'stemmaid' => $stemmaid, 'stemmasvg' => $stemma_xml };
395 $c->forward('View::JSON');
396 }
b8a92065 397}
398
399=head2 stemmadot
400
75354c3a 401 GET /stemmadot/$textid/$stemmaseq
b8a92065 402
403Returns the 'dot' format representation of the current stemma hypothesis.
404
405=cut
406
75354c3a 407sub stemmadot :Local :Args(2) {
408 my( $self, $c, $textid, $stemmaid ) = @_;
b8a92065 409 my $m = $c->model('Directory');
410 my $tradition = $m->tradition( $textid );
75354c3a 411 unless( $tradition ) {
2bfac197 412 return _json_error( $c, 404, "No tradition with ID $textid" );
75354c3a 413 }
41279a86 414 my $ok = _check_permission( $c, $tradition );
415 return unless $ok;
75354c3a 416 my $stemma = $tradition->stemma( $stemmaid );
417 unless( $stemma ) {
2bfac197 418 return _json_error( $c, 404, "Tradition $textid has no stemma ID $stemmaid" );
75354c3a 419 }
420 # Get the dot and transmute its line breaks to literal '|n'
421 $c->stash->{'result'} = { 'dot' => $stemma->editable( { linesep => '|n' } ) };
41279a86 422 $c->forward('View::JSON');
423}
424
75354c3a 425####################
426### Helper functions
427####################
41279a86 428
75354c3a 429# Helper to check what permission, if any, the active user has for
430# the given tradition
41279a86 431sub _check_permission {
432 my( $c, $tradition ) = @_;
433 my $user = $c->user_exists ? $c->user->get_object : undef;
434 if( $user ) {
929ba7c8 435 return 'full' if ( $user->is_admin ||
436 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
080f8a02 437 }
438 # Text doesn't belong to us, so maybe it's public?
439 return 'readonly' if $tradition->public;
440
441 # ...nope. Forbidden!
75354c3a 442 return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
443}
444
445# Helper to throw a JSON exception
446sub _json_error {
447 my( $c, $code, $errmsg ) = @_;
448 $c->response->status( $code );
449 $c->stash->{'result'} = { 'error' => $errmsg };
450 $c->forward('View::JSON');
929ba7c8 451 return 0;
41279a86 452}
453
b8a92065 454=head2 default
455
456Standard 404 error page
457
458=cut
459
460sub default :Path {
461 my ( $self, $c ) = @_;
462 $c->response->body( 'Page not found' );
463 $c->response->status(404);
464}
465
466=head2 end
467
468Attempt to render a view, if needed.
469
470=cut
471
472sub end : ActionClass('RenderView') {}
473
474=head1 AUTHOR
475
476Tara L Andrews
477
478=head1 LICENSE
479
480This library is free software. You can redistribute it and/or modify
481it under the same terms as Perl itself.
482
483=cut
484
485__PACKAGE__->meta->make_immutable;
486
4871;