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