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 my $nameany= $pars->{nameany
};
234 my $authorany= $pars->{authorany
};
235 my $authorpersonal= $pars->{authorpersonal
};
236 my $authorcorp= $pars->{authorcorp
};
237 my $authormeetingcon= $pars->{authormeetingcon
};
238 my $title= $pars->{title
};
239 my $uniformtitle= $pars->{uniformtitle
};
240 my $subject= $pars->{subject
};
241 my $subjectsubdiv= $pars->{subjectsubdiv
};
242 my $srchany= $pars->{srchany
};
243 my $authid= $pars->{authid
};
246 nameany
=> '@attr 1=1002 "#term" ',
247 authorany
=> '@attr 1=1003 "#term" ',
248 authorcorp
=> '@attr 1=2 "#term" ',
249 authorpersonal
=> '@attr 1=1 "#term" ',
250 authormeetingcon
=> '@attr 1=3 "#term" ',
251 subject
=> '@attr 1=21 "#term" ',
252 subjectsubdiv
=> '@attr 1=47 "#term" ',
253 title
=> '@attr 1=4 "#term" ',
254 uniformtitle
=> '@attr 1=6 "#term" ',
255 srchany
=> '@attr 1=1016 "#term" ',
261 foreach my $k ( sort keys %$pars ) {
262 #note that the sort keys forces an identical result under Perl 5.18
263 #one of the unit tests is based on that assumption
264 if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
265 $qry_build->{$k} =~ s/#term/$val/g;
266 $zquery .= $qry_build->{$k};
267 $squery .= "[$k]=\"$val\" and ";
271 $zquery = "\@and " . $zquery for 2..$nterms;
272 $squery =~ s/ and $//;
273 return ( $zquery, $squery );
281 isbn
=> '@attr 1=7 @attr 5=1 "#term" ',
282 issn
=> '@attr 1=8 @attr 5=1 "#term" ',
283 title
=> '@attr 1=4 "#term" ',
284 author
=> '@attr 1=1003 "#term" ',
285 dewey
=> '@attr 1=16 "#term" ',
286 subject
=> '@attr 1=21 "#term" ',
287 lccall
=> '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
288 '@attr 6=1 "#term" ',
289 controlnumber
=> '@attr 1=12 "#term" ',
290 srchany
=> '@attr 1=1016 "#term" ',
291 stdid
=> '@attr 1=1007 "#term" ',
297 foreach my $k ( sort keys %$pars ) {
298 #note that the sort keys forces an identical result under Perl 5.18
299 #one of the unit tests is based on that assumption
300 if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
301 $qry_build->{$k} =~ s/#term/$val/g;
302 $zquery .= $qry_build->{$k};
303 $squery .= "[$k]=\"$val\" and ";
307 $zquery = "\@and " . $zquery for 2..$nterms;
308 $squery =~ s/ and $//;
309 return ( $zquery, $squery );
312 sub _handle_one_result
{
313 my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_;
315 my $raw= $zoomrec->raw();
317 if( $servhref->{servertype
} eq 'sru' ) {
318 $marcrecord= MARC
::Record
->new_from_xml( $raw, 'UTF-8',
319 $servhref->{syntax
} );
321 ($marcrecord) = MarcToUTF8Record
($raw, C4
::Context
->preference('marcflavour'), $servhref->{encoding
} // "iso-5426" ); #ignores charset return values
323 SetUTF8Flag
($marcrecord);
325 ( $marcrecord, $error ) = _do_xslt_proc
($marcrecord, $servhref, $xslh);
327 my $batch_id = GetZ3950BatchId
($servhref->{servername
});
328 my $breedingid = AddBiblioToBatch
($batch_id, $seq, $marcrecord, 'UTF-8', 0, 0);
329 #FIXME passing 0 for z3950random
330 #Will eliminate this unused field in a followup report
331 #Last zero indicates: no update for batch record counts
334 #call to TransformMarcToKoha replaced by next call
335 #we only need six fields from the marc record
339 biblionumber
=> $bib,
340 server
=> $servhref->{servername
},
341 breedingid
=> $breedingid,
342 }, $marcrecord) if $breedingid;
343 return ( $row, $error );
347 my ( $marc, $server, $xslh ) = @_;
348 return $marc if !$server->{add_xslt
};
350 my $htdocs = C4
::Context
->config('intrahtdocs');
351 my $theme = C4
::Context
->preference("template"); #staff
352 my $lang = C4
::Languages
::getlanguage
() || 'en';
354 my @files= split ',', $server->{add_xslt
};
355 my $xml = $marc->as_xml;
356 foreach my $f ( @files ) {
357 $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
358 $f = C4
::XSLT
::_get_best_default_xslt_filename
(
359 $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
360 $xml = $xslh->transform( $xml, $f );
361 last if $xslh->err; #skip other files
364 return MARC
::Record
->new_from_xml($xml, 'UTF-8');
366 return ( $marc, $xslh->err ); #original record in case of errors
371 my ($row, $record)=@_;
373 title
=> 'biblio.title',
374 author
=> 'biblio.author',
375 isbn
=>'biblioitems.isbn',
376 lccn
=>'biblioitems.lccn', #LC control number (not call number)
377 edition
=>'biblioitems.editionstatement',
378 date
=> 'biblio.copyrightdate', #MARC21
379 date2
=> 'biblioitems.publicationyear', #UNIMARC
381 foreach my $k (keys %fetch) {
382 $row->{$k} = C4
::Biblio
::TransformMarcToKohaOneField
( $fetch{$k}, $record );
384 $row->{date
}//= $row->{date2
};
385 $row->{isbn
}=_isbn_replace
($row->{isbn
});
391 return unless defined $isbn;
392 $isbn =~ s/ |-|\.//g;
393 $isbn =~ s/\|/ \| /g;
398 sub _create_connection
{
400 my $option1= new ZOOM
::Options
();
401 $option1->option( 'async' => 1 );
402 $option1->option( 'elementSetName', 'F' );
403 $option1->option( 'preferredRecordSyntax', $server->{syntax
} );
404 $option1->option( 'timeout', $server->{timeout
} ) if $server->{timeout
};
406 if( $server->{servertype
} eq 'sru' ) {
407 foreach( split ',', $server->{sru_options
}//'' ) {
408 #first remove surrounding spaces at comma and equals-sign
410 my @temp= split '=', $_, 2;
411 @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
412 $option1->option( $temp[0] => $temp[1] ) if @temp;
414 } elsif( $server->{servertype
} eq 'zed' ) {
415 $option1->option( 'databaseName', $server->{db
} );
416 $option1->option( 'user', $server->{userid
} ) if $server->{userid
};
417 $option1->option( 'password', $server->{password
} ) if $server->{password
};
419 my $obj= ZOOM
::Connection
->create($option1);
420 if( $server->{servertype
} eq 'sru' ) {
421 my $host= $server->{host
};
422 if( $host !~ /^https?:\/\
// ) {
423 #Normally, host will not be prefixed by protocol.
424 #In that case we can (safely) assume http.
425 #In case someone prefixed with https, give it a try..
426 $host = 'http://' . $host;
428 $obj->connect( $host.':'.$server->{port
}.'/'.$server->{db
} );
430 $obj->connect( $server->{host
}, $server->{port
} );
435 sub _translate_query
{ #SRU query adjusted per server cf. srufields column
436 my ($server, $query) = @_;
438 #sru_fields is in format title=field,isbn=field,...
439 #if a field doesn't exist, try anywhere or remove [field]=
440 my @parts= split(',', $server->{sru_fields
} );
441 my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
442 my $any= $trans{srchany}?$trans{srchany}.'=':'';
445 foreach my $key (keys %trans) {
450 $q=~s/\[$key\]=/$any/g;
453 $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
457 =head2 ImportBreedingAuth
459 ImportBreedingAuth($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random);
461 ImportBreedingAuth imports MARC records in the reservoir (import_records table).
462 ImportBreedingAuth is based on the ImportBreeding subroutine.
466 sub ImportBreedingAuth {
467 my ($marcrecord,$overwrite_auth,$filename,$encoding,$z3950random) = @_;
468 my $dbh = C4::Context->dbh;
470 my $batch_id = GetZ3950BatchId($filename);
471 my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
473 my $marcflavour = C4::Context->preference('marcflavour');
474 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
476 # fields used for import results
479 my $alreadyinfarm = 0;
480 my $notmarcrecord = 0;
483 # Normalize the record so it doesn't have separated diacritics
484 SetUTF8Flag($marcrecord);
486 if (scalar($marcrecord->fields()) == 0) {
490 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
492 my $heading_authtype_code;
493 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
496 $controlnumber = $marcrecord->field('001')->data;
498 #Check if the authority record already exists in the database...
499 my ($duplicateauthid,$duplicateauthvalue);
500 if ($marcrecord && $heading_authtype_code) {
501 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
504 if ($duplicateauthid && $overwrite_auth ne 2) {
505 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
508 if ($controlnumber && $heading) {
509 $searchbreeding->execute($controlnumber,$heading);
510 ($breedingid) = $searchbreeding->fetchrow;
512 if ($breedingid && $overwrite_auth eq '0') {
515 if ($breedingid && $overwrite_auth eq '1') {
516 ModAuthorityInBatch($breedingid, $marcrecord);
518 my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
519 $breedingid = $import_id;
525 return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
528 =head2 Z3950SearchAuth
530 Z3950SearchAuth($pars, $template);
532 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
533 title, uniform title, subject, subjectsubdiv, srchany.
534 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
535 This code is used in cataloging/z3950_auth_search.
536 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
540 sub Z3950SearchAuth {
541 my ($pars, $template)= @_;
543 my $dbh = C4::Context->dbh;
544 my @id= @{$pars->{id}};
545 my $random= $pars->{random};
546 my $page= $pars->{page};
562 my @breeding_loop = ();
572 my $marcflavour = C4::Context->preference('marcflavour');
573 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
574 my $authid= $pars->{authid};
575 my ( $zquery, $squery ) = _auth_build_query( $pars );
576 foreach my $servid (@id) {
577 my $sth = $dbh->prepare("select * from z3950servers where id=?");
578 $sth->execute($servid);
579 while ( $server = $sth->fetchrow_hashref ) {
580 $oConnection[$s] = _create_connection( $server );
583 $server->{servertype} eq 'zed'?
584 $oConnection[$s]->search_pqf( $zquery ):
585 $oConnection[$s]->search(new ZOOM::Query::CQL(
586 _translate_query( $server, $squery )));
587 $encoding[$s] = ($server->{encoding}?$server->{encoding}:"iso-5426");
588 $servers[$s] = $server;
594 while ( $nremaining-- ) {
597 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
598 $event = $oConnection[ $k - 1 ]->last_event();
599 last if $event == ZOOM::Event::ZEND;
604 my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
606 if ($error =~ m/^(10000|10007)$/ ) {
607 push(@errconn, {'server' => $serverhost[$k]});
611 my $numresults = $oResult[$k]->size();
614 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
615 $show_next = 1 if $numresults >= ($page*20);
616 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
617 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
618 my $rec = $oResult[$k]->record($i);
622 $marcdata = $rec->raw();
624 my ($charset_result, $charset_errors);
625 if( $servers[$k]->{servertype} eq 'sru' ) {
626 $marcrecord = MARC::Record->new_from_xml( $marcdata, 'UTF-8', $servers[$k]->{syntax} );
628 ( $marcrecord, $charset_result, $charset_errors ) = MarcToUTF8Record( $marcdata, $marc_type, $encoding[$k] );
631 my $heading_authtype_code;
632 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
633 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
635 my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcrecord, 2, $serverhost[$k], $encoding[$k], $random);
637 $row_data{server} = $servers[$k]->{'servername'};
638 $row_data{breedingid} = $breedingid;
639 $row_data{heading} = $heading;
640 $row_data{authid} = $authid;
641 $row_data{heading_code} = $heading_authtype_code;
642 push( @breeding_loop, \%row_data );
645 push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1});
653 numberpending => $nremaining,
654 current_page => $page,
655 total_pages => $total_pages,
656 show_nextbutton => $show_next?1:0,
657 show_prevbutton => $page!=1,
661 #close result sets and connections
663 $oResult[$_]->destroy();
664 $oConnection[$_]->destroy();
668 foreach my $id (@id) {
669 push @servers, {id => $id};
672 breeding_loop => \@breeding_loop,
673 servers => \@servers,