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 $raw= MARC::Record->new_from_xml( $raw, $servhref->{encoding}, $servhref->{syntax} );
320 ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
321 SetUTF8Flag($marcrecord);
323 ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh);
325 my $batch_id = GetZ3950BatchId($servhref->{servername});
326 my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0, 0);
327 #FIXME passing 0 for z3950random
328 #Will eliminate this unused field in a followup report
329 #Last zero indicates: no update for batch record counts
332 #call to TransformMarcToKoha replaced by next call
333 #we only need six fields from the marc record
337 biblionumber => $bib,
338 server => $servhref->{servername},
339 breedingid => $breedingid,
340 }, $marcrecord) if $breedingid;
341 return ( $row, $error );
345 my ( $marc, $server, $xslh ) = @_;
346 return $marc if !$server->{add_xslt};
348 my $htdocs = C4::Context->config('intrahtdocs');
349 my $theme = C4::Context->preference("template"); #staff
350 my $lang = C4::Languages::getlanguage() || 'en';
352 my @files= split ',', $server->{add_xslt};
353 my $xml = $marc->as_xml;
354 foreach my $f ( @files ) {
355 $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
356 $f = C4::XSLT::_get_best_default_xslt_filename(
357 $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
358 $xml = $xslh->transform( $xml, $f );
359 last if $xslh->err; #skip other files
362 return MARC::Record->new_from_xml($xml, 'UTF-8');
364 return ( $marc, $xslh->err ); #original record in case of errors
369 my ($row, $record)=@_;
371 title => 'biblio.title',
372 author => 'biblio.author',
373 isbn =>'biblioitems.isbn',
374 lccn =>'biblioitems.lccn', #LC control number (not call number)
375 edition =>'biblioitems.editionstatement',
376 date => 'biblio.copyrightdate', #MARC21
377 date2 => 'biblioitems.publicationyear', #UNIMARC
379 foreach my $k (keys %fetch) {
380 $row->{$k} = C4::Biblio::TransformMarcToKohaOneField( $fetch{$k}, $record );
382 $row->{date}//= $row->{date2};
383 $row->{isbn}=_isbn_replace($row->{isbn});
389 return unless defined $isbn;
390 $isbn =~ s/ |-|\.//g;
391 $isbn =~ s/\|/ \| /g;
396 sub _create_connection {
398 my $option1= new ZOOM::Options();
399 $option1->option( 'async' => 1 );
400 $option1->option( 'elementSetName', 'F' );
401 $option1->option( 'preferredRecordSyntax', $server->{syntax} );
402 $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
404 if( $server->{servertype} eq 'sru' ) {
405 foreach( split ',', $server->{sru_options}//'' ) {
406 #first remove surrounding spaces at comma and equals-sign
408 my @temp= split '=', $_, 2;
409 @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
410 $option1->option( $temp[0] => $temp[1] ) if @temp;
412 } elsif( $server->{servertype} eq 'zed' ) {
413 $option1->option( 'databaseName', $server->{db} );
414 $option1->option( 'user', $server->{userid} ) if $server->{userid};
415 $option1->option( 'password', $server->{password} ) if $server->{password};
417 my $obj= ZOOM::Connection->create($option1);
418 if( $server->{servertype} eq 'sru' ) {
419 my $host= $server->{host};
420 if( $host !~ /^https?:\/\// ) {
421 #Normally, host will not be prefixed by protocol.
422 #In that case we can (safely) assume http.
423 #In case someone prefixed with https, give it a try..
424 $host = 'http://' . $host;
426 $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
428 $obj->connect( $server->{host}, $server->{port} );
433 sub _translate_query { #SRU query adjusted per server cf. srufields column
434 my ($server, $query) = @_;
436 #sru_fields is in format title=field,isbn=field,...
437 #if a field doesn't exist, try anywhere or remove [field]=
438 my @parts= split(',', $server->{sru_fields} );
439 my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
440 my $any= $trans{srchany}?$trans{srchany}.'=':'';
443 foreach my $key (keys %trans) {
448 $q=~s/\[$key\]=/$any/g;
451 $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
455 =head2 ImportBreedingAuth
457 ImportBreedingAuth($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random);
459 ImportBreedingAuth imports MARC records in the reservoir (import_records table).
460 ImportBreedingAuth is based on the ImportBreeding subroutine.
464 sub ImportBreedingAuth {
465 my ($marcrecord,$overwrite_auth,$filename,$encoding,$z3950random) = @_;
466 my $dbh = C4::Context->dbh;
468 my $batch_id = GetZ3950BatchId($filename);
469 my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
471 my $marcflavour = C4::Context->preference('marcflavour');
472 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
474 # fields used for import results
477 my $alreadyinfarm = 0;
478 my $notmarcrecord = 0;
481 # Normalize the record so it doesn't have separated diacritics
482 SetUTF8Flag($marcrecord);
484 if (scalar($marcrecord->fields()) == 0) {
488 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
490 my $heading_authtype_code;
491 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
494 $controlnumber = $marcrecord->field('001')->data;
496 #Check if the authority record already exists in the database...
497 my ($duplicateauthid,$duplicateauthvalue);
498 if ($marcrecord && $heading_authtype_code) {
499 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
502 if ($duplicateauthid && $overwrite_auth ne 2) {
503 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
506 if ($controlnumber && $heading) {
507 $searchbreeding->execute($controlnumber,$heading);
508 ($breedingid) = $searchbreeding->fetchrow;
510 if ($breedingid && $overwrite_auth eq '0') {
513 if ($breedingid && $overwrite_auth eq '1') {
514 ModAuthorityInBatch($breedingid, $marcrecord);
516 my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
517 $breedingid = $import_id;
523 return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
526 =head2 Z3950SearchAuth
528 Z3950SearchAuth($pars, $template);
530 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
531 title, uniform title, subject, subjectsubdiv, srchany.
532 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
533 This code is used in cataloging/z3950_auth_search.
534 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
538 sub Z3950SearchAuth {
539 my ($pars, $template)= @_;
541 my $dbh = C4::Context->dbh;
542 my @id= @{$pars->{id}};
543 my $random= $pars->{random};
544 my $page= $pars->{page};
560 my @breeding_loop = ();
570 my $marcflavour = C4::Context->preference('marcflavour');
571 my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
572 my $authid= $pars->{authid};
573 my ( $zquery, $squery ) = _auth_build_query( $pars );
574 foreach my $servid (@id) {
575 my $sth = $dbh->prepare("select * from z3950servers where id=?");
576 $sth->execute($servid);
577 while ( $server = $sth->fetchrow_hashref ) {
578 $oConnection[$s] = _create_connection( $server );
581 $server->{servertype} eq 'zed'?
582 $oConnection[$s]->search_pqf( $zquery ):
583 $oConnection[$s]->search(new ZOOM::Query::CQL(
584 _translate_query( $server, $squery )));
585 $encoding[$s] = ($server->{encoding}?$server->{encoding}:"iso-5426");
586 $servers[$s] = $server;
592 while ( $nremaining-- ) {
595 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
596 $event = $oConnection[ $k - 1 ]->last_event();
597 last if $event == ZOOM::Event::ZEND;
602 my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
604 if ($error =~ m/^(10000|10007)$/ ) {
605 push(@errconn, {'server' => $serverhost[$k]});
609 my $numresults = $oResult[$k]->size();
612 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
613 $show_next = 1 if $numresults >= ($page*20);
614 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
615 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
616 my $rec = $oResult[$k]->record($i);
620 $marcdata = $rec->raw();
622 my ($charset_result, $charset_errors);
623 if( $servers[$k]->{servertype} eq 'sru' ) {
624 $marcdata = MARC::Record->new_from_xml( $marcdata, $encoding[$k], $servers[$k]->{syntax} );
626 ($marcrecord, $charset_result, $charset_errors)= MarcToUTF8Record($marcdata, $marc_type, $encoding[$k]);
628 my $heading_authtype_code;
629 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
630 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
632 my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcrecord, 2, $serverhost[$k], $encoding[$k], $random);
634 $row_data{server} = $servers[$k]->{'servername'};
635 $row_data{breedingid} = $breedingid;
636 $row_data{heading} = $heading;
637 $row_data{authid} = $authid;
638 $row_data{heading_code} = $heading_authtype_code;
639 push( @breeding_loop, \%row_data );
642 push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1});
650 numberpending => $nremaining,
651 current_page => $page,
652 total_pages => $total_pages,
653 show_nextbutton => $show_next?1:0,
654 show_prevbutton => $page!=1,
658 #close result sets and connections
660 $oResult[$_]->destroy();
661 $oConnection[$_]->destroy();
665 foreach my $id (@id) {
666 push @servers, {id => $id};
669 breeding_loop => \@breeding_loop,
670 servers => \@servers,