adding explicit dependencies on Text::Tradition
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Relation.pm
CommitLineData
b8a92065 1package stemmaweb::Controller::Relation;
2use Moose;
cc86fa11 3use Module::Load;
b8a92065 4use namespace::autoclean;
b28e606e 5use TryCatch;
b8a92065 6
7BEGIN { extends 'Catalyst::Controller' }
8
9
10=head1 NAME
11
12stemmaweb::Controller::Relation - Controller for the relationship mapper
13
14=head1 DESCRIPTION
15
b28e606e 16The reading relationship mapper with draggable nodes.
b8a92065 17
18=head1 METHODS
19
b28e606e 20=head2 index
21
b8a92065 22 GET relation/$textid
23
24Renders the application for the text identified by $textid.
25
b8a92065 26=cut
27
9529f69c 28sub index :Path :Args(0) {
29 my( $self, $c ) = @_;
b28e606e 30 $c->stash->{'template'} = 'relate.tt';
31}
32
9529f69c 33=head2 definitions
b28e606e 34
9c2e7b80 35 GET relation/definitions
b28e606e 36
37Returns a data structure giving the valid types and scopes for a relationship.
38
39=cut
40
9c2e7b80 41sub definitions :Local :Args(0) {
b28e606e 42 my( $self, $c ) = @_;
17b660e6 43 my $valid_relationships = [ qw/ spelling orthographic grammatical lexical transposition / ];
b28e606e 44 my $valid_scopes = [ qw/ local global / ];
45 $c->stash->{'result'} = { 'types' => $valid_relationships, 'scopes' => $valid_scopes };
46 $c->forward('View::JSON');
b8a92065 47}
48
9529f69c 49=head2 text
b28e606e 50
9529f69c 51 GET relation/$textid/
52
53 Runs the relationship mapper for the specified text ID.
54
b28e606e 55=cut
56
9529f69c 57sub text :Chained('/') :PathPart('relation') :CaptureArgs(1) {
58 my( $self, $c, $textid ) = @_;
13aa153c 59 # If the tradition has more than 500 ranks or so, split it up.
60 my $tradition = $c->model('Directory')->tradition( $textid );
7562a27b 61 # Account for a bad interaction between FastCGI and KiokuDB
62 unless( $tradition->collation->tradition ) {
63 $c->log->warn( "Fixing broken tradition link" );
64 $tradition->collation->_set_tradition( $tradition );
65 $c->model('Directory')->save( $tradition );
66 }
20198e59 67 # Check permissions. Will return 403 if denied, otherwise will
68 # put the appropriate value in the stash.
69 my $ok = _check_permission( $c, $tradition );
70 return unless $ok;
71
d58766c0 72 # See how big the tradition is. Edges are more important than nodes
73 # when it comes to rendering difficulty.
74 my $numnodes = scalar $tradition->collation->readings;
75 my $numedges = scalar $tradition->collation->paths;
13aa153c 76 my $length = $tradition->collation->end->rank;
d58766c0 77 # We should display no more than roughly 500 nodes, or roughly 700
78 # edges, at a time.
79 my $segments = $numnodes / 500;
80 if( $numedges / 700 > $segments ) {
81 $segments = $numedges / 700;
82 }
83 my $segsize = sprintf( "%.0f", $length / $segments );
84 my $margin = sprintf( "%.0f", $segsize / 10 );
85 if( $segments > 1 ) {
13aa153c 86 # Segment the tradition in order not to overload the browser.
13aa153c 87 my @divs;
88 my $r = 0;
d58766c0 89 while( $r + $margin < $length ) {
13aa153c 90 push( @divs, $r );
d58766c0 91 $r += $segsize;
13aa153c 92 }
93 $c->stash->{'textsegments'} = [];
d58766c0 94 $c->stash->{'segsize'} = $segsize;
95 $c->stash->{'margin'} = $margin;
ea8e8b3c 96 foreach my $i ( 0..$#divs ) {
97 my $seg = { 'start' => $divs[$i] };
98 $seg->{'display'} = "Segment " . ($i+1);
13aa153c 99 push( @{$c->stash->{'textsegments'}}, $seg );
100 }
101 }
102 $c->stash->{'textid'} = $textid;
103 $c->stash->{'tradition'} = $tradition;
9529f69c 104}
105
106sub main :Chained('text') :PathPart('') :Args(0) {
b28e606e 107 my( $self, $c ) = @_;
13aa153c 108 my $startseg = $c->req->param('start');
9c2e7b80 109 my $tradition = delete $c->stash->{'tradition'};
110 my $collation = $tradition->collation;
13aa153c 111 my $svgopts;
112 if( $startseg ) {
d58766c0 113 # Only render the subgraph from startseg to endseg or to END,
13aa153c 114 # whichever is less.
d58766c0 115 my $endseg = $startseg + $c->stash->{'segsize'} + $c->stash->{'margin'};
13aa153c 116 $svgopts = { 'from' => $startseg };
d58766c0 117 $svgopts->{'to'} = $endseg if $endseg < $collation->end->rank;
13aa153c 118 } elsif( exists $c->stash->{'textsegments'} ) {
119 # This is the unqualified load of a long tradition. We implicitly start
120 # at zero, but go only as far as 550.
d58766c0 121 my $endseg = $c->stash->{'segsize'} + $c->stash->{'margin'};
ea8e8b3c 122 $startseg = 0;
d58766c0 123 $svgopts = { 'to' => $endseg };
13aa153c 124 }
125 my $svg_str = $collation->as_svg( $svgopts );
9529f69c 126 $svg_str =~ s/\n//gs;
ea8e8b3c 127 $c->stash->{'startseg'} = $startseg if defined $startseg;
9529f69c 128 $c->stash->{'svg_string'} = $svg_str;
129 $c->stash->{'text_title'} = $tradition->name;
cc86fa11 130 $c->stash->{'text_lang'} = $tradition->language;
9529f69c 131 $c->stash->{'template'} = 'relate.tt';
b28e606e 132}
133
cc86fa11 134=head2 help
135
136 GET relation/help/$language
137
138Returns the help window HTML.
139
140=cut
141
142sub help :Local :Args(1) {
143 my( $self, $c, $lang ) = @_;
144 # Display the morphological help for the language if it is defined.
145 if( $lang && $lang ne 'Default' ) {
146 my $mod = 'Text::Tradition::Language::' . $lang;
147 try {
148 load( $mod );
149 } catch {
150 $c->log->debug("Warning: could not load $mod");
151 }
152 my $has_mod = $mod->can('morphology_tags');
cc86fa11 153 if( $has_mod ) {
154 my $tagset = &$has_mod;
155 $c->stash->{'tagset'} = $tagset;
156 }
157 }
158 $c->stash->{'template'} = 'relatehelp.tt';
159}
160
b28e606e 161=head2 relationships
162
13aa153c 163 GET relation/$textid/relationships
9529f69c 164
165Returns the list of relationships defined for this text.
b28e606e 166
13aa153c 167 POST relation/$textid/relationships { request }
9529f69c 168
169Attempts to define the requested relationship within the text. Returns 200 on
170success or 403 on error.
b28e606e 171
13aa153c 172 DELETE relation/$textid/relationships { request }
9529f69c 173
b28e606e 174
175=cut
176
9529f69c 177sub relationships :Chained('text') :PathPart :Args(0) {
b28e606e 178 my( $self, $c ) = @_;
6d124a83 179 my $tradition = delete $c->stash->{'tradition'};
20198e59 180 my $ok = _check_permission( $c, $tradition );
181 return unless $ok;
6d124a83 182 my $collation = $tradition->collation;
cdd592f3 183 my $m = $c->model('Directory');
9529f69c 184 if( $c->request->method eq 'GET' ) {
185 my @pairs = $collation->relationships; # returns the edges
186 my @all_relations;
187 foreach my $p ( @pairs ) {
188 my $relobj = $collation->relations->get_relationship( @$p );
545163a2 189 next if $relobj->type eq 'collated'; # Don't show these
7562a27b 190 next if $p->[0] eq $p->[1]; # HACK until bugfix
69a19c91 191 my $relhash = { source => $p->[0], target => $p->[1],
192 type => $relobj->type, scope => $relobj->scope };
193 $relhash->{'note'} = $relobj->annotation if $relobj->has_annotation;
194 push( @all_relations, $relhash );
9529f69c 195 }
196 $c->stash->{'result'} = \@all_relations;
20198e59 197 } else {
198 # Check write permissions first of all
199 if( $c->stash->{'permission'} ne 'full' ) {
9529f69c 200 $c->response->status( '403' );
20198e59 201 $c->stash->{'result'} = {
202 'error' => 'You do not have permission to view this tradition.' };
203 } elsif( $c->request->method eq 'POST' ) {
204 unless( $c->stash->{'permission'} eq 'full' ) {
205 $c->response->status( '403' );
206 $c->stash->{'result'} = {
207 'error' => 'You do not have permission to view this tradition.' };
208 $c->detach( 'View::JSON' );
209 }
210 my $node = $c->request->param('source_id');
211 my $target = $c->request->param('target_id');
212 my $relation = $c->request->param('rel_type');
213 my $note = $c->request->param('note');
214 my $scope = $c->request->param('scope');
215
216 my $opts = { 'type' => $relation,
217 'scope' => $scope };
218 $opts->{'annotation'} = $note if $note;
219
220 try {
221 my @vectors = $collation->add_relationship( $node, $target, $opts );
222 $c->stash->{'result'} = \@vectors;
223 $m->save( $tradition );
224 } catch( Text::Tradition::Error $e ) {
225 $c->response->status( '403' );
226 $c->stash->{'result'} = { 'error' => $e->message };
227 }
228 } elsif( $c->request->method eq 'DELETE' ) {
229 my $node = $c->request->param('source_id');
230 my $target = $c->request->param('target_id');
231
232 try {
233 my @vectors = $collation->del_relationship( $node, $target );
234 $m->save( $tradition );
235 $c->stash->{'result'} = \@vectors;
236 } catch( Text::Tradition::Error $e ) {
237 $c->response->status( '403' );
238 $c->stash->{'result'} = { 'error' => $e->message };
239 }
9529f69c 240 }
b28e606e 241 }
b28e606e 242 $c->forward('View::JSON');
5f15640c 243}
244
245=head2 readings
246
247 GET relation/$textid/readings
248
249Returns the list of readings defined for this text along with their metadata.
250
251=cut
252
0dcdd5ec 253my %read_write_keys = (
254 'id' => 0,
255 'text' => 0,
256 'is_meta' => 0,
257 'grammar_invalid' => 1,
258 'is_nonsense' => 1,
259 'normal_form' => 1,
260);
261
5f15640c 262sub _reading_struct {
263 my( $reading ) = @_;
264 # Return a JSONable struct of the useful keys. Keys meant to be writable
265 # have a true value; read-only keys have a false value.
5f15640c 266 my $struct = {};
267 map { $struct->{$_} = $reading->$_ } keys( %read_write_keys );
268 # Special case
269 $struct->{'lexemes'} = [ $reading->lexemes ];
0dcdd5ec 270 # Look up any words related via spelling or orthography
271 my $sameword = sub {
272 my $t = $_[0]->type;
273 return $t eq 'spelling' || $t eq 'orthographic';
274 };
275 my @variants;
276 foreach my $sr ( $reading->related_readings( $sameword ) ) {
277 push( @variants, $sr->text );
278 }
279 $struct->{'variants'} = \@variants;
5f15640c 280 return $struct;
281}
282
283sub readings :Chained('text') :PathPart :Args(0) {
284 my( $self, $c ) = @_;
285 my $tradition = delete $c->stash->{'tradition'};
20198e59 286 my $ok = _check_permission( $c, $tradition );
287 return unless $ok;
5f15640c 288 my $collation = $tradition->collation;
289 my $m = $c->model('Directory');
290 if( $c->request->method eq 'GET' ) {
291 my $rdginfo = {};
292 foreach my $rdg ( $collation->readings ) {
293 $rdginfo->{$rdg->id} = _reading_struct( $rdg );
294 }
295 $c->stash->{'result'} = $rdginfo;
296 }
297 $c->forward('View::JSON');
298}
299
300=head2 reading
301
302 GET relation/$textid/reading/$id
303
304Returns the list of readings defined for this text along with their metadata.
305
306 POST relation/$textid/reading/$id { request }
307
308Alters the reading according to the values in request. Returns 403 Forbidden if
309the alteration isn't allowed.
310
311=cut
312
313sub reading :Chained('text') :PathPart :Args(1) {
314 my( $self, $c, $reading_id ) = @_;
315 my $tradition = delete $c->stash->{'tradition'};
316 my $collation = $tradition->collation;
0dcdd5ec 317 my $rdg = $collation->reading( $reading_id );
5f15640c 318 my $m = $c->model('Directory');
319 if( $c->request->method eq 'GET' ) {
5f15640c 320 $c->stash->{'result'} = $rdg ? _reading_struct( $rdg )
321 : { 'error' => "No reading with ID $reading_id" };
322 } elsif ( $c->request->method eq 'POST' ) {
20198e59 323 if( $c->stash->{'permission'} ne 'full' ) {
324 $c->response->status( '403' );
325 $c->stash->{'result'} = {
326 'error' => 'You do not have permission to view this tradition.' };
327 $c->detach('View::JSON');
328 }
6666d111 329 my $errmsg;
0dcdd5ec 330 # Are we re-lemmatizing?
331 if( $c->request->param('relemmatize') ) {
332 my $nf = $c->request->param('normal_form');
333 # TODO throw error unless $nf
334 $rdg->normal_form( $nf );
997ebe92 335 # TODO throw error if lemmatization fails
6666d111 336 # TODO skip this if normal form hasn't changed
0dcdd5ec 337 $rdg->lemmatize();
338 } else {
339 # Set all the values that we have for the reading.
340 # TODO error handling
341 foreach my $p ( keys %{$c->request->params} ) {
342 if( $p =~ /^morphology_(\d+)$/ ) {
343 # Set the form on the correct lexeme
aafcb75b 344 my $morphval = $c->request->param( $p );
345 next unless $morphval;
0dcdd5ec 346 my $midx = $1;
0dcdd5ec 347 my $lx = $rdg->lexeme( $midx );
aafcb75b 348 my $strrep = $rdg->language . ' // ' . $morphval;
0dcdd5ec 349 my $idx = $lx->has_form( $strrep );
350 unless( defined $idx ) {
351 # Make the word form and add it to the lexeme.
6666d111 352 try {
353 $idx = $lx->add_matching_form( $strrep ) - 1;
354 } catch( Text::Tradition::Error $e ) {
355 $c->response->status( '403' );
356 $errmsg = $e->message;
465848bc 357 } catch {
358 # Something else went wrong, probably a Moose error
359 $c->response->status( '403' );
360 $errmsg = 'Something went wrong with the request';
6666d111 361 }
0dcdd5ec 362 }
6666d111 363 $lx->disambiguate( $idx ) if defined $idx;
0dcdd5ec 364 } elsif( $read_write_keys{$p} ) {
997ebe92 365 my $val = _clean_booleans( $rdg, $p, $c->request->param( $p ) );
366 $rdg->$p( $val );
0dcdd5ec 367 }
368 }
369 }
19f0f822 370 $m->save( $rdg );
6666d111 371 $c->stash->{'result'} = $errmsg ? { 'error' => $errmsg }
372 : _reading_struct( $rdg );
0dcdd5ec 373
5f15640c 374 }
375 $c->forward('View::JSON');
376
377}
b28e606e 378
20198e59 379sub _check_permission {
380 my( $c, $tradition ) = @_;
381 my $user = $c->user_exists ? $c->user->get_object : undef;
b0524272 382 # Does this user have access?
20198e59 383 if( $user ) {
b0524272 384 if( $user->is_admin ||
385 ( $tradition->has_user && $tradition->user->id eq $user->id ) ) {
386 $c->stash->{'permission'} = 'full';
387 return 1;
388 }
080f8a02 389 }
390 # Is it public?
391 if( $tradition->public ) {
20198e59 392 $c->stash->{'permission'} = 'readonly';
393 return 1;
080f8a02 394 }
395 # Forbidden!
396 $c->response->status( 403 );
397 $c->response->body( 'You do not have permission to view this tradition.' );
398 $c->detach( 'View::Plain' );
399 return 0;
20198e59 400}
401
997ebe92 402sub _clean_booleans {
403 my( $rdg, $param, $val ) = @_;
404 if( $rdg->meta->get_attribute( $param )->type_constraint->name eq 'Bool' ) {
405 $val = 1 if $val eq 'true';
406 $val = undef if $val eq 'false';
407 }
408 return $val;
409}
410
b8a92065 411=head2 end
412
413Attempt to render a view, if needed.
414
415=cut
416
417sub end : ActionClass('RenderView') {}
418
419=head1 AUTHOR
420
421Tara L Andrews
422
423=head1 LICENSE
424
425This library is free software. You can redistribute it and/or modify
426it under the same terms as Perl itself.
427
428=cut
429
430__PACKAGE__->meta->make_immutable;
431
4321;