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;
29 use C4::AuthoritiesMarc; #GuessAuthTypeCode, FindDuplicateAuthority
32 use Koha::XSLT_Handler;
34 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
39 @EXPORT = 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,$random);
54 This module contains routines related to Koha's Z39.50 search into
55 cataloguing reservoir features.
59 ($count, @results) = &BreedingSearch($title,$isbn,$random);
60 C<$title> contains the title,
61 C<$isbn> contains isbn or issn,
62 C<$random> contains the random seed from a z3950 search.
64 C<$count> is the number of items in C<@results>. C<@results> is an
65 array of references-to-hash; the keys are the items from the C<import_records> and
66 C<import_biblios> tables of the Koha database.
71 my ($search,$isbn,$z3950random) = @_;
72 my $dbh = C4::Context->dbh;
78 # normalise ISBN like at import
79 $isbn = C4::Koha::GetNormalizedISBN($isbn);
81 $query = "SELECT import_record_id, file_name, isbn, title, author
83 JOIN import_records USING (import_record_id)
84 JOIN import_batches USING (import_batch_id)
87 $query .= "z3950random = ?";
91 if (defined($search) && length($search)>0) {
92 $search =~ s/(\s+)/\%/g;
93 $query .= "title like ? OR author like ?";
94 push(@bind,"%$search%", "%$search%");
96 if ($#bind!=-1 && defined($isbn) && length($isbn)>0) {
99 if (defined($isbn) && length($isbn)>0) {
100 $query .= "isbn like ?";
101 push(@bind,"$isbn%");
104 $sth = $dbh->prepare($query);
105 $sth->execute(@bind);
106 while (my $data = $sth->fetchrow_hashref) {
107 $results[$count] = $data;
108 # FIXME - hack to reflect difference in name
109 # of columns in old marc_breeding and import_records
110 # There needs to be more separation between column names and
111 # field names used in the templates </soapbox>
112 $data->{'file'} = $data->{'file_name'};
113 $data->{'id'} = $data->{'import_record_id'};
118 return($count, @results);
119 } # sub breedingsearch
124 Z3950Search($pars, $template);
126 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
127 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).
128 This code is used in acqui/z3950_search and cataloging/z3950_search.
129 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
134 my ($pars, $template)= @_;
136 my @id= @{$pars->{id}};
137 my $page= $pars->{page};
138 my $biblionumber= $pars->{biblionumber};
143 my @breeding_loop = ();
150 my ( $zquery, $squery ) = _build_query( $pars );
152 my $schema = Koha::Database->new()->schema();
153 my $rs = $schema->resultset('Z3950server')->search(
155 { result_class => 'DBIx::Class::ResultClass::HashRefInflator' },
157 my @servers = $rs->all;
158 foreach my $server ( @servers ) {
159 $oConnection[$s] = _create_connection( $server );
161 $server->{servertype} eq 'zed'?
162 $oConnection[$s]->search_pqf( $zquery ):
163 $oConnection[$s]->search(new ZOOM::Query::CQL(
164 _translate_query( $server, $squery )));
167 my $xslh = Koha::XSLT_Handler->new;
170 while ( $nremaining-- ) {
173 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
174 $event = $oConnection[ $k - 1 ]->last_event();
175 last if $event == ZOOM::Event::ZEND;
180 my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
182 if ($error =~ m/^(10000|10007)$/ ) {
183 push(@errconn, { server => $servers[$k]->{host}, error => $error } );
187 my $numresults = $oResult[$k]->size();
190 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
191 $show_next = 1 if $numresults >= ($page*20);
192 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
193 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
194 if ( $oResult[$k]->record($i) ) {
196 ( $res, $error ) = _handle_one_result( $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, $xslh ); #ignores error in sequence numbering
197 push @breeding_loop, $res if $res;
198 push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i+1 } if $error;
201 push @errconn, { 'server' => $servers[$k]->{servername}, error => ( ( $oConnection[$k]->error_x() )[0] ), seq => $i+1 };
209 numberpending => $nremaining,
210 current_page => $page,
211 total_pages => $total_pages,
212 show_nextbutton => $show_next?1:0,
213 show_prevbutton => $page!=1,
217 #close result sets and connections
219 $oResult[$_]->destroy();
220 $oConnection[$_]->destroy();
224 breeding_loop => \@breeding_loop,
225 servers => \@servers,
230 sub _auth_build_query {
233 #FIXME These variables are not used
234 my $nameany= $pars->{nameany};
235 my $authorany= $pars->{authorany};
236 my $authorpersonal= $pars->{authorpersonal};
237 my $authorcorp= $pars->{authorcorp};
238 my $authormeetingcon= $pars->{authormeetingcon};
239 my $title= $pars->{title};
240 my $uniformtitle= $pars->{uniformtitle};
241 my $subject= $pars->{subject};
242 my $subjectsubdiv= $pars->{subjectsubdiv};
243 my $srchany= $pars->{srchany};
244 my $authid= $pars->{authid};
247 nameany => '@attr 1=1002 "#term" ',
248 authorany => '@attr 1=1003 "#term" ',
249 authorcorp => '@attr 1=2 "#term" ',
250 authorpersonal => '@attr 1=1 "#term" ',
251 authormeetingcon => '@attr 1=3 "#term" ',
252 subject => '@attr 1=21 "#term" ',
253 subjectsubdiv => '@attr 1=47 "#term" ',
254 title => '@attr 1=4 "#term" ',
255 uniformtitle => '@attr 1=6 "#term" ',
256 srchany => '@attr 1=1016 "#term" ',
257 controlnumber => '@attr 1=12 "#term" ',
263 foreach my $k ( sort keys %$pars ) {
264 #note that the sort keys forces an identical result under Perl 5.18
265 #one of the unit tests is based on that assumption
266 if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
267 $qry_build->{$k} =~ s/#term/$val/g;
268 $zquery .= $qry_build->{$k};
269 $squery .= "[$k]=\"$val\" and ";
273 $zquery = "\@and " . $zquery for 2..$nterms;
274 $squery =~ s/ and $//;
275 return ( $zquery, $squery );
283 isbn => '@attr 1=7 @attr 5=1 "#term" ',
284 issn => '@attr 1=8 @attr 5=1 "#term" ',
285 title => '@attr 1=4 "#term" ',
286 author => '@attr 1=1003 "#term" ',
287 dewey => '@attr 1=16 "#term" ',
288 subject => '@attr 1=21 "#term" ',
289 lccall => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
290 '@attr 6=1 "#term" ',
291 controlnumber => '@attr 1=12 "#term" ',
292 srchany => '@attr 1=1016 "#term" ',
293 stdid => '@attr 1=1007 "#term" ',
299 foreach my $k ( sort keys %$pars ) {
300 #note that the sort keys forces an identical result under Perl 5.18
301 #one of the unit tests is based on that assumption
302 if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
303 $qry_build->{$k} =~ s/#term/$val/g;
304 $zquery .= $qry_build->{$k};
305 $squery .= "[$k]=\"$val\" and ";
309 $zquery = "\@and " . $zquery for 2..$nterms;
310 $squery =~ s/ and $//;
311 return ( $zquery, $squery );
314 sub _handle_one_result {
315 my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_;
317 my $raw= $zoomrec->raw();
319 if( $servhref->{servertype} eq 'sru' ) {
320 $marcrecord= MARC::Record->new_from_xml( $raw, 'UTF-8',
321 $servhref->{syntax} );
323 ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
325 SetUTF8Flag($marcrecord);
327 ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh);
329 my $batch_id = GetZ3950BatchId($servhref->{servername});
330 my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0, 0);
331 #FIXME passing 0 for z3950random
332 #Will eliminate this unused field in a followup report
333 #Last zero indicates: no update for batch record counts
336 #call to TransformMarcToKoha replaced by next call
337 #we only need six fields from the marc record
341 biblionumber => $bib,
342 server => $servhref->{servername},
343 breedingid => $breedingid,
344 }, $marcrecord) if $breedingid;
345 return ( $row, $error );
349 my ( $marc, $server, $xslh ) = @_;
350 return $marc if !$server->{add_xslt};
352 my $htdocs = C4::Context->config('intrahtdocs');
353 my $theme = C4::Context->preference("template"); #staff
354 my $lang = C4::Languages::getlanguage() || 'en';
356 my @files= split ',', $server->{add_xslt};
357 my $xml = $marc->as_xml;
358 foreach my $f ( @files ) {
359 $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
360 $f = C4::XSLT::_get_best_default_xslt_filename(
361 $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
362 $xml = $xslh->transform( $xml, $f );
363 last if $xslh->err; #skip other files
366 return MARC::Record->new_from_xml($xml, 'UTF-8');
368 return ( $marc, $xslh->err ); #original record in case of errors
373 my ($row, $record)=@_;
375 title => 'biblio.title',
376 author => 'biblio.author',
377 isbn =>'biblioitems.isbn',
378 lccn =>'biblioitems.lccn', #LC control number (not call number)
379 edition =>'biblioitems.editionstatement',
380 date => 'biblio.copyrightdate', #MARC21
381 date2 => 'biblioitems.publicationyear', #UNIMARC
383 foreach my $k (keys %fetch) {
384 $row->{$k} = C4::Biblio::TransformMarcToKohaOneField( $fetch{$k}, $record );
386 $row->{date}//= $row->{date2};
387 $row->{isbn}=_isbn_replace($row->{isbn});
393 return unless defined $isbn;
394 $isbn =~ s/ |-|\.//g;
395 $isbn =~ s/\|/ \| /g;
400 sub _create_connection {
402 my $option1= new ZOOM::Options();
403 $option1->option( 'async' => 1 );
404 $option1->option( 'elementSetName', 'F' );
405 $option1->option( 'preferredRecordSyntax', $server->{syntax} );
406 $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
408 if( $server->{servertype} eq 'sru' ) {
409 foreach( split ',', $server->{sru_options}//'' ) {
410 #first remove surrounding spaces at comma and equals-sign
412 my @temp= split '=', $_, 2;
413 @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
414 $option1->option( $temp[0] => $temp[1] ) if @temp;
416 } elsif( $server->{servertype} eq 'zed' ) {
417 $option1->option( 'databaseName', $server->{db} );
418 $option1->option( 'user', $server->{userid} ) if $server->{userid};
419 $option1->option( 'password', $server->{password} ) if $server->{password};
421 my $obj= ZOOM::Connection->create($option1);
422 if( $server->{servertype} eq 'sru' ) {
423 my $host= $server->{host};
424 if( $host !~ /^https?:\/\// ) {
425 #Normally, host will not be prefixed by protocol.
426 #In that case we can (safely) assume http.
427 #In case someone prefixed with https, give it a try..
428 $host = 'http://' . $host;
430 $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
432 $obj->connect( $server->{host}, $server->{port} );
437 sub _translate_query { #SRU query adjusted per server cf. srufields column
438 my ($server, $query) = @_;
440 #sru_fields is in format title=field,isbn=field,...
441 #if a field doesn't exist, try anywhere or remove [field]=
442 my @parts= split(',', $server->{sru_fields} );
443 my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
444 my $any= $trans{srchany}?$trans{srchany}.'=':'';
447 foreach my $key (keys %trans) {
452 $q=~s/\[$key\]=/$any/g;
455 $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
459 =head2 ImportBreedingAuth
461 ImportBreedingAuth($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random);
463 ImportBreedingAuth imports MARC records in the reservoir (import_records table).
464 ImportBreedingAuth is based on the ImportBreeding subroutine.
468 sub ImportBreedingAuth {
469 my ($marcrecord,$overwrite_auth,$filename,$encoding,$z3950random) = @_;
470 my $dbh = C4::Context->dbh;
472 my $batch_id = GetZ3950BatchId($filename);
473 my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
475 my $marcflavour = C4::Context->preference('marcflavour');
476 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
478 # fields used for import results
481 my $alreadyinfarm = 0;
482 my $notmarcrecord = 0;
485 # Normalize the record so it doesn't have separated diacritics
486 SetUTF8Flag($marcrecord);
488 if (scalar($marcrecord->fields()) == 0) {
492 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
494 my $heading_authtype_code;
495 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
498 $controlnumber = $marcrecord->field('001')->data;
500 #Check if the authority record already exists in the database...
501 my ($duplicateauthid,$duplicateauthvalue);
502 if ($marcrecord && $heading_authtype_code) {
503 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
506 if ($duplicateauthid && $overwrite_auth ne 2) {
507 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
510 if ($controlnumber && $heading) {
511 $searchbreeding->execute($controlnumber,$heading);
512 ($breedingid) = $searchbreeding->fetchrow;
514 if ($breedingid && $overwrite_auth eq '0') {
517 if ($breedingid && $overwrite_auth eq '1') {
518 ModAuthorityInBatch($breedingid, $marcrecord);
520 my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
521 $breedingid = $import_id;
527 return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
530 =head2 Z3950SearchAuth
532 Z3950SearchAuth($pars, $template);
534 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
535 title, uniform title, subject, subjectsubdiv, srchany.
536 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
537 This code is used in cataloging/z3950_auth_search.
538 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
542 sub Z3950SearchAuth {
543 my ($pars, $template)= @_;
545 my $dbh = C4::Context->dbh;
546 my @id= @{$pars->{id}};
547 my $random= $pars->{random};
548 my $page= $pars->{page};
564 my @breeding_loop = ();
574 my $marcflavour = C4::Context->preference('marcflavour');
575 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
576 my $authid= $pars->{authid};
577 my ( $zquery, $squery ) = _auth_build_query( $pars );
578 foreach my $servid (@id) {
579 my $sth = $dbh->prepare("select * from z3950servers where id=?");
580 $sth->execute($servid);
581 while ( $server = $sth->fetchrow_hashref ) {
582 $oConnection[$s] = _create_connection( $server );
585 $server->{servertype} eq 'zed'?
586 $oConnection[$s]->search_pqf( $zquery ):
587 $oConnection[$s]->search(new ZOOM::Query::CQL(
588 _translate_query( $server, $squery )));
589 $encoding[$s] = ($server->{encoding}?$server->{encoding}:"iso-5426");
590 $servers[$s] = $server;
596 while ( $nremaining-- ) {
599 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
600 $event = $oConnection[ $k - 1 ]->last_event();
601 last if $event == ZOOM::Event::ZEND;
606 my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
608 if ($error =~ m/^(10000|10007)$/ ) {
609 push(@errconn, {'server' => $serverhost[$k]});
613 my $numresults = $oResult[$k]->size();
616 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
617 $show_next = 1 if $numresults >= ($page*20);
618 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
619 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
620 my $rec = $oResult[$k]->record($i);
624 $marcdata = $rec->raw();
626 my ($charset_result, $charset_errors);
627 if( $servers[$k]->{servertype} eq 'sru' ) {
628 $marcrecord = MARC::Record->new_from_xml( $marcdata, 'UTF-8', $servers[$k]->{syntax} );
630 ( $marcrecord, $charset_result, $charset_errors ) = MarcToUTF8Record( $marcdata, $marc_type, $encoding[$k] );
633 my $heading_authtype_code;
634 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
635 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
637 my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcrecord, 2, $serverhost[$k], $encoding[$k], $random);
639 $row_data{server} = $servers[$k]->{'servername'};
640 $row_data{breedingid} = $breedingid;
641 $row_data{heading} = $heading;
642 $row_data{authid} = $authid;
643 $row_data{heading_code} = $heading_authtype_code;
644 push( @breeding_loop, \%row_data );
647 push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1});
655 numberpending => $nremaining,
656 current_page => $page,
657 total_pages => $total_pages,
658 show_nextbutton => $show_next?1:0,
659 show_prevbutton => $page!=1,
663 #close result sets and connections
665 $oResult[$_]->destroy();
666 $oConnection[$_]->destroy();
670 foreach my $id (@id) {
671 push @servers, {id => $id};
674 breeding_loop => \@breeding_loop,
675 servers => \@servers,