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