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