1 use strict; use warnings;
2 package OpenILS::Utils::CStoreEditor;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::AppSession;
5 use OpenSRF::EX qw(:try);
6 use OpenILS::Utils::Fieldmapper;
10 use OpenSRF::Utils::Logger qw($logger);
11 my $U = "OpenILS::Application::AppUtils";
15 # -----------------------------------------------------------------------------
16 # Export some useful functions
17 # -----------------------------------------------------------------------------
18 use vars qw(@EXPORT_OK %EXPORT_TAGS);
20 use base qw/Exporter/;
21 push @EXPORT_OK, 'new_editor';
22 %EXPORT_TAGS = ( funcs => [ qw/ new_editor / ] );
24 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
27 # -----------------------------------------------------------------------------
29 # -----------------------------------------------------------------------------
30 use constant E => 'error';
31 use constant W => 'warn';
32 use constant I => 'info';
33 use constant D => 'debug';
34 use constant A => 'activity';
38 # -----------------------------------------------------------------------------
40 # xact=><true> : creates a storage transaction
41 # authtoken=>$token : the login session key
42 # -----------------------------------------------------------------------------
44 my( $class, %params ) = @_;
45 $class = ref($class) || $class;
46 my $self = bless( \%params, $class );
47 $self->{checked_perms} = {};
51 # -----------------------------------------------------------------------------
52 # Log the editor metadata along with the log string
53 # -----------------------------------------------------------------------------
55 my( $self, $lev, $str ) = @_;
57 $s .= "0|" unless $self->{xact};
58 $s .= "1|" if $self->{xact};
59 $s .= "0" unless $self->requestor;
60 $s .= $self->requestor->id if $self->requestor;
62 $logger->$lev("$s $str");
65 # -----------------------------------------------------------------------------
66 # Verifies the auth token and fetches the requestor object
67 # -----------------------------------------------------------------------------
70 $self->log(D, "checking auth token ".$self->authtoken);
71 my ($reqr, $evt) = $U->checkses($self->authtoken);
72 $self->event($evt) if $evt;
73 return $self->{requestor} = $reqr;
77 # -----------------------------------------------------------------------------
78 # Returns the last generated event
79 # -----------------------------------------------------------------------------
81 my( $self, $evt ) = @_;
82 $self->{event} = $evt if $evt;
83 return $self->{event};
86 # -----------------------------------------------------------------------------
87 # Clears the last caught event
88 # -----------------------------------------------------------------------------
91 $self->{event} = undef;
95 my( $self, $auth ) = @_;
96 $self->{authtoken} = $auth if $auth;
97 return $self->{authtoken};
100 # -----------------------------------------------------------------------------
101 # fetches the session, creating if necessary. If 'xact' is true on this
102 # object, a db session is created
103 # -----------------------------------------------------------------------------
105 my( $self, $session ) = @_;
106 $self->{session} = $session if $session;
108 if(!$self->{session}) {
109 $self->{session} = OpenSRF::AppSession->create('open-ils.cstore');
111 if( ! $self->{session} ) {
112 my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
114 throw OpenSRF::EX::ERROR ($str);
117 $self->{session}->connect if $self->{xact} or $self->{connect};
118 $self->xact_start if $self->{xact};
120 return $self->{session};
124 # -----------------------------------------------------------------------------
125 # Starts a storage transaction
126 # -----------------------------------------------------------------------------
129 $self->log(D, "starting new db session");
130 my $stat = $self->request('open-ils.cstore.transaction.begin');
131 $self->log(E, "error starting database transaction") unless $stat;
135 # -----------------------------------------------------------------------------
136 # Commits a storage transaction
137 # -----------------------------------------------------------------------------
140 $self->log(D, "comitting db session");
141 my $stat = $self->request('open-ils.cstore.transaction.commit');
142 $self->log(E, "error comitting database transaction") unless $stat;
146 # -----------------------------------------------------------------------------
147 # Rolls back a storage stransaction
148 # -----------------------------------------------------------------------------
151 $self->log(I, "rolling back db session");
152 return $self->request("open-ils.cstore.transaction.rollback");
157 # -----------------------------------------------------------------------------
158 # Rolls back the transaction and disconnects
159 # -----------------------------------------------------------------------------
162 $self->xact_rollback if $self->{xact};
168 $self->session->disconnect if $self->{session};
172 # -----------------------------------------------------------------------------
173 # commits the db session and destroys the session
174 # -----------------------------------------------------------------------------
177 return unless $self->{xact};
179 $self->session->disconnect;
180 $self->{session} = undef;
183 # -----------------------------------------------------------------------------
184 # clears all object data. Does not commit the db transaction.
185 # -----------------------------------------------------------------------------
189 $$self{$_} = undef for (keys %$self);
193 # -----------------------------------------------------------------------------
195 # -----------------------------------------------------------------------------
204 # -----------------------------------------------------------------------------
205 # Does a simple storage request
206 # -----------------------------------------------------------------------------
208 my( $self, $method, @params ) = @_;
212 my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
214 $self->log(I, "request $method : $argstr");
217 $val = $self->session->request($method, @params)->gather(1);
221 $self->log(E, "request error $method : $argstr : $err");
229 # -----------------------------------------------------------------------------
230 # Sets / Returns the requstor object. This is set when checkauth succeeds.
231 # -----------------------------------------------------------------------------
233 my($self, $requestor) = @_;
234 $self->{requestor} = $requestor if $requestor;
235 return $self->{requestor};
240 # -----------------------------------------------------------------------------
241 # Holds the last data received from a storage call
242 # -----------------------------------------------------------------------------
244 my( $self, $data ) = @_;
245 $self->{data} = $data if defined $data;
246 return $self->{data};
250 # -----------------------------------------------------------------------------
251 # True if this perm has already been checked at this org
252 # -----------------------------------------------------------------------------
254 my( $self, $perm, $org ) = @_;
255 $self->{checked_perms}->{$org} = {}
256 unless $self->{checked_perms}->{$org};
257 my $checked = $self->{checked_perms}->{$org}->{$perm};
259 $self->{checked_perms}->{$org}->{$perm} = 1;
267 # -----------------------------------------------------------------------------
268 # Returns true if the requested perm is allowed. If the perm check fails,
269 # $e->event is set and undef is returned
270 # The perm user is $e->requestor->id and perm org defaults to the requestor's
272 # If this perm at the given org has already been verified, true is returned
273 # and the perm is not re-checked
274 # -----------------------------------------------------------------------------
276 my( $self, $perm, $org ) = @_;
277 my $uid = $self->requestor->id;
278 $org ||= $self->requestor->ws_ou;
279 $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
280 return 1 if $self->perm_checked($perm, $org);
281 return $self->checkperm($uid, $org, $perm);
285 my($self, $userid, $org, $perm) = @_;
286 my $s = $U->storagereq(
287 "open-ils.storage.permission.user_has_perm", $userid, $perm, $org );
290 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
300 # -----------------------------------------------------------------------------
301 # checks the appropriate perm for the operation
302 # -----------------------------------------------------------------------------
304 my( $self, $ptype, $action, $org ) = @_;
305 $org ||= $self->requestor->ws_ou;
306 my $perm = $PERMS{$ptype}{$action};
308 return undef if $self->perm_checked($perm, $org);
309 return $self->event unless $self->allowed($perm, $org);
311 $self->log(E, "no perm provided for $ptype.$action");
318 # -----------------------------------------------------------------------------
319 # Logs update actions to the activity log
320 # -----------------------------------------------------------------------------
322 my( $self, $type, $action, $arg ) = @_;
323 my $str = "$type.$action";
324 $str .= _prop_string($arg);
332 my @props = $obj->properties;
335 my $prop = $obj->$_() || "";
336 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
343 sub __arg_to_string {
345 return "" unless defined $arg;
346 if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
347 return (defined $arg->id) ? $arg->id : '<new object>';
349 return JSON->perl2JSON($arg);
354 # -----------------------------------------------------------------------------
355 # This does the actual storage query.
357 # 'search' calls become search_where calls and $arg can be a search hash or
358 # an array-ref of storage search options.
360 # 'retrieve' expects an id
361 # 'update' expects an object
362 # 'create' expects an object
363 # 'delete' expects an object
365 # All methods return true on success and undef on failure. On failure,
366 # $e->event is set to the generated event.
367 # Note: this method assumes that updating a non-changed object and
368 # thereby receiving a 0 from storage, is a successful update.
370 # The method will therefore return true so the caller can just do
371 # $e->update_blah($x) or return $e->event;
372 # The true value returned from storage for all methods will be stored in
373 # $e->data, until the next method is called.
375 # not-found events are generated on retrieve and serach methods.
376 # action=search methods will return [] (==true) if no data is found. If the
377 # caller is interested in the not found event, they can do:
378 # return $e->event unless @$results;
379 # -----------------------------------------------------------------------------
381 my( $self, $action, $type, $arg, $options ) = @_;
383 if( $action eq 'retrieve' ) {
384 if(! defined($arg) ) {
385 $self->log(W,"$action $type called with no ID...");
386 $self->event(_mk_not_found($type, $arg));
388 } elsif( ref($arg) =~ /Fieldmapper/ ) {
389 $self->log(E,"$action $type called with an object.. attempting ID retrieval..");
394 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
395 my $method = "open-ils.cstore.direct.$type.$action";
397 if( $action eq 'search' ) {
398 $method = "$method.atomic";
400 } elsif( $action eq 'batch_retrieve' ) {
402 @arg = ( { id => $arg } );
403 $method =~ s/batch_retrieve/search/o;
404 $method = "$method.atomic";
406 } elsif( $action eq 'retrieve_all' ) {
408 $method =~ s/retrieve_all/search/o;
411 my $fmobj = "Fieldmapper::$tt";
412 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
413 $method = "$method.atomic";
416 $method =~ s/search/id_list/o if $options->{idlist};
418 # remove any stale events
421 if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
423 $logger->error("Attempt to update DB while not in a transaction : $method");
424 throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
426 $self->log_activity($type, $action, $arg);
429 if($$options{checkperm}) {
430 my $a = ($action eq 'search') ? 'retrieve' : $action;
431 my $e = $self->_checkperm($type, $a, $$options{permorg});
442 $obj = $self->request($method, @arg);
443 } catch Error with { $err = shift; };
447 $self->log(I, "request returned no data : $method");
449 if( $action eq 'retrieve' ) {
450 $self->event(_mk_not_found($type, $arg));
452 } elsif( $action eq 'update' or
453 $action eq 'delete' or $action eq 'create' ) {
454 my $evt = OpenILS::Event->new(
455 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
461 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
462 payload => $arg, debug => "$err" ));
469 if( $action eq 'create' and $obj == 0 ) {
470 my $evt = OpenILS::Event->new(
471 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
476 # If we havn't dealt with the error in a nice way, go ahead and throw it
479 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
480 payload => $arg, debug => "$err" ));
484 if( $action eq 'search' or $action eq 'batch_retrieve' or $action eq 'retrieve_all') {
485 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
486 $self->event(_mk_not_found($type, $arg)) unless @$obj;
489 $arg->id($obj->id) if $action eq 'create'; # grabs the id on create
490 $self->data($obj); # cache the data for convenience
492 return ($obj) ? $obj : 1;
497 my( $type, $arg ) = @_;
498 (my $t = $type) =~ s/\./_/og;
500 return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
505 # utility method for loading
509 $str =~ s/Fieldmapper:://o;
515 # -------------------------------------------------------------
516 # Load up the methods from the FM classes
517 # -------------------------------------------------------------
518 my $map = $Fieldmapper::fieldmap;
519 for my $object (keys %$map) {
520 my $obj = __fm2meth($object,'_');
521 my $type = __fm2meth($object, '.');
523 my $update = "update_$obj";
525 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
528 my $retrieve = "retrieve_$obj";
530 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
533 my $search = "search_$obj";
535 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
538 my $create = "create_$obj";
540 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
543 my $delete = "delete_$obj";
545 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
548 my $bretrieve = "batch_retrieve_$obj";
550 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
553 my $retrieveall = "retrieve_all_$obj";
555 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";