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