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', 'new_rstore_editor' );
22 %EXPORT_TAGS = ( funcs => [ qw/ new_editor new_rstore_editor / ] );
24 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
26 sub new_rstore_editor {
27 my $e = OpenILS::Utils::CStoreEditor->new(@_);
28 $e->app('open-ils.reporter-store');
33 # -----------------------------------------------------------------------------
35 # -----------------------------------------------------------------------------
36 use constant E => 'error';
37 use constant W => 'warn';
38 use constant I => 'info';
39 use constant D => 'debug';
40 use constant A => 'activity';
44 # -----------------------------------------------------------------------------
46 # xact=><true> : creates a storage transaction
47 # authtoken=>$token : the login session key
48 # -----------------------------------------------------------------------------
50 my( $class, %params ) = @_;
51 $class = ref($class) || $class;
52 my $self = bless( \%params, $class );
53 $self->{checked_perms} = {};
59 my( $self, $app ) = @_;
60 $self->{app} = $app if $app;
61 $self->{app} = 'open-ils.cstore' unless $self->{app};
66 # -----------------------------------------------------------------------------
67 # Log the editor metadata along with the log string
68 # -----------------------------------------------------------------------------
70 my( $self, $lev, $str ) = @_;
72 $s .= "0|" unless $self->{xact};
73 $s .= "1|" if $self->{xact};
74 $s .= "0" unless $self->requestor;
75 $s .= $self->requestor->id if $self->requestor;
77 $logger->$lev("$s $str");
80 # -----------------------------------------------------------------------------
81 # Verifies the auth token and fetches the requestor object
82 # -----------------------------------------------------------------------------
85 $self->log(D, "checking auth token ".$self->authtoken);
86 my ($reqr, $evt) = $U->checkses($self->authtoken);
87 $self->event($evt) if $evt;
88 return $self->{requestor} = $reqr;
92 # -----------------------------------------------------------------------------
93 # Returns the last generated event
94 # -----------------------------------------------------------------------------
96 my( $self, $evt ) = @_;
97 $self->{event} = $evt if $evt;
98 return $self->{event};
101 # -----------------------------------------------------------------------------
102 # Destroys the transaction and disconnects where necessary,
103 # then returns the last event that occurred
104 # -----------------------------------------------------------------------------
112 # -----------------------------------------------------------------------------
113 # Clears the last caught event
114 # -----------------------------------------------------------------------------
117 $self->{event} = undef;
121 my( $self, $auth ) = @_;
122 $self->{authtoken} = $auth if $auth;
123 return $self->{authtoken};
126 # -----------------------------------------------------------------------------
127 # fetches the session, creating if necessary. If 'xact' is true on this
128 # object, a db session is created
129 # -----------------------------------------------------------------------------
131 my( $self, $session ) = @_;
132 $self->{session} = $session if $session;
134 if(!$self->{session}) {
135 $self->{session} = OpenSRF::AppSession->create($self->app);
137 if( ! $self->{session} ) {
138 my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
140 throw OpenSRF::EX::ERROR ($str);
143 $self->{session}->connect if $self->{xact} or $self->{connect};
144 $self->xact_start if $self->{xact};
146 return $self->{session};
150 # -----------------------------------------------------------------------------
151 # Starts a storage transaction
152 # -----------------------------------------------------------------------------
155 $self->log(D, "starting new db session");
156 my $stat = $self->request($self->app . '.transaction.begin');
157 $self->log(E, "error starting database transaction") unless $stat;
161 # -----------------------------------------------------------------------------
162 # Commits a storage transaction
163 # -----------------------------------------------------------------------------
166 $self->log(D, "comitting db session");
167 my $stat = $self->request($self->app.'.transaction.commit');
168 $self->log(E, "error comitting database transaction") unless $stat;
172 # -----------------------------------------------------------------------------
173 # Rolls back a storage stransaction
174 # -----------------------------------------------------------------------------
177 $self->log(I, "rolling back db session");
178 return $self->request($self->app.".transaction.rollback");
183 # -----------------------------------------------------------------------------
184 # Rolls back the transaction and disconnects
185 # -----------------------------------------------------------------------------
188 $self->xact_rollback if $self->{xact};
194 $self->session->disconnect if $self->{session};
198 # -----------------------------------------------------------------------------
199 # commits the db session and destroys the session
200 # -----------------------------------------------------------------------------
203 return unless $self->{xact};
205 $self->session->disconnect;
206 $self->{session} = undef;
209 # -----------------------------------------------------------------------------
210 # clears all object data. Does not commit the db transaction.
211 # -----------------------------------------------------------------------------
215 $$self{$_} = undef for (keys %$self);
219 # -----------------------------------------------------------------------------
221 # -----------------------------------------------------------------------------
230 # -----------------------------------------------------------------------------
231 # Does a simple storage request
232 # -----------------------------------------------------------------------------
234 my( $self, $method, @params ) = @_;
238 my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
240 $self->log(I, "request $method : $argstr");
243 $val = $self->session->request($method, @params)->gather(1);
247 $self->log(E, "request error $method : $argstr : $err");
255 # -----------------------------------------------------------------------------
256 # Sets / Returns the requstor object. This is set when checkauth succeeds.
257 # -----------------------------------------------------------------------------
259 my($self, $requestor) = @_;
260 $self->{requestor} = $requestor if $requestor;
261 return $self->{requestor};
266 # -----------------------------------------------------------------------------
267 # Holds the last data received from a storage call
268 # -----------------------------------------------------------------------------
270 my( $self, $data ) = @_;
271 $self->{data} = $data if defined $data;
272 return $self->{data};
276 # -----------------------------------------------------------------------------
277 # True if this perm has already been checked at this org
278 # -----------------------------------------------------------------------------
280 my( $self, $perm, $org ) = @_;
281 $self->{checked_perms}->{$org} = {}
282 unless $self->{checked_perms}->{$org};
283 my $checked = $self->{checked_perms}->{$org}->{$perm};
285 $self->{checked_perms}->{$org}->{$perm} = 1;
293 # -----------------------------------------------------------------------------
294 # Returns true if the requested perm is allowed. If the perm check fails,
295 # $e->event is set and undef is returned
296 # The perm user is $e->requestor->id and perm org defaults to the requestor's
298 # If this perm at the given org has already been verified, true is returned
299 # and the perm is not re-checked
300 # -----------------------------------------------------------------------------
302 my( $self, $perm, $org ) = @_;
303 my $uid = $self->requestor->id;
304 $org ||= $self->requestor->ws_ou;
305 $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
306 return 1 if $self->perm_checked($perm, $org);
307 return $self->checkperm($uid, $org, $perm);
311 my($self, $userid, $org, $perm) = @_;
312 my $s = $U->storagereq(
313 "open-ils.storage.permission.user_has_perm", $userid, $perm, $org );
316 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
326 # -----------------------------------------------------------------------------
327 # checks the appropriate perm for the operation
328 # -----------------------------------------------------------------------------
330 my( $self, $ptype, $action, $org ) = @_;
331 $org ||= $self->requestor->ws_ou;
332 my $perm = $PERMS{$ptype}{$action};
334 return undef if $self->perm_checked($perm, $org);
335 return $self->event unless $self->allowed($perm, $org);
337 $self->log(I, "no perm provided for $ptype.$action");
344 # -----------------------------------------------------------------------------
345 # Logs update actions to the activity log
346 # -----------------------------------------------------------------------------
348 my( $self, $type, $action, $arg ) = @_;
349 my $str = "$type.$action";
350 $str .= _prop_string($arg);
358 my @props = $obj->properties;
361 my $prop = $obj->$_() || "";
362 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
369 sub __arg_to_string {
371 return "" unless defined $arg;
372 if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
373 return (defined $arg->id) ? $arg->id : '<new object>';
375 return JSON->perl2JSON($arg);
380 # -----------------------------------------------------------------------------
381 # This does the actual storage query.
383 # 'search' calls become search_where calls and $arg can be a search hash or
384 # an array-ref of storage search options.
386 # 'retrieve' expects an id
387 # 'update' expects an object
388 # 'create' expects an object
389 # 'delete' expects an object
391 # All methods return true on success and undef on failure. On failure,
392 # $e->event is set to the generated event.
393 # Note: this method assumes that updating a non-changed object and
394 # thereby receiving a 0 from storage, is a successful update.
396 # The method will therefore return true so the caller can just do
397 # $e->update_blah($x) or return $e->event;
398 # The true value returned from storage for all methods will be stored in
399 # $e->data, until the next method is called.
401 # not-found events are generated on retrieve and serach methods.
402 # action=search methods will return [] (==true) if no data is found. If the
403 # caller is interested in the not found event, they can do:
404 # return $e->event unless @$results;
405 # -----------------------------------------------------------------------------
407 my( $self, $action, $type, $arg, $options ) = @_;
409 if( $action eq 'retrieve' ) {
410 if(! defined($arg) ) {
411 $self->log(W,"$action $type called with no ID...");
412 $self->event(_mk_not_found($type, $arg));
414 } elsif( ref($arg) =~ /Fieldmapper/ ) {
415 $self->log(E,"$action $type called with an object.. attempting ID retrieval..");
420 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
421 my $method = $self->app.".direct.$type.$action";
423 if( $action eq 'search' ) {
424 $method = "$method.atomic";
426 } elsif( $action eq 'batch_retrieve' ) {
428 @arg = ( { id => $arg } );
429 $method =~ s/batch_retrieve/search/o;
430 $method = "$method.atomic";
432 } elsif( $action eq 'retrieve_all' ) {
434 $method =~ s/retrieve_all/search/o;
437 my $fmobj = "Fieldmapper::$tt";
438 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
439 $method = "$method.atomic";
442 $method =~ s/search/id_list/o if $options->{idlist};
444 # remove any stale events
447 if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
449 $logger->error("Attempt to update DB while not in a transaction : $method");
450 throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
452 $self->log_activity($type, $action, $arg);
455 if($$options{checkperm}) {
456 my $a = ($action eq 'search') ? 'retrieve' : $action;
457 my $e = $self->_checkperm($type, $a, $$options{permorg});
468 $obj = $self->request($method, @arg);
469 } catch Error with { $err = shift; };
473 $self->log(I, "request returned no data : $method");
475 if( $action eq 'retrieve' ) {
476 $self->event(_mk_not_found($type, $arg));
478 } elsif( $action eq 'update' or
479 $action eq 'delete' or $action eq 'create' ) {
480 my $evt = OpenILS::Event->new(
481 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
487 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
488 payload => $arg, debug => "$err" ));
495 if( $action eq 'create' and $obj == 0 ) {
496 my $evt = OpenILS::Event->new(
497 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
502 # If we havn't dealt with the error in a nice way, go ahead and throw it
505 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
506 payload => $arg, debug => "$err" ));
510 if( $action eq 'search' or $action eq 'batch_retrieve' or $action eq 'retrieve_all') {
511 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
512 $self->event(_mk_not_found($type, $arg)) unless @$obj;
515 $arg->id($obj->id) if $action eq 'create'; # grabs the id on create
516 $self->data($obj); # cache the data for convenience
518 return ($obj) ? $obj : 1;
523 my( $type, $arg ) = @_;
524 (my $t = $type) =~ s/\./_/og;
526 return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
531 # utility method for loading
535 $str =~ s/Fieldmapper:://o;
541 # -------------------------------------------------------------
542 # Load up the methods from the FM classes
543 # -------------------------------------------------------------
544 my $map = $Fieldmapper::fieldmap;
545 for my $object (keys %$map) {
546 my $obj = __fm2meth($object,'_');
547 my $type = __fm2meth($object, '.');
549 my $update = "update_$obj";
551 "sub $update {return shift()->runmethod('update', '$type', \@_);}";
554 my $retrieve = "retrieve_$obj";
556 "sub $retrieve {return shift()->runmethod('retrieve', '$type', \@_);}";
559 my $search = "search_$obj";
561 "sub $search {return shift()->runmethod('search', '$type', \@_);}";
564 my $create = "create_$obj";
566 "sub $create {return shift()->runmethod('create', '$type', \@_);}";
569 my $delete = "delete_$obj";
571 "sub $delete {return shift()->runmethod('delete', '$type', \@_);}";
574 my $bretrieve = "batch_retrieve_$obj";
576 "sub $bretrieve {return shift()->runmethod('batch_retrieve', '$type', \@_);}";
579 my $retrieveall = "retrieve_all_$obj";
581 "sub $retrieveall {return shift()->runmethod('retrieve_all', '$type', \@_);}";