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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 use MARC::File::USMARC;
29 use C4::AuthoritiesMarc; #GuessAuthTypeCode, FindDuplicateAuthority
32 use Koha::XSLT_Handler;
34 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
37 # set the version for version checking
38 $VERSION = 3.07.00.049;
41 @EXPORT = qw(&BreedingSearch &Z3950Search &Z3950SearchAuth);
46 C4::Breeding : module to add biblios to import_records via
47 the breeding/reservoir API.
51 Z3950Search($pars, $template);
52 ($count, @results) = &BreedingSearch($title,$isbn,$random);
56 This module contains routines related to Koha's Z39.50 search into
57 cataloguing reservoir features.
61 ($count, @results) = &BreedingSearch($title,$isbn,$random);
62 C<$title> contains the title,
63 C<$isbn> contains isbn or issn,
64 C<$random> contains the random seed from a z3950 search.
66 C<$count> is the number of items in C<@results>. C<@results> is an
67 array of references-to-hash; the keys are the items from the C<import_records> and
68 C<import_biblios> tables of the Koha database.
73 my ($search,$isbn,$z3950random) = @_;
74 my $dbh = C4::Context->dbh;
80 # normalise ISBN like at import
81 $isbn = C4::Koha::GetNormalizedISBN($isbn);
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)
89 $query .= "z3950random = ?";
93 if (defined($search) && length($search)>0) {
94 $search =~ s/(\s+)/\%/g;
95 $query .= "title like ? OR author like ?";
96 push(@bind,"%$search%", "%$search%");
98 if ($#bind!=-1 && defined($isbn) && length($isbn)>0) {
101 if (defined($isbn) && length($isbn)>0) {
102 $query .= "isbn like ?";
103 push(@bind,"$isbn%");
106 $sth = $dbh->prepare($query);
107 $sth->execute(@bind);
108 while (my $data = $sth->fetchrow_hashref) {
109 $results[$count] = $data;
110 # FIXME - hack to reflect difference in name
111 # of columns in old marc_breeding and import_records
112 # There needs to be more separation between column names and
113 # field names used in the templates </soapbox>
114 $data->{'file'} = $data->{'file_name'};
115 $data->{'id'} = $data->{'import_record_id'};
120 return($count, @results);
121 } # sub breedingsearch
126 Z3950Search($pars, $template);
128 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
129 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).
130 This code is used in acqui/z3950_search and cataloging/z3950_search.
131 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
136 my ($pars, $template)= @_;
138 my @id= @{$pars->{id}};
139 my $page= $pars->{page};
140 my $biblionumber= $pars->{biblionumber};
145 my @breeding_loop = ();
152 my ( $zquery, $squery ) = _build_query( $pars );
154 my $schema = Koha::Database->new()->schema();
155 my $rs = $schema->resultset('Z3950server')->search(
157 { result_class => 'DBIx::Class::ResultClass::HashRefInflator' },
159 my @servers = $rs->all;
160 foreach my $server ( @servers ) {
161 $oConnection[$s] = _create_connection( $server );
163 $server->{servertype} eq 'zed'?
164 $oConnection[$s]->search_pqf( $zquery ):
165 $oConnection[$s]->search(new ZOOM::Query::CQL(
166 _translate_query( $server, $squery )));
169 my $xslh = Koha::XSLT_Handler->new;
172 while ( $nremaining-- ) {
175 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
176 $event = $oConnection[ $k - 1 ]->last_event();
177 last if $event == ZOOM::Event::ZEND;
182 my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
184 if ($error =~ m/^(10000|10007)$/ ) {
185 push(@errconn, { server => $servers[$k]->{host}, error => $error } );
189 my $numresults = $oResult[$k]->size();
192 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
193 $show_next = 1 if $numresults >= ($page*20);
194 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
195 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
196 if ( $oResult[$k]->record($i) ) {
198 ( $res, $error ) = _handle_one_result( $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, $xslh ); #ignores error in sequence numbering
199 push @breeding_loop, $res if $res;
200 push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i+1 } if $error;
203 push @errconn, { 'server' => $servers[$k]->{servername}, error => ( ( $oConnection[$k]->error_x() )[0] ), seq => $i+1 };
211 numberpending => $nremaining,
212 current_page => $page,
213 total_pages => $total_pages,
214 show_nextbutton => $show_next?1:0,
215 show_prevbutton => $page!=1,
219 #close result sets and connections
221 $oResult[$_]->destroy();
222 $oConnection[$_]->destroy();
226 breeding_loop => \@breeding_loop,
227 servers => \@servers,
236 isbn => '@attr 1=7 @attr 5=1 "#term" ',
237 issn => '@attr 1=8 @attr 5=1 "#term" ',
238 title => '@attr 1=4 #term ',
239 author => '@attr 1=1003 "#term" ',
240 dewey => '@attr 1=16 "#term" ',
241 subject => '@attr 1=21 "#term" ',
242 lccall => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
243 '@attr 6=1 "#term" ',
244 controlnumber => '@attr 1=12 "#term" ',
245 srchany => '@attr 1=1016 "#term" ',
246 stdid => '@attr 1=1007 "#term" ',
252 foreach my $k ( keys %$pars ) {
253 if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
254 $qry_build->{$k} =~ s/#term/$val/g;
255 $zquery .= $qry_build->{$k};
256 $squery .= "[$k]=\"$val\" and ";
260 $zquery = "\@and " . $zquery for 2..$nterms;
261 $squery =~ s/ and $//;
262 return ( $zquery, $squery );
265 sub _handle_one_result {
266 my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_;
268 my $raw= $zoomrec->raw();
270 if( $servhref->{servertype} eq 'sru' ) {
271 $marcrecord= MARC::Record->new_from_xml( $raw, 'UTF-8',
272 $servhref->{syntax} );
274 ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
276 SetUTF8Flag($marcrecord);
278 ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh);
280 my $batch_id = GetZ3950BatchId($servhref->{servername});
281 my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0, 0);
282 #FIXME passing 0 for z3950random
283 #Will eliminate this unused field in a followup report
284 #Last zero indicates: no update for batch record counts
287 #call to TransformMarcToKoha replaced by next call
288 #we only need six fields from the marc record
292 biblionumber => $bib,
293 server => $servhref->{servername},
294 breedingid => $breedingid,
295 }, $marcrecord) if $breedingid;
296 return ( $row, $error );
300 my ( $marc, $server, $xslh ) = @_;
301 return $marc if !$server->{add_xslt};
303 my $htdocs = C4::Context->config('intrahtdocs');
304 my $theme = C4::Context->preference("template"); #staff
305 my $lang = C4::Languages::getlanguage() || 'en';
307 my @files= split ',', $server->{add_xslt};
308 my $xml = $marc->as_xml;
309 foreach my $f ( @files ) {
310 $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
311 $f = C4::XSLT::_get_best_default_xslt_filename(
312 $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
313 $xml = $xslh->transform( $xml, $f );
314 last if $xslh->err; #skip other files
317 return MARC::Record->new_from_xml($xml, 'UTF-8');
319 return ( $marc, 'xslt_err' ); #original record in case of errors
324 my ($row, $record)=@_;
326 title => 'biblio.title',
327 author => 'biblio.author',
328 isbn =>'biblioitems.isbn',
329 lccn =>'biblioitems.lccn', #LC control number (not call number)
330 edition =>'biblioitems.editionstatement',
331 date => 'biblio.copyrightdate', #MARC21
332 date2 => 'biblioitems.publicationyear', #UNIMARC
334 foreach my $k (keys %fetch) {
335 my ($t, $f)= split '\.', $fetch{$k};
336 $row= C4::Biblio::TransformMarcToKohaOneField($t, $f, $record, $row);
337 $row->{$k}= $row->{$f} if $k ne $f;
339 $row->{date}//= $row->{date2};
340 $row->{isbn}=_isbn_replace($row->{isbn});
346 return unless defined $isbn;
347 $isbn =~ s/ |-|\.//g;
348 $isbn =~ s/\|/ \| /g;
353 sub _create_connection {
355 my $option1= new ZOOM::Options();
356 $option1->option( 'async' => 1 );
357 $option1->option( 'elementSetName', 'F' );
358 $option1->option( 'preferredRecordSyntax', $server->{syntax} );
359 $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
361 if( $server->{servertype} eq 'sru' ) {
362 foreach( split ',', $server->{sru_options}//'' ) {
363 #first remove surrounding spaces at comma and equals-sign
365 my @temp= split '=', $_, 2;
366 @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
367 $option1->option( $temp[0] => $temp[1] ) if @temp;
369 } elsif( $server->{servertype} eq 'zed' ) {
370 $option1->option( 'databaseName', $server->{db} );
371 $option1->option( 'user', $server->{userid} ) if $server->{userid};
372 $option1->option( 'password', $server->{password} ) if $server->{password};
375 my $obj= ZOOM::Connection->create($option1);
376 if( $server->{servertype} eq 'sru' ) {
377 my $host= $server->{host};
378 if( $host !~ /^https?:\/\// ) {
379 #Normally, host will not be prefixed by protocol.
380 #In that case we can (safely) assume http.
381 #In case someone prefixed with https, give it a try..
382 $host = 'http://' . $host;
384 $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
386 $obj->connect( $server->{host}, $server->{port} );
391 sub _translate_query { #SRU query adjusted per server cf. srufields column
392 my ($server, $query) = @_;
394 #sru_fields is in format title=field,isbn=field,...
395 #if a field doesn't exist, try anywhere or remove [field]=
396 my @parts= split(',', $server->{sru_fields} );
397 my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
398 my $any= $trans{srchany}?$trans{srchany}.'=':'';
401 foreach my $key (keys %trans) {
406 $q=~s/\[$key\]=/$any/g;
409 $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
413 =head2 ImportBreedingAuth
415 ImportBreedingAuth($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random,$batch_type);
417 ImportBreedingAuth imports MARC records in the reservoir (import_records table).
418 ImportBreedingAuth is based on the ImportBreeding subroutine.
422 sub ImportBreedingAuth {
423 my ($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random,$batch_type) = @_;
424 my @marcarray = split /\x1D/, $marcrecords;
426 my $dbh = C4::Context->dbh;
428 my $batch_id = GetZ3950BatchId($filename);
429 my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
431 # $encoding = C4::Context->preference("marcflavour") unless $encoding;
432 # fields used for import results
435 my $alreadyinfarm = 0;
436 my $notmarcrecord = 0;
438 for (my $i=0;$i<=$#marcarray;$i++) {
439 my ($marcrecord, $charset_result, $charset_errors);
440 ($marcrecord, $charset_result, $charset_errors) =
441 MarcToUTF8Record($marcarray[$i]."\x1D", C4::Context->preference("marcflavour"), $encoding);
443 # Normalize the record so it doesn't have separated diacritics
444 SetUTF8Flag($marcrecord);
446 if (scalar($marcrecord->fields()) == 0) {
450 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
452 my $heading_authtype_code;
453 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
456 $controlnumber = $marcrecord->field('001')->data;
458 #Check if the authority record already exists in the database...
459 my ($duplicateauthid,$duplicateauthvalue);
460 if ($marcrecord && $heading_authtype_code) {
461 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
464 if ($duplicateauthid && $overwrite_auth ne 2) {
465 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
468 if ($controlnumber && $heading) {
469 $searchbreeding->execute($controlnumber,$heading);
470 ($breedingid) = $searchbreeding->fetchrow;
472 if ($breedingid && $overwrite_auth eq '0') {
475 if ($breedingid && $overwrite_auth eq '1') {
476 ModAuthorityInBatch($breedingid, $marcrecord);
478 my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
479 $breedingid = $import_id;
486 return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
489 =head2 Z3950SearchAuth
491 Z3950SearchAuth($pars, $template);
493 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
494 title, uniform title, subject, subjectsubdiv, srchany.
495 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
496 This code is used in cataloging/z3950_auth_search.
497 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
501 sub Z3950SearchAuth {
502 my ($pars, $template)= @_;
504 my $dbh = C4::Context->dbh;
505 my @id= @{$pars->{id}};
506 my $random= $pars->{random};
507 my $page= $pars->{page};
509 my $nameany= $pars->{nameany};
510 my $authorany= $pars->{authorany};
511 my $authorpersonal= $pars->{authorpersonal};
512 my $authorcorp= $pars->{authorcorp};
513 my $authormeetingcon= $pars->{authormeetingcon};
514 my $title= $pars->{title};
515 my $uniformtitle= $pars->{uniformtitle};
516 my $subject= $pars->{subject};
517 my $subjectsubdiv= $pars->{subjectsubdiv};
518 my $srchany= $pars->{srchany};
534 my @breeding_loop = ();
544 $query .= " \@attr 1=1002 \"$nameany\" "; #Any name (this includes personal, corporate, meeting/conference authors, and author names in subject headings)
545 #This attribute is supported by both the Library of Congress and Libraries Australia 08/05/2013
550 $query .= " \@attr 1=1003 \"$authorany\" "; #Author-name (this includes personal, corporate, meeting/conference authors, but not author names in subject headings)
551 #This attribute is not supported by the Library of Congress, but is supported by Libraries Australia 08/05/2013
556 $query .= " \@attr 1=2 \"$authorcorp\" "; #1005 is another valid corporate author attribute...
560 if ($authorpersonal) {
561 $query .= " \@attr 1=1 \"$authorpersonal\" "; #1004 is another valid personal name attribute...
565 if ($authormeetingcon) {
566 $query .= " \@attr 1=3 \"$authormeetingcon\" "; #1006 is another valid meeting/conference name attribute...
571 $query .= " \@attr 1=21 \"$subject\" ";
575 if ($subjectsubdiv) {
576 $query .= " \@attr 1=47 \"$subjectsubdiv\" ";
581 $query .= " \@attr 1=4 \"$title\" "; #This is a regular title search. 1=6 will give just uniform titles
586 $query .= " \@attr 1=6 \"$uniformtitle\" "; #This is the uniform title search
591 $query .= " \@attr 1=1016 \"$srchany\" ";
595 for my $i (1..$nterms-1) {
596 $query = "\@and " . $query;
599 foreach my $servid (@id) {
600 my $sth = $dbh->prepare("select * from z3950servers where id=?");
601 $sth->execute($servid);
602 while ( $server = $sth->fetchrow_hashref ) {
603 my $option1 = new ZOOM::Options();
604 $option1->option( 'async' => 1 );
605 $option1->option( 'elementSetName', 'F' );
606 $option1->option( 'databaseName', $server->{db} );
607 $option1->option( 'user', $server->{userid} ) if $server->{userid};
608 $option1->option( 'password', $server->{password} ) if $server->{password};
609 $option1->option( 'preferredRecordSyntax', $server->{syntax} );
610 $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
611 $oConnection[$s] = create ZOOM::Connection($option1);
612 $oConnection[$s]->connect( $server->{host}, $server->{port} );
613 $serverhost[$s] = $server->{host};
614 $servername[$s] = $server->{name};
615 $encoding[$s] = ($server->{encoding}?$server->{encoding}:"iso-5426");
621 for ( my $z = 0 ; $z < $s ; $z++ ) {
622 $oResult[$z] = $oConnection[$z]->search_pqf($query);
625 while ( $nremaining-- ) {
628 while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
629 $event = $oConnection[ $k - 1 ]->last_event();
630 last if $event == ZOOM::Event::ZEND;
635 my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
637 if ($error =~ m/^(10000|10007)$/ ) {
638 push(@errconn, {'server' => $serverhost[$k]});
642 my $numresults = $oResult[$k]->size();
645 if ( $numresults > 0 and $numresults >= (($page-1)*20)) {
646 $show_next = 1 if $numresults >= ($page*20);
647 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
648 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
649 my $rec = $oResult[$k]->record($i);
653 $marcdata = $rec->raw();
655 my ($charset_result, $charset_errors);
656 ($marcrecord, $charset_result, $charset_errors)= MarcToUTF8Record($marcdata, C4::Context->preference('marcflavour'), $encoding[$k]);
659 my $heading_authtype_code;
660 $heading_authtype_code = GuessAuthTypeCode($marcrecord);
661 $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
663 my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcdata, 2, $serverhost[$k], $encoding[$k], $random, 'z3950' );
665 $row_data{server} = $servername[$k];
666 $row_data{breedingid} = $breedingid;
667 $row_data{heading} = $heading;
668 $row_data{heading_code} = $heading_authtype_code;
669 push( @breeding_loop, \%row_data );
672 push(@breeding_loop,{'server'=>$servername[$k],'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1});
680 numberpending => $nremaining,
681 current_page => $page,
682 total_pages => $total_pages,
683 show_nextbutton => $show_next?1:0,
684 show_prevbutton => $page!=1,
688 #close result sets and connections
690 $oResult[$_]->destroy();
691 $oConnection[$_]->destroy();
695 foreach my $id (@id) {
696 push @servers, {id => $id};
699 breeding_loop => \@breeding_loop,
700 servers => \@servers,