]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Biblio.pm
added some input scrubbing on limit and offset
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Search / Biblio.pm
1 package OpenILS::Application::Search::Biblio;
2 use base qw/OpenILS::Application/;
3 use strict; use warnings;
4
5
6 use OpenSRF::Utils::JSON;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Utils::ModsParser;
9 use OpenSRF::Utils::SettingsClient;
10 use OpenILS::Utils::CStoreEditor q/:funcs/;
11 use OpenSRF::Utils::Cache;
12 use Encode;
13
14 use OpenSRF::Utils::Logger qw/:logger/;
15
16
17 use OpenSRF::Utils::JSON;
18
19 use Time::HiRes qw(time);
20 use OpenSRF::EX qw(:try);
21 use Digest::MD5 qw(md5_hex);
22
23 use XML::LibXML;
24 use XML::LibXSLT;
25
26 use Data::Dumper;
27 $Data::Dumper::Indent = 0;
28
29 use OpenILS::Const qw/:const/;
30
31 use OpenILS::Application::AppUtils;
32 my $apputils = "OpenILS::Application::AppUtils";
33 my $U = $apputils;
34
35 my $pfx = "open-ils.search_";
36
37 my $cache;
38 my $cache_timeout;
39
40 sub initialize {
41         $cache = OpenSRF::Utils::Cache->new('global');
42         my $sclient = OpenSRF::Utils::SettingsClient->new();
43         $cache_timeout = $sclient->config_value(
44                         "apps", "open-ils.search", "app_settings", "cache_timeout" ) || 300;
45         $logger->info("Search cache timeout is $cache_timeout");
46 }
47
48
49
50 # ---------------------------------------------------------------------------
51 # takes a list of record id's and turns the docs into friendly 
52 # mods structures. Creates one MODS structure for each doc id.
53 # ---------------------------------------------------------------------------
54 sub _records_to_mods {
55         my @ids = @_;
56         
57         my @results;
58         my @marcxml_objs;
59
60         my $session = OpenSRF::AppSession->create("open-ils.cstore");
61         my $request = $session->request(
62                         "open-ils.cstore.direct.biblio.record_entry.search", { id => \@ids } );
63
64         while( my $resp = $request->recv ) {
65                 my $content = $resp->content;
66                 next if $content->id == OILS_PRECAT_RECORD;
67                 my $u = OpenILS::Utils::ModsParser->new();
68                 $u->start_mods_batch( $content->marc );
69                 my $mods = $u->finish_mods_batch();
70                 $mods->doc_id($content->id());
71                 $mods->tcn($content->tcn_value);
72                 push @results, $mods;
73         }
74
75         $session->disconnect();
76         return \@results;
77 }
78
79 __PACKAGE__->register_method(
80         method  => "record_id_to_mods",
81         api_name        => "open-ils.search.biblio.record.mods.retrieve",
82         argc            => 1, 
83         note            => "Provide ID, we provide the mods"
84 );
85
86 # converts a record into a mods object with copy counts attached
87 sub record_id_to_mods {
88
89         my( $self, $client, $org_id, $id ) = @_;
90
91         my $mods_list = _records_to_mods( $id );
92         my $mods_obj = $mods_list->[0];
93         my $cmethod = $self->method_lookup(
94                         "open-ils.search.biblio.record.copy_count");
95         my ($count) = $cmethod->run($org_id, $id);
96         $mods_obj->copy_count($count);
97
98         return $mods_obj;
99 }
100
101
102
103 __PACKAGE__->register_method(
104         method  => "record_id_to_mods_slim",
105     authoritative => 1,
106         api_name        => "open-ils.search.biblio.record.mods_slim.retrieve",
107         argc            => 1, 
108         note            => "Provide ID, we provide the mods"
109 );
110
111 # converts a record into a mods object with NO copy counts attached
112 sub record_id_to_mods_slim {
113         my( $self, $client, $id ) = @_;
114         return undef unless defined $id;
115
116         if(ref($id) and ref($id) == 'ARRAY') {
117                 return _records_to_mods( @$id );
118         }
119         my $mods_list = _records_to_mods( $id );
120         my $mods_obj = $mods_list->[0];
121         return OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND') unless $mods_obj;
122         return $mods_obj;
123 }
124
125
126 # Returns the number of copies attached to a record based on org location
127 __PACKAGE__->register_method(
128         method  => "record_id_to_copy_count",
129         api_name        => "open-ils.search.biblio.record.copy_count",
130 );
131
132 __PACKAGE__->register_method(
133         method  => "record_id_to_copy_count",
134     authoritative => 1,
135         api_name        => "open-ils.search.biblio.record.copy_count.staff",
136 );
137
138 __PACKAGE__->register_method(
139         method  => "record_id_to_copy_count",
140         api_name        => "open-ils.search.biblio.metarecord.copy_count",
141 );
142
143 __PACKAGE__->register_method(
144         method  => "record_id_to_copy_count",
145         api_name        => "open-ils.search.biblio.metarecord.copy_count.staff",
146 );
147 sub record_id_to_copy_count {
148         my( $self, $client, $org_id, $record_id, $format ) = @_;
149
150         return [] unless $record_id;
151         $format = undef if (!$format or $format eq 'all');
152
153         my $method = "open-ils.storage.biblio.record_entry.copy_count.atomic";
154         my $key = "record";
155
156         if($self->api_name =~ /metarecord/) {
157                 $method = "open-ils.storage.metabib.metarecord.copy_count.atomic";
158                 $key = "metarecord";
159         }
160
161         $method =~ s/atomic/staff\.atomic/og if($self->api_name =~ /staff/ );
162
163         my $count = $U->storagereq( $method, 
164                 org_unit => $org_id, $key => $record_id, format => $format );
165
166         return [ sort { $a->{depth} <=> $b->{depth} } @$count ];
167 }
168
169
170
171
172 __PACKAGE__->register_method(
173         method  => "biblio_search_tcn",
174         api_name        => "open-ils.search.biblio.tcn",
175         argc            => 3, 
176         note            => "Retrieve a record by TCN",
177 );
178
179 sub biblio_search_tcn {
180
181         my( $self, $client, $tcn, $include_deleted ) = @_;
182
183         $tcn =~ s/.*?(\w+)\s*$/$1/o;
184
185         my $e = new_editor();
186    my $search = {tcn_value => $tcn};
187    $search->{deleted} = 'f' unless $include_deleted;
188         my $recs = $e->search_biblio_record_entry( $search, {idlist =>1} );
189         
190         return { count => scalar(@$recs), ids => $recs };
191 }
192
193
194 # --------------------------------------------------------------------------------
195
196 __PACKAGE__->register_method(
197         method  => "biblio_barcode_to_copy",
198         api_name        => "open-ils.search.asset.copy.find_by_barcode",);
199 sub biblio_barcode_to_copy { 
200         my( $self, $client, $barcode ) = @_;
201         my( $copy, $evt ) = $U->fetch_copy_by_barcode($barcode);
202         return $evt if $evt;
203         return $copy;
204 }
205
206 __PACKAGE__->register_method(
207         method  => "biblio_id_to_copy",
208         api_name        => "open-ils.search.asset.copy.batch.retrieve",);
209 sub biblio_id_to_copy { 
210         my( $self, $client, $ids ) = @_;
211         $logger->info("Fetching copies @$ids");
212         return $U->cstorereq(
213                 "open-ils.cstore.direct.asset.copy.search.atomic", { id => $ids } );
214 }
215
216
217 __PACKAGE__->register_method(
218         method  => "copy_retrieve", 
219         api_name        => "open-ils.search.asset.copy.retrieve",);
220 sub copy_retrieve {
221         my( $self, $client, $cid ) = @_;
222         my( $copy, $evt ) = $U->fetch_copy($cid);
223         return $evt if $evt;
224         return $copy;
225 }
226
227 __PACKAGE__->register_method(
228         method  => "volume_retrieve", 
229         api_name        => "open-ils.search.asset.call_number.retrieve");
230 sub volume_retrieve {
231         my( $self, $client, $vid ) = @_;
232         my $e = new_editor();
233         my $vol = $e->retrieve_asset_call_number($vid) or return $e->event;
234         return $vol;
235 }
236
237 __PACKAGE__->register_method(
238         method  => "fleshed_copy_retrieve_batch",
239     authoritative => 1,
240         api_name        => "open-ils.search.asset.copy.fleshed.batch.retrieve");
241
242 sub fleshed_copy_retrieve_batch { 
243         my( $self, $client, $ids ) = @_;
244         $logger->info("Fetching fleshed copies @$ids");
245         return $U->cstorereq(
246                 "open-ils.cstore.direct.asset.copy.search.atomic",
247                 { id => $ids },
248                 { flesh => 1, 
249                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
250                 });
251 }
252
253
254 __PACKAGE__->register_method(
255         method  => "fleshed_copy_retrieve",
256         api_name        => "open-ils.search.asset.copy.fleshed.retrieve",);
257
258 sub fleshed_copy_retrieve { 
259         my( $self, $client, $id ) = @_;
260         my( $c, $e) = $U->fetch_fleshed_copy($id);
261         return $e if $e;
262         return $c;
263 }
264
265
266
267 __PACKAGE__->register_method(
268         method => 'fleshed_by_barcode',
269         api_name        => "open-ils.search.asset.copy.fleshed2.find_by_barcode",);
270 sub fleshed_by_barcode {
271         my( $self, $conn, $barcode ) = @_;
272         my $e = new_editor();
273         my $copyid = $e->search_asset_copy(
274                 {barcode => $barcode, deleted => 'f'}, {idlist=>1})->[0]
275                 or return $e->event;
276         return fleshed_copy_retrieve2( $self, $conn, $copyid);
277 }
278
279
280 __PACKAGE__->register_method(
281         method  => "fleshed_copy_retrieve2",
282         api_name        => "open-ils.search.asset.copy.fleshed2.retrieve",);
283
284 sub fleshed_copy_retrieve2 { 
285         my( $self, $client, $id ) = @_;
286         my $e = new_editor();
287         my $copy = $e->retrieve_asset_copy(
288                 [
289                         $id,
290                         { 
291                                 flesh                           => 2,
292                                 flesh_fields    => { 
293                                         acp => [ qw/ location status stat_cat_entry_copy_maps notes age_protect / ],
294                                         ascecm => [ qw/ stat_cat stat_cat_entry / ],
295                                 }
296                         }
297                 ]
298         ) or return $e->event;
299
300         # For backwards compatibility
301         #$copy->stat_cat_entries($copy->stat_cat_entry_copy_maps);
302
303         if( $copy->status->id == OILS_COPY_STATUS_CHECKED_OUT ) {
304                 $copy->circulations(
305                         $e->search_action_circulation( 
306                                 [       
307                                         { target_copy => $copy->id },
308                                         {
309                                                 order_by => { circ => 'xact_start desc' },
310                                                 limit => 1
311                                         }
312                                 ]
313                         )
314                 );
315         }
316
317         return $copy;
318 }
319
320
321 __PACKAGE__->register_method(
322         method => 'flesh_copy_custom',
323         api_name => 'open-ils.search.asset.copy.fleshed.custom'
324 );
325
326 sub flesh_copy_custom {
327         my( $self, $conn, $copyid, $fields ) = @_;
328         my $e = new_editor();
329         my $copy = $e->retrieve_asset_copy(
330                 [
331                         $copyid,
332                         { 
333                                 flesh                           => 1,
334                                 flesh_fields    => { 
335                                         acp => $fields,
336                                 }
337                         }
338                 ]
339         ) or return $e->event;
340         return $copy;
341 }
342
343
344
345
346
347
348 __PACKAGE__->register_method(
349         method  => "biblio_barcode_to_title",
350         api_name        => "open-ils.search.biblio.find_by_barcode",
351 );
352
353 sub biblio_barcode_to_title {
354         my( $self, $client, $barcode ) = @_;
355
356         my $title = $apputils->simple_scalar_request(
357                 "open-ils.storage",
358                 "open-ils.storage.biblio.record_entry.retrieve_by_barcode", $barcode );
359
360         return { ids => [ $title->id ], count => 1 } if $title;
361         return { count => 0 };
362 }
363
364 __PACKAGE__->register_method(
365     method => 'title_id_by_item_barcode',
366     api_name => 'open-ils.search.bib_id.by_barcode'
367 );
368
369 sub title_id_by_item_barcode {
370     my( $self, $conn, $barcode ) = @_;
371     my $e = new_editor();
372     my $copies = $e->search_asset_copy(
373         [
374             { deleted => 'f', barcode => $barcode },
375             {
376                 flesh => 2,
377                 flesh_fields => {
378                     acp => [ 'call_number' ],
379                     acn => [ 'record' ]
380                 }
381             }
382         ]
383     );
384
385     return $e->event unless @$copies;
386     return $$copies[0]->call_number->record->id;
387 }
388
389
390 __PACKAGE__->register_method(
391         method  => "biblio_copy_to_mods",
392         api_name        => "open-ils.search.biblio.copy.mods.retrieve",
393 );
394
395 # takes a copy object and returns it fleshed mods object
396 sub biblio_copy_to_mods {
397         my( $self, $client, $copy ) = @_;
398
399         my $volume = $U->cstorereq( 
400                 "open-ils.cstore.direct.asset.call_number.retrieve",
401                 $copy->call_number() );
402
403         my $mods = _records_to_mods($volume->record());
404         $mods = shift @$mods;
405         $volume->copies([$copy]);
406         push @{$mods->call_numbers()}, $volume;
407
408         return $mods;
409 }
410
411
412 __PACKAGE__->register_method(
413     api_name => 'open-ils.search.biblio.multiclass.query',
414     method => 'multiclass_query',
415     signature => q#
416         @param arghash @see open-ils.search.biblio.multiclass
417         @param query Raw human-readable query string.  
418             Recognized search keys include: 
419                 keyword/kw - search keyword(s)
420                 author/au/name - search author(s)
421                 title/ti - search title
422                 subject/su - search subject
423                 series/se - search series
424                 lang - limit by language (specifiy multiple langs with lang:l1 lang:l2 ...)
425                 site - search at specified org unit, corresponds to actor.org_unit.shortname
426                 sort - sort type (title, author, pubdate)
427                 dir - sort direction (asc, desc)
428                 available - if set to anything other than "false" or "0", limits to available items
429
430                 keyword, title, author, subject, and series support additional search 
431                 subclasses, specified with a "|". For example, "title|proper:gone with the wind" 
432                 For more, see config.metabib_field
433
434         @param docache @see open-ils.search.biblio.multiclass
435     #
436 );
437 __PACKAGE__->register_method(
438     api_name => 'open-ils.search.biblio.multiclass.query.staff',
439     method => 'multiclass_query',
440     signature => '@see open-ils.search.biblio.multiclass.query');
441 __PACKAGE__->register_method(
442     api_name => 'open-ils.search.metabib.multiclass.query',
443     method => 'multiclass_query',
444     signature => '@see open-ils.search.biblio.multiclass.query');
445 __PACKAGE__->register_method(
446     api_name => 'open-ils.search.metabib.multiclass.query.staff',
447     method => 'multiclass_query',
448     signature => '@see open-ils.search.biblio.multiclass.query');
449
450 sub multiclass_query {
451     my($self, $conn, $arghash, $query, $docache) = @_;
452
453     $logger->debug("initial search query => $query");
454     my $orig_query = $query;
455
456     $query =~ s/\+/ /go;
457     $query =~ s/'//go;
458     $query =~ s/^\s+//go;
459
460     # convert convenience classes (e.g. kw for keyword) to the full class name
461     $query =~ s/kw(:|\|)/keyword$1/go;
462     $query =~ s/ti(:|\|)/title$1/go;
463     $query =~ s/au(:|\|)/author$1/go;
464     $query =~ s/su(:|\|)/subject$1/go;
465     $query =~ s/se(:|\|)/series$1/go;
466     $query =~ s/name(:|\|)/author$1/og;
467
468     $logger->debug("cleansed query string => $query");
469     my $search = $arghash->{searches} = {};
470
471     while ($query =~ s/((?:keyword(?:\|\w+)?|title(?:\|\w+)?|author(?:\|\w+)?|subject(?:\|\w+)?|series(?:\|\w+)?|site|dir|sort|lang|available):[^:]+)$//so) {
472         my($type, $value) = split(':', $1);
473         next unless $type and $value;
474
475         $value =~ s/^\s*//og;
476         $value =~ s/\s*$//og;
477         $type = 'sort_dir' if $type eq 'dir';
478
479         if($type eq 'site') {
480             # 'site' is the org shortname.  when using this, we also want 
481             # to search at the requested org's depth
482             my $e = new_editor();
483             if(my $org = $e->search_actor_org_unit({shortname => $value})->[0]) {
484                 $arghash->{org_unit} = $org->id if $org;
485                 $arghash->{depth} = $e->retrieve_actor_org_unit_type($org->ou_type)->depth;
486             } else {
487                 $logger->warn("'site:' query used on invalid org shortname: $value ... ignoring");
488             }
489
490         } elsif($type eq 'available') {
491             # limit to available
492             $arghash->{available} = 1 unless $value eq 'false' or $value eq '0';
493
494         } elsif($type eq 'lang') {
495             # collect languages into an array of languages
496             $arghash->{language} = [] unless $arghash->{language};
497             push(@{$arghash->{language}}, $value);
498
499         } elsif($type =~ /^sort/o) {
500             # sort and sort_dir modifiers
501             $arghash->{$type} = $value;
502
503         } else {
504             # append the search term to the term under construction
505             $search->{$type} =  {} unless $search->{$type};
506             $search->{$type}->{term} =  
507                 ($search->{$type}->{term}) ? $search->{$type}->{term} . " $value" : $value;
508         }
509     }
510
511     if($query) {
512         # This is the front part of the string before any special tokens were parsed. 
513         # Add this data to the default search class
514         my $type = $arghash->{default_class} || 'keyword';
515         $search->{$type} =  {} unless $search->{$type};
516         $search->{$type}->{term} =
517             ($search->{$type}->{term}) ? $search->{$type}->{term} . " $query" : $query;
518     }
519
520     # capture the original limit because the search method alters the limit internally
521     my $ol = $arghash->{limit};
522
523         my $sclient = OpenSRF::Utils::SettingsClient->new;
524
525     (my $method = $self->api_name) =~ s/\.query//o;
526
527     $method =~ s/multiclass/multiclass.staged/
528         if $sclient->config_value(apps => 'open-ils.search',
529             app_settings => 'use_staged_search') =~ /true/i;
530
531
532         $method = $self->method_lookup($method);
533     my ($data) = $method->run($arghash, $docache);
534
535     $arghash->{limit} = $ol if $ol;
536     $data->{compiled_search} = $arghash;
537     $data->{query} = $orig_query;
538
539     $logger->info("compiled search is " . OpenSRF::Utils::JSON->perl2JSON($arghash));
540
541     return $data;
542 }
543
544 __PACKAGE__->register_method(
545         method          => 'cat_search_z_style_wrapper',
546         api_name        => 'open-ils.search.biblio.zstyle',
547         stream          => 1,
548         signature       => q/@see open-ils.search.biblio.multiclass/);
549
550 sub cat_search_z_style_wrapper {
551         my $self = shift;
552         my $client = shift;
553         my $authtoken = shift;
554         my $args = shift;
555
556         my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
557
558         my $ou = $cstore->request(
559                 'open-ils.cstore.direct.actor.org_unit.search',
560                 { parent_ou => undef }
561         )->gather(1);
562
563         my $result = { service => 'native-evergreen-catalog', records => [] };
564         my $searchhash = { limit => $$args{limit}, offset => $$args{offset}, org_unit => $ou->id };
565
566         $$searchhash{searches}{title}{term} = $$args{search}{title} if $$args{search}{title};
567         $$searchhash{searches}{author}{term} = $$args{search}{author} if $$args{search}{author};
568         $$searchhash{searches}{subject}{term} = $$args{search}{subject} if $$args{search}{subject};
569         $$searchhash{searches}{keyword}{term} = $$args{search}{keyword} if $$args{search}{keyword};
570
571         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{tcn} if $$args{search}{tcn};
572         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{isbn} if $$args{search}{isbn};
573         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{issn} if $$args{search}{issn};
574         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{publisher} if $$args{search}{publisher};
575         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{pubdate} if $$args{search}{pubdate};
576         $$searchhash{searches}{keyword}{term} .= join ' ', $$searchhash{searches}{keyword}{term}, $$args{search}{item_type} if $$args{search}{item_type};
577
578         my $list = the_quest_for_knowledge( $self, $client, $searchhash );
579
580         if ($list->{count} > 0) {
581                 $result->{count} = $list->{count};
582
583                 my $records = $cstore->request(
584                         'open-ils.cstore.direct.biblio.record_entry.search.atomic',
585                         { id => [ map { ( $_->[0] ) } @{$list->{ids}} ] }
586                 )->gather(1);
587
588                 for my $rec ( @$records ) {
589                         
590                         my $u = OpenILS::Utils::ModsParser->new();
591                         $u->start_mods_batch( $rec->marc );
592                         my $mods = $u->finish_mods_batch();
593
594                         push @{ $result->{records} }, { mvr => $mods, marcxml => $rec->marc, bibid => $rec->id };
595
596                 }
597
598         }
599
600     $cstore->disconnect();
601         return $result;
602 }
603
604 # ----------------------------------------------------------------------------
605 # These are the main OPAC search methods
606 # ----------------------------------------------------------------------------
607
608 __PACKAGE__->register_method(
609         method          => 'the_quest_for_knowledge',
610         api_name                => 'open-ils.search.biblio.multiclass',
611         signature       => q/
612                 Performs a multi class bilbli or metabib search
613                 @param searchhash A search object layed out like so:
614                         searches : { "$class" : "$value", ...}
615                         org_unit : The org id to focus the search at
616                         depth           : The org depth
617                         limit           : The search limit
618                         offset  : The search offset
619                         format  : The MARC format
620                         sort            : What field to sort the results on [ author | title | pubdate ]
621                         sort_dir        : What direction do we sort? [ asc | desc ]
622                 @return An object of the form 
623                         { "count" : $count, "ids" : [ [ $id, $relevancy, $total ], ...] }
624         /
625 );
626
627 __PACKAGE__->register_method(
628         method          => 'the_quest_for_knowledge',
629         api_name                => 'open-ils.search.biblio.multiclass.staff',
630         signature       => q/@see open-ils.search.biblio.multiclass/);
631 __PACKAGE__->register_method(
632         method          => 'the_quest_for_knowledge',
633         api_name                => 'open-ils.search.metabib.multiclass',
634         signature       => q/@see open-ils.search.biblio.multiclass/);
635 __PACKAGE__->register_method(
636         method          => 'the_quest_for_knowledge',
637         api_name                => 'open-ils.search.metabib.multiclass.staff',
638         signature       => q/@see open-ils.search.biblio.multiclass/);
639
640 sub the_quest_for_knowledge {
641         my( $self, $conn, $searchhash, $docache ) = @_;
642
643         return { count => 0 } unless $searchhash and
644                 ref $searchhash->{searches} eq 'HASH';
645
646         my $method = 'open-ils.storage.biblio.multiclass.search_fts';
647         my $ismeta = 0;
648         my @recs;
649
650         if($self->api_name =~ /metabib/) {
651                 $ismeta = 1;
652                 $method =~ s/biblio/metabib/o;
653         }
654
655
656         my $offset      = $searchhash->{offset} || 0;
657         my $limit       = $searchhash->{limit} || 10;
658         my $end         = $offset + $limit - 1;
659
660         # do some simple sanity checking
661         if(!$searchhash->{searches} or
662                 ( !grep { /^(?:title|author|subject|series|keyword)/ } keys %{$searchhash->{searches}} ) ) {
663                 return { count => 0 };
664         }
665
666
667         my $maxlimit = 5000;
668         $searchhash->{offset}   = 0;
669         $searchhash->{limit}            = $maxlimit;
670
671         return { count => 0 } if $offset > $maxlimit;
672
673         my @search;
674         push( @search, ($_ => $$searchhash{$_})) for (sort keys %$searchhash);
675         my $s = OpenSRF::Utils::JSON->perl2JSON(\@search);
676         my $ckey = $pfx . md5_hex($method . $s);
677
678         $logger->info("bib search for: $s");
679
680         $searchhash->{limit} -= $offset;
681
682
683     my $trim = 0;
684         my $result = ($docache) ? search_cache($ckey, $offset, $limit) : undef;
685
686         if(!$result) {
687
688                 $method .= ".staff" if($self->api_name =~ /staff/);
689                 $method .= ".atomic";
690         
691                 for (keys %$searchhash) { 
692                         delete $$searchhash{$_} 
693                                 unless defined $$searchhash{$_}; 
694                 }
695         
696                 $result = $U->storagereq( $method, %$searchhash );
697         $trim = 1;
698
699         } else { 
700                 $docache = 0; 
701         }
702
703         return {count => 0} unless ($result && $$result[0]);
704
705         @recs = @$result;
706
707         my $count = ($ismeta) ? $result->[0]->[3] : $result->[0]->[2];
708
709         if($docache) {
710                 # If we didn't get this data from the cache, put it into the cache
711                 # then return the correct offset of records
712                 $logger->debug("putting search cache $ckey\n");
713                 put_cache($ckey, $count, \@recs);
714         }
715
716     if($trim) {
717         # if we have the full set of data, trim out 
718         # the requested chunk based on limit and offset
719         my @t;
720         for ($offset..$end) {
721             last unless $recs[$_];
722             push(@t, $recs[$_]);
723         }
724         @recs = @t;
725     }
726
727         return { ids => \@recs, count => $count };
728 }
729
730
731 __PACKAGE__->register_method(
732         method          => 'staged_search',
733         api_name        => 'open-ils.search.biblio.multiclass.staged');
734 __PACKAGE__->register_method(
735         method          => 'staged_search',
736         api_name        => 'open-ils.search.biblio.multiclass.staged.staff',
737         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
738 __PACKAGE__->register_method(
739         method          => 'staged_search',
740         api_name        => 'open-ils.search.metabib.multiclass.staged',
741         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
742 __PACKAGE__->register_method(
743         method          => 'staged_search',
744         api_name        => 'open-ils.search.metabib.multiclass.staged.staff',
745         signature       => q/@see open-ils.search.biblio.multiclass.staged/);
746
747 my $PAGE_SIZE = 1000;
748 my $SEARCH_PAGES = 25;
749 sub staged_search {
750         my($self, $conn, $search_hash, $docache) = @_;
751
752     my $method = ($self->api_name =~ /metabib/) ?
753         'open-ils.storage.metabib.multiclass.staged.search_fts':
754         'open-ils.storage.biblio.multiclass.staged.search_fts';
755
756     $method .= '.staff' if $self->api_name =~ /staff$/;
757     $method .= '.atomic';
758
759     my $user_offset = $search_hash->{offset} || 0; # user-specified offset
760     my $user_limit = $search_hash->{limit} || 10;
761     $user_offset = ($user_offset >= 0) ? $user_offset : 0;
762     $user_limit = ($user_limit >= 0) ? $user_limit : 10;
763
764
765     # we're grabbing results on a per-superpage basis, which means the 
766     # limit and offset should coincide with superpage boundaries
767     $search_hash->{offset} = 0;
768     $search_hash->{limit} = $PAGE_SIZE;
769     $search_hash->{check_limit} = $PAGE_SIZE; # force a well-known check_limit
770
771     # pull any existing results from the cache
772     my $key = search_cache_key($method, $search_hash);
773     my $cache_data = $cache->get_cache($key) || {};
774
775     # keep retrieving results until we find enough to 
776     # fulfill the user-specified limit and offset
777     my $all_results = [];
778     my $page; # current superpage
779     my $est_hit_count = 0;
780
781     for($page = 0; $page < $SEARCH_PAGES; $page++) {
782
783         my $data = $cache_data->{$page};
784         my $results;
785         my $summary;
786
787         $logger->debug("staged search: analyzing superpage $page");
788
789         if($data) {
790             # this window of results is already cached
791             $logger->debug("staged search: found cached results");
792             $summary = $data->{summary};
793             $results = $data->{results};
794
795         } else {
796             # retrieve the window of results from the database
797             $logger->debug("staged search: fetching results from the database");
798             $search_hash->{skip_check} = $page * $PAGE_SIZE;
799             my $start = time;
800             $results = $U->storagereq($method, %$search_hash);
801             $logger->info("staged search: DB call took ".(time - $start)." seconds");
802             $summary = shift(@$results);
803
804             # Create backwards-compatible result structures
805             if($self->api_name =~ /biblio/) {
806                 $results = [map {[$_->{id}]} @$results];
807             } else {
808                 $results = [map {[$_->{id}, $_->{rel}, $_->{record}]} @$results];
809             }
810
811             $results = [grep {defined $_->[0]} @$results];
812             cache_staged_search_page($key, $page, $summary, $results) if $docache;
813         }
814
815         # add the new set of results to the set under construction
816         push(@$all_results, @$results);
817
818         my $current_count = scalar(@$all_results);
819
820         $est_hit_count = $summary->{estimated_hit_count} || $summary->{visible}
821             if $page == 0;
822
823         $logger->debug("staged search: located $current_count, with estimated hits=".
824             $summary->{estimated_hit_count}." : visible=".$summary->{visible}.", checked=".$summary->{checked});
825
826         # we've found all the possible hits
827         last if $current_count == $summary->{visible}
828             and not defined $summary->{estimated_hit_count};
829
830         # we've found enough results to satisfy the requested limit/offset
831         last if $current_count >= ($user_limit + $user_offset);
832
833         # we've scanned all possible hits
834         last if $summary->{checked} < $PAGE_SIZE;
835     }
836
837     my @results = grep {defined $_} @$all_results[$user_offset..($user_offset + $user_limit - 1)];
838
839     return {
840         count => $est_hit_count,
841         ids => \@results
842     };
843 }
844
845 # creates a unique token to represent the query in the cache
846 sub search_cache_key {
847     my $method = shift;
848     my $search_hash = shift;
849         my @sorted;
850     for my $key (sort keys %$search_hash) {
851             push(@sorted, ($key => $$search_hash{$key})) 
852             unless $key eq 'limit' or 
853                 $key eq 'offset' or 
854                 $key eq 'skip_check';
855     }
856         my $s = OpenSRF::Utils::JSON->perl2JSON(\@sorted);
857         return $pfx . md5_hex($method . $s);
858 }
859
860 sub cache_staged_search_page {
861     # puts this set of results into the cache
862     my($key, $page, $summary, $results) = @_;
863     my $data = $cache->get_cache($key);
864     $data ||= {};
865     $data->{$page} = {
866         summary => $summary,
867         results => $results
868     };
869
870     $logger->info("staged search: cached with key=$key, superpage=$page, estimated=".
871         $summary->{estimated_hit_count}.", visible=".$summary->{visible});
872
873     $cache->put_cache($key, $data);
874 }
875
876 sub search_cache {
877
878         my $key         = shift;
879         my $offset      = shift;
880         my $limit       = shift;
881         my $start       = $offset;
882         my $end         = $offset + $limit - 1;
883
884         $logger->debug("searching cache for $key : $start..$end\n");
885
886         return undef unless $cache;
887         my $data = $cache->get_cache($key);
888
889         return undef unless $data;
890
891         my $count = $data->[0];
892         $data = $data->[1];
893
894         return undef unless $offset < $count;
895
896         my @result;
897         for( my $i = $offset; $i <= $end; $i++ ) {
898                 last unless my $d = $$data[$i];
899                 push( @result, $d );
900         }
901
902         $logger->debug("search_cache found ".scalar(@result)." items for count=$count, start=$start, end=$end");
903
904         return \@result;
905 }
906
907
908 sub put_cache {
909         my( $key, $count, $data ) = @_;
910         return undef unless $cache;
911         $logger->debug("search_cache putting ".
912                 scalar(@$data)." items at key $key with timeout $cache_timeout");
913         $cache->put_cache($key, [ $count, $data ], $cache_timeout);
914 }
915
916
917
918
919
920
921 __PACKAGE__->register_method(
922         method  => "biblio_mrid_to_modsbatch_batch",
923         api_name        => "open-ils.search.biblio.metarecord.mods_slim.batch.retrieve");
924
925 sub biblio_mrid_to_modsbatch_batch {
926         my( $self, $client, $mrids) = @_;
927         warn "Performing mrid_to_modsbatch_batch...";
928         my @mods;
929         my $method = $self->method_lookup("open-ils.search.biblio.metarecord.mods_slim.retrieve");
930         for my $id (@$mrids) {
931                 next unless defined $id;
932                 my ($m) = $method->run($id);
933                 push @mods, $m;
934         }
935         return \@mods;
936 }
937
938
939 __PACKAGE__->register_method(
940         method  => "biblio_mrid_to_modsbatch",
941         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve",
942         notes           => <<"  NOTES");
943         Returns the mvr associated with a given metarecod. If none exists, 
944         it is created.
945         NOTES
946
947 __PACKAGE__->register_method(
948         method  => "biblio_mrid_to_modsbatch",
949         api_name        => "open-ils.search.biblio.metarecord.mods_slim.retrieve.staff",
950         notes           => <<"  NOTES");
951         Returns the mvr associated with a given metarecod. If none exists, 
952         it is created.
953         NOTES
954
955 sub biblio_mrid_to_modsbatch {
956         my( $self, $client, $mrid, $args) = @_;
957
958         warn "Grabbing mvr for $mrid\n";
959
960         my ($mr, $evt) = _grab_metarecord($mrid);
961         return $evt unless $mr;
962
963         my $mvr = biblio_mrid_check_mvr($self, $client, $mr);
964         $mvr = biblio_mrid_make_modsbatch( $self, $client, $mr ) unless $mvr;
965
966         return $mvr unless ref($args);  
967
968         # Here we find the lead record appropriate for the given filters 
969         # and use that for the title and author of the metarecord
970         my $format      = $$args{format};
971         my $org         = $$args{org};
972         my $depth       = $$args{depth};
973
974         return $mvr unless $format or $org or $depth;
975
976         my $method = "open-ils.storage.ordered.metabib.metarecord.records";
977         $method = "$method.staff" if $self->api_name =~ /staff/o; 
978
979         my $rec = $U->storagereq($method, $format, $org, $depth, 1);
980
981         if( my $mods = $U->record_to_mvr($rec) ) {
982
983                 $mvr->title($mods->title);
984                 $mvr->title($mods->author);
985                 $logger->debug("mods_slim updating title and ".
986                         "author in mvr with ".$mods->title." : ".$mods->author);
987         }
988
989         return $mvr;
990 }
991
992 # converts a metarecord to an mvr
993 sub _mr_to_mvr {
994         my $mr = shift;
995         my $perl = OpenSRF::Utils::JSON->JSON2perl($mr->mods());
996         return Fieldmapper::metabib::virtual_record->new($perl);
997 }
998
999 # checks to see if a metarecord has mods, if so returns true;
1000
1001 __PACKAGE__->register_method(
1002         method  => "biblio_mrid_check_mvr",
1003         api_name        => "open-ils.search.biblio.metarecord.mods_slim.check",
1004         notes           => <<"  NOTES");
1005         Takes a metarecord ID or a metarecord object and returns true
1006         if the metarecord already has an mvr associated with it.
1007         NOTES
1008
1009 sub biblio_mrid_check_mvr {
1010         my( $self, $client, $mrid ) = @_;
1011         my $mr; 
1012
1013         my $evt;
1014         if(ref($mrid)) { $mr = $mrid; } 
1015         else { ($mr, $evt) = _grab_metarecord($mrid); }
1016         return $evt if $evt;
1017
1018         warn "Checking mvr for mr " . $mr->id . "\n";
1019
1020         return _mr_to_mvr($mr) if $mr->mods();
1021         return undef;
1022 }
1023
1024 sub _grab_metarecord {
1025         my $mrid = shift;
1026         #my $e = OpenILS::Utils::Editor->new;
1027         my $e = new_editor();
1028         my $mr = $e->retrieve_metabib_metarecord($mrid) or return ( undef, $e->event );
1029         return ($mr);
1030 }
1031
1032
1033 __PACKAGE__->register_method(
1034         method  => "biblio_mrid_make_modsbatch",
1035         api_name        => "open-ils.search.biblio.metarecord.mods_slim.create",
1036         notes           => <<"  NOTES");
1037         Takes either a metarecord ID or a metarecord object.
1038         Forces the creations of an mvr for the given metarecord.
1039         The created mvr is returned.
1040         NOTES
1041
1042 sub biblio_mrid_make_modsbatch {
1043         my( $self, $client, $mrid ) = @_;
1044
1045         #my $e = OpenILS::Utils::Editor->new;
1046         my $e = new_editor();
1047
1048         my $mr;
1049         if( ref($mrid) ) {
1050                 $mr = $mrid;
1051                 $mrid = $mr->id;
1052         } else {
1053                 $mr = $e->retrieve_metabib_metarecord($mrid) 
1054                         or return $e->event;
1055         }
1056
1057         my $masterid = $mr->master_record;
1058         $logger->info("creating new mods batch for metarecord=$mrid, master record=$masterid");
1059
1060         my $ids = $U->storagereq(
1061                 'open-ils.storage.ordered.metabib.metarecord.records.staff.atomic', $mrid);
1062         return undef unless @$ids;
1063
1064         my $master = $e->retrieve_biblio_record_entry($masterid)
1065                 or return $e->event;
1066
1067         # start the mods batch
1068         my $u = OpenILS::Utils::ModsParser->new();
1069         $u->start_mods_batch( $master->marc );
1070
1071         # grab all of the sub-records and shove them into the batch
1072         my @ids = grep { $_ ne $masterid } @$ids;
1073         #my $subrecs = (@ids) ? $e->batch_retrieve_biblio_record_entry(\@ids) : [];
1074
1075         my $subrecs = [];
1076         if(@$ids) {
1077                 for my $i (@$ids) {
1078                         my $r = $e->retrieve_biblio_record_entry($i);
1079                         push( @$subrecs, $r ) if $r;
1080                 }
1081         }
1082
1083         for(@$subrecs) {
1084                 $logger->debug("adding record ".$_->id." to mods batch for metarecord=$mrid");
1085                 $u->push_mods_batch( $_->marc ) if $_->marc;
1086         }
1087
1088
1089         # finish up and send to the client
1090         my $mods = $u->finish_mods_batch();
1091         $mods->doc_id($mrid);
1092         $client->respond_complete($mods);
1093
1094
1095         # now update the mods string in the db
1096         my $string = OpenSRF::Utils::JSON->perl2JSON($mods->decast);
1097         $mr->mods($string);
1098
1099         #$e = OpenILS::Utils::Editor->new(xact => 1);
1100         $e = new_editor(xact => 1);
1101         $e->update_metabib_metarecord($mr) 
1102                 or $logger->error("Error setting mods text on metarecord $mrid : " . Dumper($e->event));
1103         $e->finish;
1104
1105         return undef;
1106 }
1107
1108
1109
1110
1111 # converts a mr id into a list of record ids
1112
1113 __PACKAGE__->register_method(
1114         method  => "biblio_mrid_to_record_ids",
1115         api_name        => "open-ils.search.biblio.metarecord_to_records",
1116 );
1117
1118 __PACKAGE__->register_method(
1119         method  => "biblio_mrid_to_record_ids",
1120         api_name        => "open-ils.search.biblio.metarecord_to_records.staff",
1121 );
1122
1123 sub biblio_mrid_to_record_ids {
1124         my( $self, $client, $mrid, $args ) = @_;
1125
1126         my $format      = $$args{format};
1127         my $org         = $$args{org};
1128         my $depth       = $$args{depth};
1129
1130         my $method = "open-ils.storage.ordered.metabib.metarecord.records.atomic";
1131         $method =~ s/atomic/staff\.atomic/o if $self->api_name =~ /staff/o; 
1132         my $recs = $U->storagereq($method, $mrid, $format, $org, $depth);
1133
1134         return { count => scalar(@$recs), ids => $recs };
1135 }
1136
1137
1138 __PACKAGE__->register_method(
1139         method  => "biblio_record_to_marc_html",
1140         api_name        => "open-ils.search.biblio.record.html" );
1141
1142 my $parser              = XML::LibXML->new();
1143 my $xslt                        = XML::LibXSLT->new();
1144 my $marc_sheet;
1145
1146 my $settings_client = OpenSRF::Utils::SettingsClient->new();
1147 sub biblio_record_to_marc_html {
1148         my( $self, $client, $recordid ) = @_;
1149
1150         if( !$marc_sheet ) {
1151                 my $dir = $settings_client->config_value( "dirs", "xsl" );
1152                 my $xsl = $settings_client->config_value(
1153                         "apps", "open-ils.search", "app_settings", "marc_html_xsl" );
1154
1155                 $xsl = $parser->parse_file("$dir/$xsl");
1156                 $marc_sheet = $xslt->parse_stylesheet( $xsl );
1157         }
1158
1159
1160         my $record = $apputils->simple_scalar_request(
1161                 "open-ils.cstore", 
1162                 "open-ils.cstore.direct.biblio.record_entry.retrieve",
1163                 $recordid );
1164
1165         my $xmldoc = $parser->parse_string($record->marc);
1166         my $html = $marc_sheet->transform($xmldoc);
1167         $html = $html->toString();
1168         return $html;
1169
1170 }
1171
1172
1173 =head duplicate
1174 __PACKAGE__->register_method(
1175         method  => "retrieve_all_copy_locations",
1176         api_name        => "open-ils.search.config.copy_location.retrieve.all" );
1177
1178 my $shelving_locations;
1179 sub retrieve_all_copy_locations {
1180         my( $self, $client ) = @_;
1181         if(!$shelving_locations) {
1182                 $shelving_locations = $apputils->simple_scalar_request(
1183                         "open-ils.cstore", 
1184                         "open-ils.cstore.direct.asset.copy_location.search.atomic",
1185                         { id => { "!=" => undef } }
1186                 );
1187         }
1188         return $shelving_locations;
1189 }
1190 =cut
1191
1192
1193
1194 __PACKAGE__->register_method(
1195         method  => "retrieve_all_copy_statuses",
1196         api_name        => "open-ils.search.config.copy_status.retrieve.all" );
1197
1198 my $copy_statuses;
1199 sub retrieve_all_copy_statuses {
1200         my( $self, $client ) = @_;
1201         return $copy_statuses if $copy_statuses;
1202         return $copy_statuses = 
1203                 new_editor()->retrieve_all_config_copy_status();
1204 }
1205
1206
1207 __PACKAGE__->register_method(
1208         method  => "copy_counts_per_org",
1209         api_name        => "open-ils.search.biblio.copy_counts.retrieve");
1210
1211 __PACKAGE__->register_method(
1212         method  => "copy_counts_per_org",
1213         api_name        => "open-ils.search.biblio.copy_counts.retrieve.staff");
1214
1215 sub copy_counts_per_org {
1216         my( $self, $client, $record_id ) = @_;
1217
1218         warn "Retreiveing copy copy counts for record $record_id and method " . $self->api_name . "\n";
1219
1220         my $method = "open-ils.storage.biblio.record_entry.global_copy_count.atomic";
1221         if($self->api_name =~ /staff/) { $method =~ s/atomic/staff\.atomic/; }
1222
1223         my $counts = $apputils->simple_scalar_request(
1224                 "open-ils.storage", $method, $record_id );
1225
1226         $counts = [ sort {$a->[0] <=> $b->[0]} @$counts ];
1227         return $counts;
1228 }
1229
1230
1231 __PACKAGE__->register_method(
1232         method          => "copy_count_summary",
1233         api_name        => "open-ils.search.biblio.copy_counts.summary.retrieve",
1234         notes           => <<"  NOTES");
1235         returns an array of these:
1236                 [ org_id, callnumber_label, <status1_count>, <status2_cout>,...]
1237                 where statusx is a copy status name.  the statuses are sorted
1238                 by id.
1239         NOTES
1240
1241 sub copy_count_summary {
1242         my( $self, $client, $rid, $org, $depth ) = @_;
1243         $org ||= 1;
1244         $depth ||= 0;
1245     my $data = $U->storagereq(
1246                 'open-ils.storage.biblio.record_entry.status_copy_count.atomic', $rid, $org, $depth );
1247
1248     return [ sort { $a->[1] cmp $b->[1] } @$data ];
1249 }
1250
1251
1252
1253 =head
1254 __PACKAGE__->register_method(
1255         method          => "multiclass_search",
1256         api_name        => "open-ils.search.biblio.multiclass",
1257         notes           => <<"  NOTES");
1258                 Performs a multiclass search
1259                 PARAMS( searchBlob, org_unit, format, limit ) 
1260                 where searchBlob is defined like this:
1261                         { 
1262                                 "title" : { "term" : "water" }, 
1263                                 "author" : { "term" : "smith" }, 
1264                                 ... 
1265                         }
1266         NOTES
1267
1268 __PACKAGE__->register_method(
1269         method          => "multiclass_search",
1270         api_name        => "open-ils.search.biblio.multiclass.staff",
1271         notes           => "see open-ils.search.biblio.multiclass" );
1272
1273 sub multiclass_search {
1274         my( $self, $client, $searchBlob, $orgid, $format, $limit ) = @_;
1275
1276         $logger->debug("Performing multiclass search with org => $orgid, " .
1277                 "format => $format, limit => $limit, and search blob " . Dumper($searchBlob));
1278
1279         my $meth = 'open-ils.storage.metabib.post_filter.multiclass.search_fts.metarecord.atomic';
1280         if($self->api_name =~ /staff/) { $meth =~ s/metarecord\.atomic/metarecord.staff.atomic/; }
1281
1282
1283         my $records = $apputils->simplereq(
1284                 'open-ils.storage', $meth, 
1285                  org_unit => $orgid, searches => $searchBlob, format => $format, limit => $limit );
1286
1287         my $count = 0;
1288         my $recs = [];
1289
1290         if( ref($records) and $records->[0] and 
1291                 defined($records->[0]->[3])) { $count = $records->[0]->[3];}
1292
1293         for my $r (@$records) { push( @$recs, $r ) if ($r and $r->[0]); }
1294
1295         # records has the form: [ mrid, rank, singleRecord / 0, hitCount ];
1296         return { ids => $recs, count => $count };
1297 }
1298 =cut
1299
1300
1301 =head comment-1
1302 __PACKAGE__->register_method(
1303         method          => "multiclass_search",
1304         api_name                => "open-ils.search.biblio.multiclass",
1305         signature       => q/
1306                 Performs a multiclass search
1307                 @param args A names hash of arguments:
1308                         org_unit : The org to focus the search on
1309                         depth           : The search depth
1310                         format  : Item format
1311                         limit           : Return limit
1312                         offset  : Search offset
1313                         searches : A named hash of searches which has the following format:
1314                                 { 
1315                                         "title" : { "term" : "water" }, 
1316                                         "author" : { "term" : "smith" }, 
1317                                         ... 
1318                                 }
1319                 @return { ids : <array of ids>, count : hitcount }
1320         /
1321 );
1322
1323 __PACKAGE__->register_method(
1324         method          => "multiclass_search",
1325         api_name                => "open-ils.search.biblio.multiclass.staff",
1326         notes           => q/@see open-ils.search.biblio.multiclass/ );
1327
1328 sub multiclass_search {
1329         my( $self, $client, $args ) = @_;
1330
1331         $logger->debug("Performing multiclass search with args:\n" . Dumper($args));
1332         my $meth = 'open-ils.storage.metabib.post_filter.multiclass.search_fts.metarecord.atomic';
1333         if($self->api_name =~ /staff/) { $meth =~ s/metarecord\.atomic/metarecord.staff.atomic/; }
1334
1335         my $records = $apputils->simplereq( 'open-ils.storage', $meth, %$args );
1336
1337         my $count = 0;
1338         my $recs = [];
1339
1340         if( ref($records) and $records->[0] and 
1341                 defined($records->[0]->[3])) { $count = $records->[0]->[3];}
1342
1343         for my $r (@$records) { push( @$recs, $r ) if ($r and $r->[0]); }
1344
1345         return { ids => $recs, count => $count };
1346 }
1347
1348 =cut
1349
1350
1351
1352 __PACKAGE__->register_method(
1353         method          => "marc_search",
1354         api_name        => "open-ils.search.biblio.marc.staff");
1355
1356 __PACKAGE__->register_method(
1357         method          => "marc_search",
1358         api_name        => "open-ils.search.biblio.marc",
1359         notes           => <<"  NOTES");
1360                 Example:
1361                 open-ils.storage.biblio.full_rec.multi_search.atomic 
1362                 { "searches": [{"term":"harry","restrict": [{"tag":245,"subfield":"a"}]}], "org_unit": 1,
1363         "limit":5,"sort":"author","item_type":"g"}
1364         NOTES
1365
1366 sub marc_search {
1367         my( $self, $conn, $args, $limit, $offset ) = @_;
1368
1369         my $method = 'open-ils.storage.biblio.full_rec.multi_search';
1370         $method .= ".staff" if $self->api_name =~ /staff/;
1371         $method .= ".atomic";
1372
1373         $limit ||= 10;
1374         $offset ||= 0;
1375
1376         my @search;
1377         push( @search, ($_ => $$args{$_}) ) for (sort keys %$args);
1378         my $ckey = $pfx . md5_hex($method . OpenSRF::Utils::JSON->perl2JSON(\@search));
1379
1380         my $recs = search_cache($ckey, $offset, $limit);
1381
1382         if(!$recs) {
1383                 $recs = $U->storagereq($method, %$args) || [];
1384                 if( $recs ) {
1385                         put_cache($ckey, scalar(@$recs), $recs);
1386                         $recs = [ @$recs[$offset..($offset + ($limit - 1))] ];
1387                 } else {
1388                         $recs = [];
1389                 }
1390         }
1391
1392         my $count = 0;
1393         $count = $recs->[0]->[2] if $recs->[0] and $recs->[0]->[2];
1394         my @recs = map { $_->[0] } @$recs;
1395
1396         return { ids => \@recs, count => $count };
1397 }
1398
1399
1400 __PACKAGE__->register_method(
1401         method  => "biblio_search_isbn",
1402         api_name        => "open-ils.search.biblio.isbn",
1403 );
1404
1405 sub biblio_search_isbn { 
1406         my( $self, $client, $isbn ) = @_;
1407         $logger->debug("Searching ISBN $isbn");
1408         my $e = new_editor();
1409         my $recs = $U->storagereq(
1410                 'open-ils.storage.id_list.biblio.record_entry.search.isbn.atomic', $isbn );
1411         return { ids => $recs, count => scalar(@$recs) };
1412 }
1413
1414
1415 __PACKAGE__->register_method(
1416         method  => "biblio_search_issn",
1417         api_name        => "open-ils.search.biblio.issn",
1418 );
1419
1420 sub biblio_search_issn { 
1421         my( $self, $client, $issn ) = @_;
1422         $logger->debug("Searching ISSN $issn");
1423         my $e = new_editor();
1424         my $recs = $U->storagereq(
1425                 'open-ils.storage.id_list.biblio.record_entry.search.issn.atomic', $issn );
1426         return { ids => $recs, count => scalar(@$recs) };
1427 }
1428
1429
1430
1431
1432 __PACKAGE__->register_method(
1433         method  => "fetch_mods_by_copy",
1434         api_name        => "open-ils.search.biblio.mods_from_copy",
1435 );
1436
1437 sub fetch_mods_by_copy {
1438         my( $self, $client, $copyid ) = @_;
1439         my ($record, $evt) = $apputils->fetch_record_by_copy( $copyid );
1440         return $evt if $evt;
1441         return OpenILS::Event->new('ITEM_NOT_CATALOGED') unless $record->marc;
1442         return $apputils->record_to_mvr($record);
1443 }
1444
1445
1446
1447 # -------------------------------------------------------------------------------------
1448
1449 __PACKAGE__->register_method(
1450         method  => "cn_browse",
1451         api_name        => "open-ils.search.callnumber.browse.target",
1452         notes           => "Starts a callnumber browse"
1453         );
1454
1455 __PACKAGE__->register_method(
1456         method  => "cn_browse",
1457         api_name        => "open-ils.search.callnumber.browse.page_up",
1458         notes           => "Returns the previous page of callnumbers", 
1459         );
1460
1461 __PACKAGE__->register_method(
1462         method  => "cn_browse",
1463         api_name        => "open-ils.search.callnumber.browse.page_down",
1464         notes           => "Returns the next page of callnumbers", 
1465         );
1466
1467
1468 # RETURNS array of arrays like so: label, owning_lib, record, id
1469 sub cn_browse {
1470         my( $self, $client, @params ) = @_;
1471         my $method;
1472
1473         $method = 'open-ils.storage.asset.call_number.browse.target.atomic' 
1474                 if( $self->api_name =~ /target/ );
1475         $method = 'open-ils.storage.asset.call_number.browse.page_up.atomic'
1476                 if( $self->api_name =~ /page_up/ );
1477         $method = 'open-ils.storage.asset.call_number.browse.page_down.atomic'
1478                 if( $self->api_name =~ /page_down/ );
1479
1480         return $apputils->simplereq( 'open-ils.storage', $method, @params );
1481 }
1482 # -------------------------------------------------------------------------------------
1483
1484 __PACKAGE__->register_method(
1485         method => "fetch_cn",
1486     authoritative => 1,
1487         api_name => "open-ils.search.callnumber.retrieve",
1488         notes           => "retrieves a callnumber based on ID",
1489         );
1490
1491 sub fetch_cn {
1492         my( $self, $client, $id ) = @_;
1493         my( $cn, $evt ) = $apputils->fetch_callnumber( $id );
1494         return $evt if $evt;
1495         return $cn;
1496 }
1497
1498 __PACKAGE__->register_method (
1499         method          => "fetch_copy_by_cn",
1500         api_name                => 'open-ils.search.copies_by_call_number.retrieve',
1501         signature       => q/
1502                 Returns an array of copy id's by callnumber id
1503                 @param cnid The callnumber id
1504                 @return An array of copy ids
1505         /
1506 );
1507
1508 sub fetch_copy_by_cn {
1509         my( $self, $conn, $cnid ) = @_;
1510         return $U->cstorereq(
1511                 'open-ils.cstore.direct.asset.copy.id_list.atomic', 
1512                 { call_number => $cnid, deleted => 'f' } );
1513 }
1514
1515 __PACKAGE__->register_method (
1516         method          => 'fetch_cn_by_info',
1517         api_name                => 'open-ils.search.call_number.retrieve_by_info',
1518         signature       => q/
1519                 @param label The callnumber label
1520                 @param record The record the cn is attached to
1521                 @param org The owning library of the cn
1522                 @return The callnumber object
1523         /
1524 );
1525
1526
1527 sub fetch_cn_by_info {
1528         my( $self, $conn, $label, $record, $org ) = @_;
1529         return $U->cstorereq(
1530                 'open-ils.cstore.direct.asset.call_number.search',
1531                 { label => $label, record => $record, owning_lib => $org, deleted => 'f' });
1532 }
1533
1534
1535                 
1536
1537
1538 __PACKAGE__->register_method (
1539         method => 'bib_extras',
1540         api_name => 'open-ils.search.biblio.lit_form_map.retrieve.all');
1541 __PACKAGE__->register_method (
1542         method => 'bib_extras',
1543         api_name => 'open-ils.search.biblio.item_form_map.retrieve.all');
1544 __PACKAGE__->register_method (
1545         method => 'bib_extras',
1546         api_name => 'open-ils.search.biblio.item_type_map.retrieve.all');
1547 __PACKAGE__->register_method (
1548         method => 'bib_extras',
1549         api_name => 'open-ils.search.biblio.bib_level_map.retrieve.all');
1550 __PACKAGE__->register_method (
1551         method => 'bib_extras',
1552         api_name => 'open-ils.search.biblio.audience_map.retrieve.all');
1553
1554 sub bib_extras {
1555         my $self = shift;
1556
1557         my $e = new_editor();
1558
1559         return $e->retrieve_all_config_lit_form_map()
1560                 if( $self->api_name =~ /lit_form/ );
1561
1562         return $e->retrieve_all_config_item_form_map()
1563                 if( $self->api_name =~ /item_form_map/ );
1564
1565         return $e->retrieve_all_config_item_type_map()
1566                 if( $self->api_name =~ /item_type_map/ );
1567
1568         return $e->retrieve_all_config_bib_level_map()
1569                 if( $self->api_name =~ /bib_level_map/ );
1570
1571         return $e->retrieve_all_config_audience_map()
1572                 if( $self->api_name =~ /audience_map/ );
1573
1574         return [];
1575 }
1576
1577
1578
1579 __PACKAGE__->register_method(
1580         method  => 'fetch_slim_record',
1581         api_name        => 'open-ils.search.biblio.record_entry.slim.retrieve',
1582         signature=> q/
1583                 Returns a biblio.record_entry without the attached marcxml
1584         /
1585 );
1586
1587 sub fetch_slim_record {
1588         my( $self, $conn, $ids ) = @_;
1589
1590         #my $editor = OpenILS::Utils::Editor->new;
1591         my $editor = new_editor();
1592         my @res;
1593         for( @$ids ) {
1594                 return $editor->event unless
1595                         my $r = $editor->retrieve_biblio_record_entry($_);
1596                 $r->clear_marc;
1597                 push(@res, $r);
1598         }
1599         return \@res;
1600 }
1601
1602
1603
1604 __PACKAGE__->register_method(
1605         method => 'rec_to_mr_rec_descriptors',
1606         api_name        => 'open-ils.search.metabib.record_to_descriptors',
1607         signature       => q/
1608                 specialized method...
1609                 Given a biblio record id or a metarecord id, 
1610                 this returns a list of metabib.record_descriptor
1611                 objects that live within the same metarecord
1612                 @param args Object of args including:
1613         /
1614 );
1615
1616 sub rec_to_mr_rec_descriptors {
1617         my( $self, $conn, $args ) = @_;
1618
1619         my $rec = $$args{record};
1620         my $mrec        = $$args{metarecord};
1621         my $item_forms = $$args{item_forms};
1622         my $item_types  = $$args{item_types};
1623         my $item_lang   = $$args{item_lang};
1624
1625         my $e = new_editor();
1626         my $recs;
1627
1628         if( !$mrec ) {
1629                 my $map = $e->search_metabib_metarecord_source_map({source => $rec});
1630                 return $e->event unless @$map;
1631                 $mrec = $$map[0]->metarecord;
1632         }
1633
1634         $recs = $e->search_metabib_metarecord_source_map({metarecord => $mrec});
1635         return $e->event unless @$recs;
1636
1637         my @recs = map { $_->source } @$recs;
1638         my $search = { record => \@recs };
1639         $search->{item_form} = $item_forms if $item_forms and @$item_forms;
1640         $search->{item_type} = $item_types if $item_types and @$item_types;
1641         $search->{item_lang} = $item_lang if $item_lang;
1642
1643         my $desc = $e->search_metabib_record_descriptor($search);
1644
1645         return { metarecord => $mrec, descriptors => $desc };
1646 }
1647
1648
1649
1650
1651 __PACKAGE__->register_method(
1652         method => 'copies_created_on',  
1653 );
1654
1655
1656 sub copies_created_on {
1657         my( $self, $conn, $auth, $org, $date ) = @_;
1658         my $e = new_editor(authtoken=>$auth);
1659         return $e->event unless $e->checkauth;
1660 }
1661
1662
1663 __PACKAGE__->register_method(
1664         method => 'fetch_age_protect',
1665         api_name => 'open-ils.search.copy.age_protect.retrieve.all',
1666 );
1667
1668 sub fetch_age_protect {
1669         return new_editor()->retrieve_all_config_rule_age_hold_protect();
1670 }
1671
1672
1673 __PACKAGE__->register_method(
1674         method => 'copies_by_cn_label',
1675         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label',
1676 );
1677
1678 __PACKAGE__->register_method(
1679         method => 'copies_by_cn_label',
1680         api_name => 'open-ils.search.asset.copy.retrieve_by_cn_label.staff',
1681 );
1682
1683 sub copies_by_cn_label {
1684         my( $self, $conn, $record, $label, $circ_lib ) = @_;
1685         my $e = new_editor();
1686         my $cns = $e->search_asset_call_number({record => $record, label => $label, deleted => 'f'}, {idlist=>1});
1687         return [] unless @$cns;
1688
1689         # show all non-deleted copies in the staff client ...
1690         if ($self->api_name =~ /staff$/o) {
1691                 return $e->search_asset_copy({call_number => $cns, circ_lib => $circ_lib, deleted => 'f'}, {idlist=>1});
1692         }
1693
1694         # ... otherwise, grab the copies ...
1695         my $copies = $e->search_asset_copy(
1696                 [ {call_number => $cns, circ_lib => $circ_lib, deleted => 'f', opac_visible => 't'},
1697                   {flesh => 1, flesh_fields => { acp => [ qw/location status/] } }
1698                 ]
1699         );
1700
1701         # ... and test for location and status visibility
1702         return [ map { ($U->is_true($_->location->opac_visible) && $U->is_true($_->status->holdable)) ? ($_->id) : () } @$copies ];
1703 }
1704
1705
1706
1707 1;
1708
1709