3 # Copyright 2000-2002 Katipo Communications
4 # Parts Copyright 2013 Prosentient Systems
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
25 use C4::Koha qw( GetVariationsOfISBN );
26 use C4::Charset qw( MarcToUTF8Record SetUTF8Flag );
27 use MARC::File::USMARC;
29 use C4::ImportBatch qw( GetZ3950BatchId AddBiblioToBatch AddAuthToBatch );
30 use C4::AuthoritiesMarc qw( GuessAuthTypeCode );
35 our (@ISA, @EXPORT_OK);
39 @EXPORT_OK = qw(BreedingSearch Z3950Search Z3950SearchAuth);
44 C4::Breeding : module to add biblios to import_records via
45 the breeding/reservoir API.
49 Z3950Search($pars, $template);
50 ($count, @results) = &BreedingSearch($title,$isbn);
54 This module contains routines related to Koha's Z39.50 search into
55 cataloguing reservoir features.
59 ($count, @results) = &BreedingSearch($term);
60 C<$term> contains the term to search, it will be searched as title,author, or isbn
62 C<$count> is the number of items in C<@results>. C<@results> is an
63 array of references-to-hash; the keys are the items from the C<import_records> and
64 C<import_biblios> tables of the Koha database.
70 my $dbh = C4::Context->dbh;
76 my $authortitle = $term;
77 $authortitle =~ s/(\s+)/\%/g; #Replace spaces with wildcard
78 $authortitle = "%" . $authortitle . "%"; #Add wildcard to start and end of string
79 # normalise ISBN like at import
80 my @isbns = C4::Koha::GetVariationsOfISBN($term);
82 $query = "SELECT import_record_id, file_name, isbn, title, author
84 JOIN import_records USING (import_record_id)
85 JOIN import_batches USING (import_batch_id)
86 WHERE title LIKE ? OR author LIKE ? OR isbn IN (" . join(',',('?') x @isbns) . ")";
87 @bind=( $authortitle, $authortitle, @isbns );
88 $sth = $dbh->prepare($query);
90 while (my $data = $sth->fetchrow_hashref) {
91 $results[$count] = $data;
92 # FIXME - hack to reflect difference in name
93 # of columns in old marc_breeding and import_records
94 # There needs to be more separation between column names and
95 # field names used in the templates </soapbox>
96 $data->{'file'} = $data->{'file_name'};
97 $data->{'id'} = $data->{'import_record_id'};
102 return($count, @results);
103 } # sub breedingsearch
108 Z3950Search($pars, $template);
110 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
111 Also it should contain an arrayref id that points to a list of id's of the z3950 targets to be queried (see z3950servers table).
112 This code is used in acqui/z3950_search and cataloging/z3950_search.
113 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
118 my ($pars, $template)= @_;
120 my @id= @{$pars->{id}};
121 my $page= $pars->{page};
122 my $biblionumber= $pars->{biblionumber};
127 my @breeding_loop = ();
134 my ( $zquery, $squery ) = _bib_build_query( $pars );
136 my $schema = Koha::Database->new()->schema();
137 my $rs = $schema->resultset('Z3950server')->search(
139 { result_class => 'DBIx::Class::ResultClass::HashRefInflator' },
141 my @servers = $rs->all;
142 foreach my $server ( @servers ) {
143 my $server_zquery = $zquery;
144 if(my $attributes = $server->{attributes}){
145 $server_zquery = "$attributes $zquery";
147 $oConnection[$s] = _create_connection( $server );
149 $server->{servertype} eq 'zed'?
150 $oConnection[$s]->search_pqf( $server_zquery ):
151 $oConnection[$s]->search(ZOOM::Query::CQL->new(
152 _translate_query( $server, $squery )));
155 my $xslh = Koha::XSLT::Base->new;
158 while ( $nremaining-- ) {
161 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
162 $event = $oConnection[ $k - 1 ]->last_event();
163 last if $event == ZOOM::Event::ZEND;
168 my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
170 if ($error =~ m/^(10000|10007)$/ ) {
171 push(@errconn, { server => $servers[$k]->{host}, error => $error } );
175 my $numresults = $oResult[$k]->size();
178 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
179 $show_next = 1 if $numresults >= ($page*20);
180 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
181 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
182 if ( $oResult[$k]->record($i) ) {
184 ( $res, $error ) = _handle_one_result( $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, $xslh ); #ignores error in sequence numbering
185 push @breeding_loop, $res if $res;
186 push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i+1 } if $error;
189 push @errconn, { 'server' => $servers[$k]->{servername}, error => ( ( $oConnection[$k]->error_x() )[0] ), seq => $i+1 };
197 numberpending => $nremaining,
198 current_page => $page,
199 total_pages => $total_pages,
200 show_nextbutton => $show_next?1:0,
201 show_prevbutton => $page!=1,
205 #close result sets and connections
207 $oResult[$_]->destroy();
208 $oConnection[$_]->destroy();
212 breeding_loop => \@breeding_loop,
213 servers => \@servers,
218 sub _auth_build_query {
222 nameany => '@attr 1=1002 "#term" ',
223 authorany => '@attr 1=1003 "#term" ',
224 authorcorp => '@attr 1=2 "#term" ',
225 authorpersonal => '@attr 1=1 "#term" ',
226 authormeetingcon => '@attr 1=3 "#term" ',
227 subject => '@attr 1=21 "#term" ',
228 subjectsubdiv => '@attr 1=47 "#term" ',
229 title => '@attr 1=4 "#term" ',
230 uniformtitle => '@attr 1=6 "#term" ',
231 srchany => '@attr 1=1016 "#term" ',
232 controlnumber => '@attr 1=12 "#term" ',
235 return _build_query( $pars, $qry_build );
238 sub _bib_build_query {
243 isbn => '@attr 1=7 @attr 5=1 "#term" ',
244 issn => '@attr 1=8 @attr 5=1 "#term" ',
245 title => '@attr 1=4 "#term" ',
246 author => '@attr 1=1003 "#term" ',
247 dewey => '@attr 1=16 "#term" ',
248 subject => '@attr 1=21 "#term" ',
249 lccall => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
250 '@attr 6=1 "#term" ',
251 controlnumber => '@attr 1=12 "#term" ',
252 srchany => '@attr 1=1016 "#term" ',
253 stdid => '@attr 1=1007 "#term" ',
254 publicationyear => '@attr 1=31 "#term" '
257 return _build_query( $pars, $qry_build );
262 my ( $pars, $qry_build ) = @_;
267 foreach my $k ( sort keys %$pars ) {
268 #note that the sort keys forces an identical result under Perl 5.18
269 #one of the unit tests is based on that assumption
270 if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
271 $qry_build->{$k} =~ s/#term/$val/g;
272 $zquery .= $qry_build->{$k};
273 $squery .= "[$k]=\"$val\" and ";
277 $zquery = "\@and " . $zquery for 2..$nterms;
278 $squery =~ s/ and $//;
279 return ( $zquery, $squery );
282 sub _handle_one_result {
283 my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_;
285 my $raw= $zoomrec->raw();
287 if( $servhref->{servertype} eq 'sru' ) {
288 $marcrecord= MARC::Record->new_from_xml( $raw, 'UTF-8',
289 $servhref->{syntax} );
290 $marcrecord->encoding('UTF-8');
292 ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
294 SetUTF8Flag($marcrecord);
296 ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh);
298 my $batch_id = GetZ3950BatchId($servhref->{servername});
299 my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0);
300 #Last zero indicates: no update for batch record counts
303 #call to TransformMarcToKoha replaced by next call
304 #we only need six fields from the marc record
308 biblionumber => $bib,
309 server => $servhref->{servername},
310 breedingid => $breedingid,
311 }, $marcrecord) if $breedingid;
312 return ( $row, $error );
316 my ( $marc, $server, $xslh ) = @_;
317 return $marc if !$server->{add_xslt};
319 my $htdocs = C4::Context->config('intrahtdocs');
320 my $theme = C4::Context->preference("template"); #staff
321 my $lang = C4::Languages::getlanguage() || 'en';
323 my @files= split ',', $server->{add_xslt};
324 my $xml = $marc->as_xml;
325 foreach my $f ( @files ) {
326 $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
327 $f = C4::XSLT::_get_best_default_xslt_filename(
328 $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
329 $xml = $xslh->transform( $xml, $f );
330 last if $xslh->err; #skip other files
333 return MARC::Record->new_from_xml($xml, 'UTF-8');
335 return ( $marc, $xslh->err ); #original record in case of errors
340 my ($row, $record)=@_;
342 title => 'biblio.title',
343 author => 'biblio.author',
344 isbn =>'biblioitems.isbn',
345 lccn =>'biblioitems.lccn', #LC control number (not call number)
346 edition =>'biblioitems.editionstatement'
348 $fetch{date} = C4::Context->preference('marcflavour') eq "MARC21" ? 'biblio.copyrightdate' : 'biblioitems.publicationyear';
350 foreach my $k (keys %fetch) {
351 $row->{$k} = C4::Biblio::TransformMarcToKohaOneField( $fetch{$k}, $record );
353 $row->{date}//= $row->{date2};
354 $row->{isbn}=_isbn_replace($row->{isbn});
356 $row = _add_custom_field_rowdata($row, $record);
361 sub _add_custom_field_rowdata
363 my ( $row, $record ) = @_;
364 my $pref_newtags = C4::Context->preference('AdditionalFieldsInZ3950ResultSearch');
365 my $pref_flavour = C4::Context->preference('MarcFlavour');
367 $pref_newtags =~ s/^\s+|\s+$//g;
368 $pref_newtags =~ s/\h+/ /g;
372 foreach my $field (split /\,/, $pref_newtags) {
373 $field =~ s/^\s+|\s+$//g ; # trim whitespace
374 my ($tag, $subtags) = split(/\$/, $field);
376 if ( $record->field($tag) ) {
379 for my $marcfield ($record->field($tag)) {
382 for my $code (split //, $subtags) {
383 if ( $marcfield->subfield($code) ) {
384 $str .= $marcfield->subfield($code) . ' ';
387 if ( not $str eq '') {
390 } elsif ( $tag == 10 ) {
391 push @content, ( $pref_flavour eq "MARC21" ? $marcfield->data : $marcfield->as_string );
392 } elsif ( $tag < 10 ) {
393 push @content, $marcfield->data();
395 push @content, $marcfield->as_string();
400 $row->{$field} = \@content;
401 push( @addnumberfields, $field );
406 $row->{'addnumberfields'} = \@addnumberfields;
413 return unless defined $isbn;
414 $isbn =~ s/ |-|\.//g;
415 $isbn =~ s/\|/ \| /g;
420 sub _create_connection {
422 my $option1= ZOOM::Options->new();
423 $option1->option( 'async' => 1 );
424 $option1->option( 'elementSetName', 'F' );
425 $option1->option( 'preferredRecordSyntax', $server->{syntax} );
426 $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
428 if( $server->{servertype} eq 'sru' ) {
429 foreach( split ',', $server->{sru_options}//'' ) {
430 #first remove surrounding spaces at comma and equals-sign
432 my @temp= split '=', $_, 2;
433 @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
434 $option1->option( $temp[0] => $temp[1] ) if @temp;
436 } elsif( $server->{servertype} eq 'zed' ) {
437 $option1->option( 'databaseName', $server->{db} );
438 $option1->option( 'user', $server->{userid} ) if $server->{userid};
439 $option1->option( 'password', $server->{password} ) if $server->{password};
441 my $obj= ZOOM::Connection->create($option1);
442 if( $server->{servertype} eq 'sru' ) {
443 my $host= $server->{host};
444 if( $host !~ /^https?:\/\// ) {
445 #Normally, host will not be prefixed by protocol.
446 #In that case we can (safely) assume http.
447 #In case someone prefixed with https, give it a try..
448 $host = 'http://' . $host;
450 $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
452 $obj->connect( $server->{host}, $server->{port} );
457 sub _translate_query { #SRU query adjusted per server cf. srufields column
458 my ($server, $query) = @_;
460 #sru_fields is in format title=field,isbn=field,...
461 #if a field doesn't exist, try anywhere or remove [field]=
462 my @parts= split(',', $server->{sru_fields} );
463 my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
464 my $any= $trans{srchany}?$trans{srchany}.'=':'';
467 foreach my $key (keys %trans) {
472 $q=~s/\[$key\]=/$any/g;
475 $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
479 =head2 ImportBreedingAuth
481 ImportBreedingAuth( $marcrecord, $filename, $encoding, $heading );
483 ImportBreedingAuth imports MARC records in the reservoir (import_records table) or returns their id if they already exist.
487 sub ImportBreedingAuth {
488 my ( $marcrecord, $filename, $encoding, $heading ) = @_;
489 my $dbh = C4::Context->dbh;
491 my $batch_id = GetZ3950BatchId($filename);
492 my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
494 my $controlnumber = $marcrecord->field('001')->data;
496 # Normalize the record so it doesn't have separated diacritics
497 SetUTF8Flag($marcrecord);
499 $searchbreeding->execute($controlnumber,$heading);
500 my ($breedingid) = $searchbreeding->fetchrow;
502 return $breedingid if $breedingid;
503 $breedingid = AddAuthToBatch($batch_id, 0, $marcrecord, $encoding);
507 =head2 Z3950SearchAuth
509 Z3950SearchAuth($pars, $template);
511 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
512 title, uniform title, subject, subjectsubdiv, srchany.
513 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
514 This code is used in cataloging/z3950_auth_search.
515 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
519 sub Z3950SearchAuth {
520 my ($pars, $template)= @_;
522 my $dbh = C4::Context->dbh;
523 my @id= @{$pars->{id}};
524 my $page= $pars->{page};
532 my @breeding_loop = ();
541 my $marcflavour = C4::Context->preference('marcflavour');
542 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
543 my $authid= $pars->{authid};
544 my ( $zquery, $squery ) = _auth_build_query( $pars );
545 foreach my $servid (@id) {
546 my $sth = $dbh->prepare("select * from z3950servers where id=?");
547 $sth->execute($servid);
548 while ( my $server = $sth->fetchrow_hashref ) {
549 $oConnection[$s] = _create_connection( $server );
551 if ( $server->{servertype} eq 'zed' ) {
552 my $server_zquery = $zquery;
553 if ( my $attributes = $server->{attributes} ) {
554 $server_zquery = "$attributes $zquery";
556 $oResult[$s] = $oConnection[$s]->search_pqf( $server_zquery );
559 $oResult[$s] = $oConnection[$s]->search(
560 ZOOM::Query::CQL->new(_translate_query( $server, $squery ))
563 $encoding[$s] = ($server->{encoding}?$server->{encoding}:"iso-5426");
564 $servers[$s] = $server;
570 while ( $nremaining-- ) {
573 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
574 $event = $oConnection[ $k - 1 ]->last_event();
575 last if $event == ZOOM::Event::ZEND;
580 my ($error )= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
582 if ($error =~ m/^(10000|10007)$/ ) {
583 push(@errconn, {'server' => $serverhost[$k]});
587 my $numresults = $oResult[$k]->size();
590 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
591 $show_next = 1 if $numresults >= ($page*20);
592 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
593 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
594 my $rec = $oResult[$k]->record($i);
598 $marcdata = $rec->raw();
600 my ($charset_result, $charset_errors);
601 if( $servers[$k]->{servertype} eq 'sru' ) {
602 $marcrecord = MARC::Record->new_from_xml( $marcdata, 'UTF-8', $servers[$k]->{syntax} );
603 $marcrecord->encoding('UTF-8');
605 ( $marcrecord, $charset_result, $charset_errors ) = MarcToUTF8Record( $marcdata, $marc_type, $encoding[$k] );
608 my $heading_authtype_code;
609 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
610 next if ( not defined $heading_authtype_code ) ;
612 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
614 my $breedingid = ImportBreedingAuth( $marcrecord, $serverhost[$k], $encoding[$k], $heading );
616 $row_data{server} = $servers[$k]->{'servername'};
617 $row_data{breedingid} = $breedingid;
618 $row_data{heading} = $heading;
619 $row_data{authid} = $authid;
620 $row_data{heading_code} = $heading_authtype_code;
621 push( @breeding_loop, \%row_data );
624 push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1});
632 numberpending => $nremaining,
633 current_page => $page,
634 total_pages => $total_pages,
635 show_nextbutton => $show_next?1:0,
636 show_prevbutton => $page!=1,
640 #close result sets and connections
642 $oResult[$_]->destroy();
643 $oConnection[$_]->destroy();
647 foreach my $id (@id) {
648 push @servers, {id => $id};
651 breeding_loop => \@breeding_loop,
652 servers => \@servers,