1 package Text::Tradition::Directory;
7 use Encode qw/ decode_utf8 /;
8 use KiokuDB::GC::Naive;
10 use KiokuDB::TypeMap::Entry::Naive;
12 use Text::Tradition::Error;
15 use KiokuX::User::Util qw(crypt_password);
16 use Text::Tradition::Store;
17 use Text::Tradition::User;
18 use Text::Tradition::TypeMap::Entry;
20 extends 'KiokuX::Model';
22 use vars qw/ $VERSION /;
27 Text::Tradition::Directory - a KiokuDB interface for storing and retrieving
28 traditions and their owners
32 use Text::Tradition::Directory;
33 my $d = Text::Tradition::Directory->new(
34 'dsn' => 'dbi:SQLite:mytraditions.db',
35 'extra_args' => { 'create' => 1 },
38 my $tradition = Text::Tradition->new( @args );
39 my $stemma = $tradition->add_stemma( dotfile => $dotfile ); # if Analysis module installed
40 $d->save_tradition( $tradition );
42 foreach my $id ( $d->traditions ) {
43 print $d->tradition( $id )->name;
47 my $userstore = Text::Tradition::UserStore->new(dsn => 'dbi:SQLite:foo.db');
48 my $newuser = $userstore->add_user({ username => 'fred',
49 password => 'somepassword' });
51 my $fetchuser = $userstore->find_user({ username => 'fred' });
52 if($fetchuser->check_password('somepassword')) {
53 ## login user or .. whatever
56 my $user = $userstore->deactivate_user({ username => 'fred' });
58 ## shouldnt be able to login etc
63 Text::Tradition::Directory is an interface for storing and retrieving text
64 traditions and all their data, including an associated stemma hypothesis
65 and a user who has ownership rights to the tradition data. It is an
66 instantiation of a KiokuDB::Model, storing traditions and associated
69 The Text::Tradition::Directory package also includes the
70 L<Text::Tradition::User> class for user objects, and the
71 L<Text::Tradition::Ownership> role which extends the Text::Tradition class
72 to handle user ownership.
78 Constant for the minimum password length when validating passwords,
83 has MIN_PASS_LEN => ( is => 'ro', isa => 'Num', default => sub { 8 } );
89 Returns a Directory object.
93 Returns a hashref mapping of ID => name for all traditions in the directory.
95 =head2 tradition( $id )
97 Returns the Text::Tradition object of the given ID.
99 =head2 save( $tradition )
101 Writes the given tradition to the database, returning its ID.
103 =head2 delete( $tradition )
105 Deletes the given tradition object from the database.
106 WARNING!! Garbage collection does not yet work. Use this sparingly.
114 use_ok 'Text::Tradition::Directory';
116 my $fh = File::Temp->new();
117 my $file = $fh->filename;
119 my $dsn = "dbi:SQLite:dbname=$file";
121 my $user = 'user@example.org';
122 my $t = Text::Tradition->new(
124 'input' => 'Tabular',
125 'file' => 't/data/simple.txt',
127 my $stemma_enabled = $t->can( 'add_stemma' );
130 my $d = Text::Tradition::Directory->new( 'dsn' => $dsn,
131 'extra_args' => { 'create' => 1 } );
132 ok( $d->$_isa('Text::Tradition::Directory'), "Got directory object" );
134 my $scope = $d->new_scope;
135 $uuid = $d->save( $t );
136 ok( $uuid, "Saved test tradition" );
139 my $user = $d->add_user({ username => $user, password => 'UserPass' });
140 $user->add_tradition( $t );
142 is( $t->user, $user, "Assigned tradition to test user" );
145 skip "Analysis package not installed", 5 unless $stemma_enabled;
146 my $s = $t->add_stemma( dotfile => 't/data/simple.dot' );
147 ok( $d->save( $t ), "Updated tradition with stemma" );
148 is( $d->tradition( $uuid ), $t, "Correct tradition returned for id" );
149 is( $d->tradition( $uuid )->stemma(0), $s, "...and it has the correct stemma" );
152 } catch( Text::Tradition::Error $e ) {
153 is( $e->ident, 'database error', "Got exception trying to save stemma directly" );
154 like( $e->message, qr/Cannot directly save non-Tradition object/,
155 "Exception has correct message" );
159 my $nt = Text::Tradition->new(
161 'input' => 'CollateX',
162 'file' => 't/data/Collatex-16.xml',
164 ok( $nt->$_isa('Text::Tradition'), "Made new tradition" );
167 my $f = Text::Tradition::Directory->new( 'dsn' => $dsn );
168 my $scope = $f->new_scope;
169 is( scalar $f->traditionlist, 1, "Directory index has our tradition" );
170 my $nuuid = $f->save( $nt );
171 ok( $nuuid, "Stored second tradition" );
172 my @tlist = $f->traditionlist;
173 is( scalar @tlist, 2, "Directory index has both traditions" );
174 my $tf = $f->tradition( $uuid );
175 my( $tlobj ) = grep { $_->{'id'} eq $uuid } @tlist;
176 is( $tlobj->{'name'}, $tf->name, "Directory index has correct tradition name" );
177 is( $tf->name, $t->name, "Retrieved the tradition from a new directory" );
180 skip "Analysis package not installed", 4 unless $stemma_enabled;
181 $sid = $f->object_to_id( $tf->stemma(0) );
183 $f->tradition( $sid );
184 } catch( Text::Tradition::Error $e ) {
185 is( $e->ident, 'database error', "Got exception trying to fetch stemma directly" );
186 like( $e->message, qr/not a Text::Tradition/, "Exception has correct message" );
190 } catch( Text::Tradition::Error $e ) {
191 is( $e->ident, 'database error', "Got exception trying to delete stemma directly" );
192 like( $e->message, qr/Cannot directly delete non-Tradition object/,
193 "Exception has correct message" );
198 ok( !$f->exists( $uuid ), "Object is deleted from DB" );
199 ok( !$f->exists( $sid ), "Object stemma also deleted from DB" ) if $stemma_enabled;
200 is( scalar $f->traditionlist, 1, "Object is deleted from index" );
204 my $g = Text::Tradition::Directory->new( 'dsn' => $dsn );
205 my $scope = $g->new_scope;
206 is( scalar $g->traditionlist, 1, "Now one object in new directory index" );
207 my $ntobj = $g->tradition( 'CX' );
208 my @w1 = sort { $a->sigil cmp $b->sigil } $ntobj->witnesses;
209 my @w2 = sort{ $a->sigil cmp $b->sigil } $nt->witnesses;
210 is_deeply( \@w1, \@w2, "Looked up remaining tradition by name" );
216 use Text::Tradition::TypeMap::Entry;
220 isa => 'KiokuDB::TypeMap',
222 KiokuDB::TypeMap->new(
224 # now that we fall back to YAML deflation, all attributes of
225 # Text::Tradition will be serialized to YAML as individual objects
226 # Except if we declare a specific entry type here
228 KiokuDB::TypeMap::Entry::MOP->new(),
229 # We need users to be naive entries so that they hold
230 # references to the original tradition objects, not clones
231 "Text::Tradition::User" =>
232 KiokuDB::TypeMap::Entry::MOP->new(),
233 "Text::Tradition::Collation" =>
234 KiokuDB::TypeMap::Entry::MOP->new(),
235 "Text::Tradition::Witness" =>
236 KiokuDB::TypeMap::Entry::MOP->new(),
237 "Graph" => Text::Tradition::TypeMap::Entry->new(),
238 "Set::Scalar" => Text::Tradition::TypeMap::Entry->new(),
244 # Push some columns into the extra_args
245 around BUILDARGS => sub {
255 if( $args->{'dsn'} =~ /^dbi/ ) { # We're using Backend::DBI
256 @column_args = ( 'columns',
257 [ 'name' => { 'data_type' => 'varchar', 'is_nullable' => 1 },
258 'public' => { 'data_type' => 'bool', 'is_nullable' => 1 } ] );
260 my $ea = $args->{'extra_args'};
261 if( ref( $ea ) eq 'ARRAY' ) {
262 push( @$ea, @column_args );
263 } elsif( ref( $ea ) eq 'HASH' ) {
264 $ea = { %$ea, @column_args };
266 $ea = { @column_args };
268 $args->{'extra_args'} = $ea;
270 return $class->$orig( $args );
273 override _build_directory => sub {
275 Text::Tradition::Store->connect(@{ $self->_connect_args },
276 resolver_constructor => sub {
278 $class->new({ typemap => $self->directory->merged_typemap,
279 fallback_entry => Text::Tradition::TypeMap::Entry->new() });
283 ## These checks don't cover store($id, $obj)
284 # before [ qw/ store update insert delete / ] => sub {
285 before [ qw/ delete / ] => sub {
288 foreach my $obj ( @_ ) {
289 if( ref( $obj ) && !$obj->$_isa( 'Text::Tradition' )
290 && !$obj->$_isa('Text::Tradition::User') ) {
291 # Is it an id => Tradition hash?
292 if( ref( $obj ) eq 'HASH' && keys( %$obj ) == 1 ) {
293 my( $k ) = keys %$obj;
294 next if $obj->{$k}->$_isa('Text::Tradition');
296 push( @nontrad, $obj );
300 throw( "Cannot directly save non-Tradition object of type "
301 . ref( $nontrad[0] ) );
305 # TODO Garbage collection doesn't work. Suck it up and live with the
307 after delete => sub {
309 my $gc = KiokuDB::GC::Naive->new( backend => $self->directory->backend );
310 $self->directory->backend->delete( $gc->garbage->members );
315 return $self->store( @_ );
319 my( $self, $id ) = @_;
320 my $obj = $self->lookup( $id );
322 # Try looking up by name.
323 foreach my $item ( $self->traditionlist ) {
324 if( $item->{'name'} eq $id ) {
325 $obj = $self->lookup( $item->{'id'} );
330 if( $obj && !$obj->$_isa('Text::Tradition') ) {
331 throw( "Retrieved object is a " . ref( $obj ) . ", not a Text::Tradition" );
340 return $self->user_traditionlist($user) if($user);
343 # If we are using DBI, we can do it the easy way; if not, the hard way.
344 # Easy way still involves making a separate DBI connection. Ew.
345 if( $self->dsn =~ /^dbi:(\w+):/ ) {
347 my @connection = @{$self->directory->backend->connect_info};
348 # Get rid of KiokuDB-specific arg
349 pop @connection if scalar @connection > 4;
350 $connection[3]->{'sqlite_unicode'} = 1 if $dbtype eq 'SQLite';
351 $connection[3]->{'pg_enable_utf8'} = 1 if $dbtype eq 'Pg';
352 my $dbh = DBI->connect( @connection );
353 my $q = $dbh->prepare( 'SELECT id, name, public from entries WHERE class = "Text::Tradition"' );
355 while( my @row = $q->fetchrow_array ) {
356 my( $id, $name ) = @row;
357 # Horrible horrible hack
358 $name = decode_utf8( $name ) if $dbtype eq 'mysql';
359 push( @tlist, { 'id' => $row[0], 'name' => $row[1], 'public' => $row[2] } );
362 $self->scan( sub { my $o = shift;
363 push( @tlist, { 'id' => $self->object_to_id( $o ),
365 'public' => $o->public } ) } );
371 Text::Tradition::Error->throw(
372 'ident' => 'database error',
378 # has 'directory' => (
380 # isa => 'KiokuX::Model',
384 ## TODO: Some of these methods should probably optionally take $user objects
385 ## instead of hashrefs.
387 ## It also occurs to me that all these methods don't need to be named
388 ## XX_user, but leaving that way for now incase we merge this code
389 ## into ::Directory for one-store.
391 =head1 USER DIRECTORY METHODS
393 =head2 add_user( $userinfo )
395 Takes a hashref of C<username>, C<password>.
397 Create a new user object, store in the KiokuDB backend, and return it.
402 my ($self, $userinfo) = @_;
404 my $username = $userinfo->{username};
405 my $password = $userinfo->{password};
406 my $role = $userinfo->{role} || 'user';
408 throw( "No username given" ) unless $username;
409 throw( "Invalid password - must be at least " . $self->MIN_PASS_LEN
410 . " characters long" )
411 unless ( $self->validate_password($password) || $username =~ /^https?:/ );
413 my $user = Text::Tradition::User->new(
415 password => ($password ? crypt_password($password) : ''),
416 email => ($userinfo->{email} ? $userinfo->{email} : $username),
420 $self->store($user->kiokudb_object_id, $user);
425 =head2 create_user( $userinfo )
427 Takes a hashref that can either be suitable for add_user (see above) or be
428 a hash of OpenID user information from Credential::OpenID.
433 my ($self, $userinfo) = @_;
435 ## No username means probably an OpenID based user
436 if(!exists $userinfo->{username}) {
437 _extract_openid_data($userinfo);
440 return $self->add_user($userinfo);
443 ## Not quite sure where this method should be.. Auth /
444 ## Credential::OpenID just pass us back the chunk of extension data
445 sub _extract_openid_data {
448 ## Spec says SHOULD use url as identifier
449 $userinfo->{username} = $userinfo->{url};
451 ## Use email addy as display if available
452 if(exists $userinfo->{extensions} &&
453 exists $userinfo->{extensions}{'http://openid.net/srv/ax/1.0'} &&
454 defined $userinfo->{extensions}{'http://openid.net/srv/ax/1.0'}{'value.email'}) {
455 ## Somewhat ugly attribute extension reponse, contains
456 ## google-email string which we can use as the id
458 $userinfo->{email} = $userinfo->{extensions}{'http://openid.net/srv/ax/1.0'}{'value.email'};
464 =head2 find_user( $userinfo )
466 Takes a hashref of C<username> or C<email>, and possibly openIDish results from
467 L<Net::OpenID::Consumer>.
469 Fetches the user object for the given username and returns it.
474 my ($self, $userinfo) = @_;
476 ## A URL field means probably an OpenID based user
477 if( exists $userinfo->{url} ) {
478 _extract_openid_data($userinfo);
482 if( exists $userinfo->{username} ) {
483 my $username = $userinfo->{username};
484 ## No logins if user is deactivated (use lookup to fetch to re-activate)
485 $user = $self->lookup(Text::Tradition::User->id_for_user($username));
486 ## If there is an inactive user, skip it
487 return if( $user && !$user->active );
488 } elsif( exists $userinfo->{email} ) {
489 ## Scan the users looking for a matching email
491 $self->scan( sub { push( @matches, @_ )
492 if $_[0]->isa('Text::Tradition::User')
493 && $_[0]->email eq $userinfo->{email} } );
494 $user = shift @matches;
496 # print STDERR "Found user, $username, email is :", $user->email, ":\n";
500 =head2 modify_user( $userinfo )
502 Takes a hashref of C<username> and C<password> (same as add_user).
504 Retrieves the user, and updates it with the new information. Username
505 changing is not currently supported.
507 Returns the updated user object, or undef if not found.
512 my ($self, $userinfo) = @_;
513 my $username = $userinfo->{username};
514 my $password = $userinfo->{password};
515 my $role = $userinfo->{role};
517 throw( "Missing username" ) unless $username;
519 my $user = $self->find_user({ username => $username });
520 throw( "Could not find user $username" ) unless $user;
523 throw( "Bad password" ) unless $self->validate_password($password);
524 $user->password(crypt_password($password));
530 $self->update($user);
535 =head2 deactivate_user( $userinfo )
537 Takes a hashref of C<username>.
539 Sets the users C<active> flag to false (0), and sets all traditions
540 assigned to them to non-public, updates the storage and returns the
543 Returns undef if user not found.
547 sub deactivate_user {
548 my ($self, $userinfo) = @_;
549 my $username = $userinfo->{username};
551 throw( "Need to specify a username for deactivation" ) unless $username;
553 my $user = $self->find_user({ username => $username });
554 throw( "User $username not found" ) unless $user;
557 foreach my $tradition (@{ $user->traditions }) {
558 ## Not implemented yet
559 # $tradition->public(0);
562 ## Should we be using Text::Tradition::Directory also?
563 $self->update(@{ $user->traditions });
565 $self->update($user);
570 =head2 reactivate_user( $userinfo )
572 Takes a hashref of C<username>.
574 Returns the user object if already activated. Activates (sets the
575 active flag to true (1)), updates the storage and returns the user.
577 Returns undef if the user is not found.
581 sub reactivate_user {
582 my ($self, $userinfo) = @_;
583 my $username = $userinfo->{username};
585 throw( "Need to specify a username for reactivation" ) unless $username;
587 my $user = $self->lookup(Text::Tradition::User->id_for_user($username));
588 throw( "User $username not found" ) unless $user;
590 return $user if $user->active;
593 $self->update($user);
598 =head2 delete_user( $userinfo )
600 CAUTION: Deletes actual data!
602 Takes a hashref of C<username>.
604 Returns undef if the user doesn't exist.
606 Removes the user from the store and returns 1.
611 my ($self, $userinfo) = @_;
612 my $username = $userinfo->{username};
614 throw( "Need to specify a username for deletion" ) unless $username;
616 my $user = $self->find_user({ username => $username });
617 throw( "User $username not found" ) unless $user;
619 ## Should we be using Text::Tradition::Directory for this bit?
620 $self->delete( @{ $user->traditions });
623 $self->delete($user);
628 =head2 validate_password( $password )
630 Takes a password string. Returns true if it is longer than
631 L</MIN_PASS_LEN>, false otherwise.
633 Used internally by L</add_user>.
637 sub validate_password {
638 my ($self, $password) = @_;
640 return if !$password;
641 return if length($password) < $self->MIN_PASS_LEN;
646 =head2 user_traditionlist( $user )
648 Returns a tradition list (see specification above) but containing only
649 those traditions visible to the specified user. If $user is the string
650 'public', returns only publicly-viewable traditions.
654 sub user_traditionlist {
655 my ($self, $user) = @_;
658 if(ref $user && $user->is_admin) {
660 return $self->traditionlist();
662 ## We have a user object already, so just fetch its traditions and use tose
663 foreach my $t (@{ $user->traditions }) {
664 push( @tlist, { 'id' => $self->object_to_id( $t ),
665 'name' => $t->name } );
668 } elsif($user ne 'public') {
669 die "Passed neither a user object nor 'public' to user_traditionlist";
672 ## Search for all traditions which allow public viewing
673 my @list = grep { $_->{public} } $self->traditionlist();
681 This package is free software and is provided "as is" without express
682 or implied warranty. You can redistribute it and/or modify it under
683 the same terms as Perl itself.
687 Tara L Andrews E<lt>aurum@cpan.orgE<gt> (initial release)
689 Shadowcat Systems L<http://www.scsys.co.uk/> (user functionality; making it all work)