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>.
27 use MARC::File::USMARC;
30 use C4::AuthoritiesMarc; #GuessAuthTypeCode, FindDuplicateAuthority
35 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
40 @EXPORT = qw(&BreedingSearch &Z3950Search &Z3950SearchAuth);
45 C4::Breeding : module to add biblios to import_records via
46 the breeding/reservoir API.
50 Z3950Search($pars, $template);
51 ($count, @results) = &BreedingSearch($title,$isbn);
55 This module contains routines related to Koha's Z39.50 search into
56 cataloguing reservoir features.
60 ($count, @results) = &BreedingSearch($term);
61 C<$term> contains the term to search, it will be searched as title,author, or isbn
63 C<$count> is the number of items in C<@results>. C<@results> is an
64 array of references-to-hash; the keys are the items from the C<import_records> and
65 C<import_biblios> tables of the Koha database.
71 my $dbh = C4::Context->dbh;
77 my $authortitle = $term;
78 $authortitle =~ s/(\s+)/\%/g; #Replace spaces with wildcard
79 $authortitle = "%" . $authortitle . "%"; #Add wildcard to start and end of string
80 # normalise ISBN like at import
81 my @isbns = C4::Koha::GetVariationsOfISBN($term);
83 $query = "SELECT import_record_id, file_name, isbn, title, author
85 JOIN import_records USING (import_record_id)
86 JOIN import_batches USING (import_batch_id)
87 WHERE title LIKE ? OR author LIKE ? OR isbn IN (" . join(',',('?') x @isbns) . ")";
88 @bind=( $authortitle, $authortitle, @isbns );
89 $sth = $dbh->prepare($query);
91 while (my $data = $sth->fetchrow_hashref) {
92 $results[$count] = $data;
93 # FIXME - hack to reflect difference in name
94 # of columns in old marc_breeding and import_records
95 # There needs to be more separation between column names and
96 # field names used in the templates </soapbox>
97 $data->{'file'} = $data->{'file_name'};
98 $data->{'id'} = $data->{'import_record_id'};
103 return($count, @results);
104 } # sub breedingsearch
109 Z3950Search($pars, $template);
111 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
112 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).
113 This code is used in acqui/z3950_search and cataloging/z3950_search.
114 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
119 my ($pars, $template)= @_;
121 my @id= @{$pars->{id}};
122 my $page= $pars->{page};
123 my $biblionumber= $pars->{biblionumber};
128 my @breeding_loop = ();
135 my ( $zquery, $squery ) = _bib_build_query( $pars );
137 my $schema = Koha::Database->new()->schema();
138 my $rs = $schema->resultset('Z3950server')->search(
140 { result_class => 'DBIx::Class::ResultClass::HashRefInflator' },
142 my @servers = $rs->all;
143 foreach my $server ( @servers ) {
144 my $server_zquery = $zquery;
145 if(my $attributes = $server->{attributes}){
146 $server_zquery = "$attributes $zquery";
148 $oConnection[$s] = _create_connection( $server );
150 $server->{servertype} eq 'zed'?
151 $oConnection[$s]->search_pqf( $server_zquery ):
152 $oConnection[$s]->search(ZOOM::Query::CQL->new(
153 _translate_query( $server, $squery )));
156 my $xslh = Koha::XSLT::Base->new;
159 while ( $nremaining-- ) {
162 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
163 $event = $oConnection[ $k - 1 ]->last_event();
164 last if $event == ZOOM::Event::ZEND;
169 my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
171 if ($error =~ m/^(10000|10007)$/ ) {
172 push(@errconn, { server => $servers[$k]->{host}, error => $error } );
176 my $numresults = $oResult[$k]->size();
179 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
180 $show_next = 1 if $numresults >= ($page*20);
181 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
182 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
183 if ( $oResult[$k]->record($i) ) {
185 ( $res, $error ) = _handle_one_result( $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, $xslh ); #ignores error in sequence numbering
186 push @breeding_loop, $res if $res;
187 push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i+1 } if $error;
190 push @errconn, { 'server' => $servers[$k]->{servername}, error => ( ( $oConnection[$k]->error_x() )[0] ), seq => $i+1 };
198 numberpending => $nremaining,
199 current_page => $page,
200 total_pages => $total_pages,
201 show_nextbutton => $show_next?1:0,
202 show_prevbutton => $page!=1,
206 #close result sets and connections
208 $oResult[$_]->destroy();
209 $oConnection[$_]->destroy();
213 breeding_loop => \@breeding_loop,
214 servers => \@servers,
219 sub _auth_build_query {
223 nameany => '@attr 1=1002 "#term" ',
224 authorany => '@attr 1=1003 "#term" ',
225 authorcorp => '@attr 1=2 "#term" ',
226 authorpersonal => '@attr 1=1 "#term" ',
227 authormeetingcon => '@attr 1=3 "#term" ',
228 subject => '@attr 1=21 "#term" ',
229 subjectsubdiv => '@attr 1=47 "#term" ',
230 title => '@attr 1=4 "#term" ',
231 uniformtitle => '@attr 1=6 "#term" ',
232 srchany => '@attr 1=1016 "#term" ',
233 controlnumber => '@attr 1=12 "#term" ',
236 return _build_query( $pars, $qry_build );
239 sub _bib_build_query {
244 isbn => '@attr 1=7 @attr 5=1 "#term" ',
245 issn => '@attr 1=8 @attr 5=1 "#term" ',
246 title => '@attr 1=4 "#term" ',
247 author => '@attr 1=1003 "#term" ',
248 dewey => '@attr 1=16 "#term" ',
249 subject => '@attr 1=21 "#term" ',
250 lccall => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
251 '@attr 6=1 "#term" ',
252 controlnumber => '@attr 1=12 "#term" ',
253 srchany => '@attr 1=1016 "#term" ',
254 stdid => '@attr 1=1007 "#term" ',
255 publicationyear => '@attr 1=31 "#term" '
258 return _build_query( $pars, $qry_build );
263 my ( $pars, $qry_build ) = @_;
268 foreach my $k ( sort keys %$pars ) {
269 #note that the sort keys forces an identical result under Perl 5.18
270 #one of the unit tests is based on that assumption
271 if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
272 $qry_build->{$k} =~ s/#term/$val/g;
273 $zquery .= $qry_build->{$k};
274 $squery .= "[$k]=\"$val\" and ";
278 $zquery = "\@and " . $zquery for 2..$nterms;
279 $squery =~ s/ and $//;
280 return ( $zquery, $squery );
283 sub _handle_one_result {
284 my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_;
286 my $raw= $zoomrec->raw();
288 if( $servhref->{servertype} eq 'sru' ) {
289 $marcrecord= MARC::Record->new_from_xml( $raw, 'UTF-8',
290 $servhref->{syntax} );
291 $marcrecord->encoding('UTF-8');
293 ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
295 SetUTF8Flag($marcrecord);
297 ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh);
299 my $batch_id = GetZ3950BatchId($servhref->{servername});
300 my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0);
301 #Last zero indicates: no update for batch record counts
304 #call to TransformMarcToKoha replaced by next call
305 #we only need six fields from the marc record
309 biblionumber => $bib,
310 server => $servhref->{servername},
311 breedingid => $breedingid,
312 }, $marcrecord) if $breedingid;
313 return ( $row, $error );
317 my ( $marc, $server, $xslh ) = @_;
318 return $marc if !$server->{add_xslt};
320 my $htdocs = C4::Context->config('intrahtdocs');
321 my $theme = C4::Context->preference("template"); #staff
322 my $lang = C4::Languages::getlanguage() || 'en';
324 my @files= split ',', $server->{add_xslt};
325 my $xml = $marc->as_xml;
326 foreach my $f ( @files ) {
327 $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
328 $f = C4::XSLT::_get_best_default_xslt_filename(
329 $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
330 $xml = $xslh->transform( $xml, $f );
331 last if $xslh->err; #skip other files
334 return MARC::Record->new_from_xml($xml, 'UTF-8');
336 return ( $marc, $xslh->err ); #original record in case of errors
341 my ($row, $record)=@_;
343 title => 'biblio.title',
344 author => 'biblio.author',
345 isbn =>'biblioitems.isbn',
346 lccn =>'biblioitems.lccn', #LC control number (not call number)
347 edition =>'biblioitems.editionstatement'
349 $fetch{date} = C4::Context->preference('marcflavour') eq "MARC21" ? 'biblio.copyrightdate' : 'biblioitems.publicationyear';
351 foreach my $k (keys %fetch) {
352 $row->{$k} = C4::Biblio::TransformMarcToKohaOneField( $fetch{$k}, $record );
354 $row->{date}//= $row->{date2};
355 $row->{isbn}=_isbn_replace($row->{isbn});
357 $row = _add_custom_field_rowdata($row, $record);
362 sub _add_custom_field_rowdata
364 my ( $row, $record ) = @_;
365 my $pref_newtags = C4::Context->preference('AdditionalFieldsInZ3950ResultSearch');
366 my $pref_flavour = C4::Context->preference('MarcFlavour');
368 $pref_newtags =~ s/^\s+|\s+$//g;
369 $pref_newtags =~ s/\h+/ /g;
373 foreach my $field (split /\,/, $pref_newtags) {
374 $field =~ s/^\s+|\s+$//g ; # trim whitespace
375 my ($tag, $subtags) = split(/\$/, $field);
377 if ( $record->field($tag) ) {
380 for my $marcfield ($record->field($tag)) {
383 for my $code (split //, $subtags) {
384 if ( $marcfield->subfield($code) ) {
385 $str .= $marcfield->subfield($code) . ' ';
388 if ( not $str eq '') {
391 } elsif ( $tag == 10 ) {
392 push @content, ( $pref_flavour eq "MARC21" ? $marcfield->data : $marcfield->as_string );
393 } elsif ( $tag < 10 ) {
394 push @content, $marcfield->data();
396 push @content, $marcfield->as_string();
401 $row->{$field} = \@content;
402 push( @addnumberfields, $field );
407 $row->{'addnumberfields'} = \@addnumberfields;
414 return unless defined $isbn;
415 $isbn =~ s/ |-|\.//g;
416 $isbn =~ s/\|/ \| /g;
421 sub _create_connection {
423 my $option1= ZOOM::Options->new();
424 $option1->option( 'async' => 1 );
425 $option1->option( 'elementSetName', 'F' );
426 $option1->option( 'preferredRecordSyntax', $server->{syntax} );
427 $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
429 if( $server->{servertype} eq 'sru' ) {
430 foreach( split ',', $server->{sru_options}//'' ) {
431 #first remove surrounding spaces at comma and equals-sign
433 my @temp= split '=', $_, 2;
434 @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
435 $option1->option( $temp[0] => $temp[1] ) if @temp;
437 } elsif( $server->{servertype} eq 'zed' ) {
438 $option1->option( 'databaseName', $server->{db} );
439 $option1->option( 'user', $server->{userid} ) if $server->{userid};
440 $option1->option( 'password', $server->{password} ) if $server->{password};
442 my $obj= ZOOM::Connection->create($option1);
443 if( $server->{servertype} eq 'sru' ) {
444 my $host= $server->{host};
445 if( $host !~ /^https?:\/\// ) {
446 #Normally, host will not be prefixed by protocol.
447 #In that case we can (safely) assume http.
448 #In case someone prefixed with https, give it a try..
449 $host = 'http://' . $host;
451 $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
453 $obj->connect( $server->{host}, $server->{port} );
458 sub _translate_query { #SRU query adjusted per server cf. srufields column
459 my ($server, $query) = @_;
461 #sru_fields is in format title=field,isbn=field,...
462 #if a field doesn't exist, try anywhere or remove [field]=
463 my @parts= split(',', $server->{sru_fields} );
464 my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
465 my $any= $trans{srchany}?$trans{srchany}.'=':'';
468 foreach my $key (keys %trans) {
473 $q=~s/\[$key\]=/$any/g;
476 $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
480 =head2 ImportBreedingAuth
482 ImportBreedingAuth( $marcrecord, $filename, $encoding, $heading );
484 ImportBreedingAuth imports MARC records in the reservoir (import_records table) or returns their id if they already exist.
488 sub ImportBreedingAuth {
489 my ( $marcrecord, $filename, $encoding, $heading ) = @_;
490 my $dbh = C4::Context->dbh;
492 my $batch_id = GetZ3950BatchId($filename);
493 my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
495 my $controlnumber = $marcrecord->field('001')->data;
497 # Normalize the record so it doesn't have separated diacritics
498 SetUTF8Flag($marcrecord);
500 $searchbreeding->execute($controlnumber,$heading);
501 my ($breedingid) = $searchbreeding->fetchrow;
503 return $breedingid if $breedingid;
504 $breedingid = AddAuthToBatch($batch_id, 0, $marcrecord, $encoding);
508 =head2 Z3950SearchAuth
510 Z3950SearchAuth($pars, $template);
512 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
513 title, uniform title, subject, subjectsubdiv, srchany.
514 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
515 This code is used in cataloging/z3950_auth_search.
516 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
520 sub Z3950SearchAuth {
521 my ($pars, $template)= @_;
523 my $dbh = C4::Context->dbh;
524 my @id= @{$pars->{id}};
525 my $page= $pars->{page};
533 my @breeding_loop = ();
542 my $marcflavour = C4::Context->preference('marcflavour');
543 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
544 my $authid= $pars->{authid};
545 my ( $zquery, $squery ) = _auth_build_query( $pars );
546 foreach my $servid (@id) {
547 my $sth = $dbh->prepare("select * from z3950servers where id=?");
548 $sth->execute($servid);
549 while ( my $server = $sth->fetchrow_hashref ) {
550 $oConnection[$s] = _create_connection( $server );
552 if ( $server->{servertype} eq 'zed' ) {
553 my $server_zquery = $zquery;
554 if ( my $attributes = $server->{attributes} ) {
555 $server_zquery = "$attributes $zquery";
557 $oResult[$s] = $oConnection[$s]->search_pqf( $server_zquery );
560 $oResult[$s] = $oConnection[$s]->search(
561 ZOOM::Query::CQL->new(_translate_query( $server, $squery ))
564 $encoding[$s] = ($server->{encoding}?$server->{encoding}:"iso-5426");
565 $servers[$s] = $server;
571 while ( $nremaining-- ) {
574 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
575 $event = $oConnection[ $k - 1 ]->last_event();
576 last if $event == ZOOM::Event::ZEND;
581 my ($error )= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
583 if ($error =~ m/^(10000|10007)$/ ) {
584 push(@errconn, {'server' => $serverhost[$k]});
588 my $numresults = $oResult[$k]->size();
591 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
592 $show_next = 1 if $numresults >= ($page*20);
593 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
594 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
595 my $rec = $oResult[$k]->record($i);
599 $marcdata = $rec->raw();
601 my ($charset_result, $charset_errors);
602 if( $servers[$k]->{servertype} eq 'sru' ) {
603 $marcrecord = MARC::Record->new_from_xml( $marcdata, 'UTF-8', $servers[$k]->{syntax} );
604 $marcrecord->encoding('UTF-8');
606 ( $marcrecord, $charset_result, $charset_errors ) = MarcToUTF8Record( $marcdata, $marc_type, $encoding[$k] );
609 my $heading_authtype_code;
610 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
611 next if ( not defined $heading_authtype_code ) ;
613 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
615 my $breedingid = ImportBreedingAuth( $marcrecord, $serverhost[$k], $encoding[$k], $heading );
617 $row_data{server} = $servers[$k]->{'servername'};
618 $row_data{breedingid} = $breedingid;
619 $row_data{heading} = $heading;
620 $row_data{authid} = $authid;
621 $row_data{heading_code} = $heading_authtype_code;
622 push( @breeding_loop, \%row_data );
625 push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1});
633 numberpending => $nremaining,
634 current_page => $page,
635 total_pages => $total_pages,
636 show_nextbutton => $show_next?1:0,
637 show_prevbutton => $page!=1,
641 #close result sets and connections
643 $oResult[$_]->destroy();
644 $oConnection[$_]->destroy();
648 foreach my $id (@id) {
649 push @servers, {id => $id};
652 breeding_loop => \@breeding_loop,
653 servers => \@servers,