Bug 18433: Add missing filter
[koha.git] / C4 / Breeding.pm
1 package C4::Breeding;
2
3 # Copyright 2000-2002 Katipo Communications
4 # Parts Copyright 2013 Prosentient Systems
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 use strict;
22 use warnings;
23
24 use C4::Biblio;
25 use C4::Koha;
26 use C4::Charset;
27 use MARC::File::USMARC;
28 use MARC::Field;
29 use C4::ImportBatch;
30 use C4::AuthoritiesMarc; #GuessAuthTypeCode, FindDuplicateAuthority
31 use C4::Languages;
32 use Koha::Database;
33 use Koha::XSLT_Handler;
34
35 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
36
37 BEGIN {
38         require Exporter;
39         @ISA = qw(Exporter);
40     @EXPORT = qw(&BreedingSearch &Z3950Search &Z3950SearchAuth);
41 }
42
43 =head1 NAME
44
45 C4::Breeding : module to add biblios to import_records via
46                the breeding/reservoir API.
47
48 =head1 SYNOPSIS
49
50     Z3950Search($pars, $template);
51     ($count, @results) = &BreedingSearch($title,$isbn);
52
53 =head1 DESCRIPTION
54
55 This module contains routines related to Koha's Z39.50 search into
56 cataloguing reservoir features.
57
58 =head2 BreedingSearch
59
60 ($count, @results) = &BreedingSearch($title,$isbn);
61 C<$title> contains the title,
62 C<$isbn> contains isbn or issn,
63
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.
67
68 =cut
69
70 sub BreedingSearch {
71     my ($search,$isbn) = @_;
72     my $dbh   = C4::Context->dbh;
73     my $count = 0;
74     my ($query,@bind);
75     my $sth;
76     my @results;
77
78     # normalise ISBN like at import
79     $isbn = C4::Koha::GetNormalizedISBN($isbn);
80
81     $query = "SELECT import_record_id, file_name, isbn, title, author
82               FROM  import_biblios 
83               JOIN import_records USING (import_record_id)
84               JOIN import_batches USING (import_batch_id)
85               WHERE ";
86     @bind=();
87     if (defined($search) && length($search)>0) {
88         $search =~ s/(\s+)/\%/g;
89         $query .= "title like ? OR author like ?";
90         push(@bind,"%$search%", "%$search%");
91     }
92     if ($#bind!=-1 && defined($isbn) && length($isbn)>0) {
93         $query .= " and ";
94     }
95     if (defined($isbn) && length($isbn)>0) {
96         $query .= "isbn like ?";
97         push(@bind,"$isbn%");
98     }
99     $sth = $dbh->prepare($query);
100     $sth->execute(@bind);
101     while (my $data = $sth->fetchrow_hashref) {
102             $results[$count] = $data;
103             # FIXME - hack to reflect difference in name 
104             # of columns in old marc_breeding and import_records
105             # There needs to be more separation between column names and 
106             # field names used in the templates </soapbox>
107             $data->{'file'} = $data->{'file_name'};
108             $data->{'id'} = $data->{'import_record_id'};
109             $count++;
110     } # while
111
112     $sth->finish;
113     return($count, @results);
114 } # sub breedingsearch
115
116
117 =head2 Z3950Search
118
119 Z3950Search($pars, $template);
120
121 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
122 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).
123 This code is used in acqui/z3950_search and cataloging/z3950_search.
124 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
125
126 =cut
127
128 sub Z3950Search {
129     my ($pars, $template)= @_;
130
131     my @id= @{$pars->{id}};
132     my $page= $pars->{page};
133     my $biblionumber= $pars->{biblionumber};
134
135     my $show_next       = 0;
136     my $total_pages     = 0;
137     my @results;
138     my @breeding_loop = ();
139     my @oConnection;
140     my @oResult;
141     my @errconn;
142     my $s = 0;
143     my $imported=0;
144
145     my ( $zquery, $squery ) = _bib_build_query( $pars );
146
147     my $schema = Koha::Database->new()->schema();
148     my $rs = $schema->resultset('Z3950server')->search(
149         { id => [ @id ] },
150         { result_class => 'DBIx::Class::ResultClass::HashRefInflator' },
151     );
152     my @servers = $rs->all;
153     foreach my $server ( @servers ) {
154         $oConnection[$s] = _create_connection( $server );
155         $oResult[$s] =
156             $server->{servertype} eq 'zed'?
157                 $oConnection[$s]->search_pqf( $zquery ):
158                 $oConnection[$s]->search(new ZOOM::Query::CQL(
159                     _translate_query( $server, $squery )));
160         $s++;
161     }
162     my $xslh = Koha::XSLT_Handler->new;
163
164     my $nremaining = $s;
165     while ( $nremaining-- ) {
166         my $k;
167         my $event;
168         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
169             $event = $oConnection[ $k - 1 ]->last_event();
170             last if $event == ZOOM::Event::ZEND;
171         }
172
173         if ( $k != 0 ) {
174             $k--;
175             my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
176             if ($error) {
177                 if ($error =~ m/^(10000|10007)$/ ) {
178                     push(@errconn, { server => $servers[$k]->{host}, error => $error } );
179                 }
180             }
181             else {
182                 my $numresults = $oResult[$k]->size();
183                 my $i;
184                 my $res;
185                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
186                     $show_next = 1 if $numresults >= ($page*20);
187                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
188                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
189                         if ( $oResult[$k]->record($i) ) {
190                             undef $error;
191                             ( $res, $error ) = _handle_one_result( $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, $xslh ); #ignores error in sequence numbering
192                             push @breeding_loop, $res if $res;
193                             push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i+1 } if $error;
194                         }
195                         else {
196                             push @errconn, { 'server' => $servers[$k]->{servername}, error => ( ( $oConnection[$k]->error_x() )[0] ), seq => $i+1 };
197                         }
198                     }
199                 }    #if $numresults
200             }
201         }    # if $k !=0
202
203         $template->param(
204             numberpending => $nremaining,
205             current_page => $page,
206             total_pages => $total_pages,
207             show_nextbutton => $show_next?1:0,
208             show_prevbutton => $page!=1,
209         );
210     } # while nremaining
211
212     #close result sets and connections
213     foreach(0..$s-1) {
214         $oResult[$_]->destroy();
215         $oConnection[$_]->destroy();
216     }
217
218     $template->param(
219         breeding_loop => \@breeding_loop,
220         servers => \@servers,
221         errconn       => \@errconn
222     );
223 }
224
225 sub _auth_build_query {
226     my ( $pars ) = @_;
227
228     my $qry_build = {
229         nameany           => '@attr 1=1002 "#term" ',
230         authorany         => '@attr 1=1003 "#term" ',
231         authorcorp        => '@attr 1=2 "#term" ',
232         authorpersonal    => '@attr 1=1 "#term" ',
233         authormeetingcon  => '@attr 1=3 "#term" ',
234         subject           => '@attr 1=21 "#term" ',
235         subjectsubdiv     => '@attr 1=47 "#term" ',
236         title             => '@attr 1=4 "#term" ',
237         uniformtitle      => '@attr 1=6 "#term" ',
238         srchany           => '@attr 1=1016 "#term" ',
239         controlnumber     => '@attr 1=12 "#term" ',
240     };
241
242     return _build_query( $pars, $qry_build );
243 }
244
245 sub _bib_build_query {
246
247     my ( $pars ) = @_;
248
249     my $qry_build = {
250         isbn    => '@attr 1=7 @attr 5=1 "#term" ',
251         issn    => '@attr 1=8 @attr 5=1 "#term" ',
252         title   => '@attr 1=4 "#term" ',
253         author  => '@attr 1=1003 "#term" ',
254         dewey   => '@attr 1=16 "#term" ',
255         subject => '@attr 1=21 "#term" ',
256         lccall  => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
257                    '@attr 6=1 "#term" ',
258         controlnumber => '@attr 1=12 "#term" ',
259         srchany => '@attr 1=1016 "#term" ',
260         stdid   => '@attr 1=1007 "#term" ',
261         publicationyear => '@attr 1=31 "#term" '
262     };
263
264     return _build_query( $pars, $qry_build );
265 }
266
267 sub _build_query {
268
269     my ( $pars, $qry_build ) = @_;
270
271     my $zquery='';
272     my $squery='';
273     my $nterms=0;
274     foreach my $k ( sort keys %$pars ) {
275     #note that the sort keys forces an identical result under Perl 5.18
276     #one of the unit tests is based on that assumption
277         if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
278             $qry_build->{$k} =~ s/#term/$val/g;
279             $zquery .= $qry_build->{$k};
280             $squery .= "[$k]=\"$val\" and ";
281             $nterms++;
282         }
283     }
284     $zquery = "\@and " . $zquery for 2..$nterms;
285     $squery =~ s/ and $//;
286     return ( $zquery, $squery );
287 }
288
289 sub _handle_one_result {
290     my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_;
291
292     my $raw= $zoomrec->raw();
293     my $marcrecord;
294     if( $servhref->{servertype} eq 'sru' ) {
295         $marcrecord= MARC::Record->new_from_xml( $raw, 'UTF-8',
296             $servhref->{syntax} );
297     } else {
298         ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
299     }
300     SetUTF8Flag($marcrecord);
301     my $error;
302     ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh);
303
304     my $batch_id = GetZ3950BatchId($servhref->{servername});
305     my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0);
306         #Last zero indicates: no update for batch record counts
307
308
309     #call to TransformMarcToKoha replaced by next call
310     #we only need six fields from the marc record
311     my $row;
312     $row = _add_rowdata(
313         {
314             biblionumber => $bib,
315             server       => $servhref->{servername},
316             breedingid   => $breedingid,
317         }, $marcrecord) if $breedingid;
318     return ( $row, $error );
319 }
320
321 sub _do_xslt_proc {
322     my ( $marc, $server, $xslh ) = @_;
323     return $marc if !$server->{add_xslt};
324
325     my $htdocs = C4::Context->config('intrahtdocs');
326     my $theme = C4::Context->preference("template"); #staff
327     my $lang = C4::Languages::getlanguage() || 'en';
328
329     my @files= split ',', $server->{add_xslt};
330     my $xml = $marc->as_xml;
331     foreach my $f ( @files ) {
332         $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
333         $f = C4::XSLT::_get_best_default_xslt_filename(
334             $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
335         $xml = $xslh->transform( $xml, $f );
336         last if $xslh->err; #skip other files
337     }
338     if( !$xslh->err ) {
339         return MARC::Record->new_from_xml($xml, 'UTF-8');
340     } else {
341         return ( $marc, $xslh->err ); #original record in case of errors
342     }
343 }
344
345 sub _add_rowdata {
346     my ($row, $record)=@_;
347     my %fetch= (
348         title => 'biblio.title',
349         author => 'biblio.author',
350         isbn =>'biblioitems.isbn',
351         lccn =>'biblioitems.lccn', #LC control number (not call number)
352         edition =>'biblioitems.editionstatement'
353     );
354     $fetch{date} = C4::Context->preference('marcflavour') eq "MARC21" ? 'biblio.copyrightdate' : 'biblioitems.publicationyear';
355
356     foreach my $k (keys %fetch) {
357         $row->{$k} = C4::Biblio::TransformMarcToKohaOneField( $fetch{$k}, $record );
358     }
359     $row->{date}//= $row->{date2};
360     $row->{isbn}=_isbn_replace($row->{isbn});
361
362     $row = _add_custom_field_rowdata($row, $record);
363
364     return $row;
365 }
366
367 sub _add_custom_field_rowdata
368 {
369     my ( $row, $record ) = @_;
370     my $pref_newtags = C4::Context->preference('AdditionalFieldsInZ3950ResultSearch');
371     my $pref_flavour = C4::Context->preference('MarcFlavour');
372
373     $pref_newtags =~ s/^\s+|\s+$//g;
374     $pref_newtags =~ s/\h+/ /g;
375
376     my @addnumberfields;
377
378     foreach my $field (split /\,/, $pref_newtags) {
379         $field =~ s/^\s+|\s+$//g ;  # trim whitespace
380         my ($tag, $subtags) = split(/\$/, $field);
381
382         if ( $record->field($tag) ) {
383             my @content = ();
384
385             for my $marcfield ($record->field($tag)) {
386                 if ( $subtags ) {
387                     my $str = '';
388                     for my $code (split //, $subtags) {
389                         if ( $marcfield->subfield($code) ) {
390                             $str .= $marcfield->subfield($code) . ' ';
391                         }
392                     }
393                     if ( not $str eq '') {
394                         push @content, $str;
395                     }
396                 } elsif ( $tag == 10 ) {
397                     push @content, ( $pref_flavour eq "MARC21" ? $marcfield->data : $marcfield->as_string );
398                 } elsif ( $tag < 10 ) {
399                     push @content, $marcfield->data();
400                 } else {
401                     push @content, $marcfield->as_string();
402                 }
403             }
404
405             if ( @content ) {
406                 $row->{$field} = \@content;
407                 push( @addnumberfields, $field );
408             }
409         }
410     }
411
412     $row->{'addnumberfields'} = \@addnumberfields;
413
414     return $row;
415 }
416
417 sub _isbn_replace {
418     my ($isbn) = @_;
419     return unless defined $isbn;
420     $isbn =~ s/ |-|\.//g;
421     $isbn =~ s/\|/ \| /g;
422     $isbn =~ s/\(/ \(/g;
423     return $isbn;
424 }
425
426 sub _create_connection {
427     my ( $server ) = @_;
428     my $option1= new ZOOM::Options();
429     $option1->option( 'async' => 1 );
430     $option1->option( 'elementSetName', 'F' );
431     $option1->option( 'preferredRecordSyntax', $server->{syntax} );
432     $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
433
434     if( $server->{servertype} eq 'sru' ) {
435         foreach( split ',', $server->{sru_options}//'' ) {
436             #first remove surrounding spaces at comma and equals-sign
437             s/^\s+|\s+$//g;
438             my @temp= split '=', $_, 2;
439             @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
440             $option1->option( $temp[0] => $temp[1] ) if @temp;
441         }
442     } elsif( $server->{servertype} eq 'zed' ) {
443         $option1->option( 'databaseName',   $server->{db} );
444         $option1->option( 'user', $server->{userid} ) if $server->{userid};
445         $option1->option( 'password', $server->{password} ) if $server->{password};
446     }
447     my $obj= ZOOM::Connection->create($option1);
448     if( $server->{servertype} eq 'sru' ) {
449         my $host= $server->{host};
450         if( $host !~ /^https?:\/\// ) {
451             #Normally, host will not be prefixed by protocol.
452             #In that case we can (safely) assume http.
453             #In case someone prefixed with https, give it a try..
454             $host = 'http://' . $host;
455         }
456         $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
457     } else {
458         $obj->connect( $server->{host}, $server->{port} );
459     }
460     return $obj;
461 }
462
463 sub _translate_query { #SRU query adjusted per server cf. srufields column
464     my ($server, $query) = @_;
465
466     #sru_fields is in format title=field,isbn=field,...
467     #if a field doesn't exist, try anywhere or remove [field]=
468     my @parts= split(',', $server->{sru_fields} );
469     my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
470     my $any= $trans{srchany}?$trans{srchany}.'=':'';
471
472     my $q=$query;
473     foreach my $key (keys %trans) {
474         my $f=$trans{$key};
475         if( $f ) {
476             $q=~s/\[$key\]/$f/g;
477         } else {
478             $q=~s/\[$key\]=/$any/g;
479         }
480     }
481     $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
482     return $q;
483 }
484
485 =head2 ImportBreedingAuth
486
487 ImportBreedingAuth( $marcrecord, $filename, $encoding, $heading );
488
489     ImportBreedingAuth imports MARC records in the reservoir (import_records table) or returns their id if they already exist.
490
491 =cut
492
493 sub ImportBreedingAuth {
494     my ( $marcrecord, $filename, $encoding, $heading ) = @_;
495     my $dbh = C4::Context->dbh;
496
497     my $batch_id = GetZ3950BatchId($filename);
498     my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
499
500     my $controlnumber = $marcrecord->field('001')->data;
501
502     # Normalize the record so it doesn't have separated diacritics
503     SetUTF8Flag($marcrecord);
504
505     $searchbreeding->execute($controlnumber,$heading);
506     my ($breedingid) = $searchbreeding->fetchrow;
507
508     return $breedingid if $breedingid;
509     $breedingid = AddAuthToBatch($batch_id, 0, $marcrecord, $encoding);
510     return $breedingid;
511 }
512
513 =head2 Z3950SearchAuth
514
515 Z3950SearchAuth($pars, $template);
516
517 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
518 title, uniform title, subject, subjectsubdiv, srchany.
519 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
520 This code is used in cataloging/z3950_auth_search.
521 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
522
523 =cut
524
525 sub Z3950SearchAuth {
526     my ($pars, $template)= @_;
527
528     my $dbh   = C4::Context->dbh;
529     my @id= @{$pars->{id}};
530     my $page= $pars->{page};
531
532
533     my $show_next       = 0;
534     my $total_pages     = 0;
535     my @encoding;
536     my @results;
537     my @serverhost;
538     my @breeding_loop = ();
539     my @oConnection;
540     my @oResult;
541     my @errconn;
542     my @servers;
543     my $s = 0;
544     my $query;
545     my $nterms=0;
546
547     my $marcflavour = C4::Context->preference('marcflavour');
548     my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
549     my $authid= $pars->{authid};
550     my ( $zquery, $squery ) = _auth_build_query( $pars );
551     foreach my $servid (@id) {
552         my $sth = $dbh->prepare("select * from z3950servers where id=?");
553         $sth->execute($servid);
554         while ( my $server = $sth->fetchrow_hashref ) {
555             $oConnection[$s] = _create_connection( $server );
556
557             $oResult[$s] =
558             $server->{servertype} eq 'zed'?
559                 $oConnection[$s]->search_pqf( $zquery ):
560                 $oConnection[$s]->search(new ZOOM::Query::CQL(
561                     _translate_query( $server, $squery )));
562             $encoding[$s]   = $server->{encoding} // "iso-5426";
563             $servers[$s] = $server;
564             $s++;
565         }   ## while fetch
566     }    # foreach
567     my $nremaining  = $s;
568
569     while ( $nremaining-- ) {
570         my $k;
571         my $event;
572         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
573             $event = $oConnection[ $k - 1 ]->last_event();
574             last if $event == ZOOM::Event::ZEND;
575         }
576
577         if ( $k != 0 ) {
578             $k--;
579             my ($error )= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
580             if ($error) {
581                 if ($error =~ m/^(10000|10007)$/ ) {
582                     push(@errconn, {'server' => $serverhost[$k]});
583                 }
584             }
585             else {
586                 my $numresults = $oResult[$k]->size();
587                 my $i;
588                 my $result = '';
589                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
590                     $show_next = 1 if $numresults >= ($page*20);
591                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
592                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
593                         my $rec = $oResult[$k]->record($i);
594                         if ($rec) {
595                             my $marcrecord;
596                             my $marcdata;
597                             $marcdata   = $rec->raw();
598
599                             my ($charset_result, $charset_errors);
600                             if( $servers[$k]->{servertype} eq 'sru' ) {
601                                 $marcrecord = MARC::Record->new_from_xml( $marcdata, 'UTF-8', $servers[$k]->{syntax} );
602                             } else {
603                                 ( $marcrecord, $charset_result, $charset_errors ) = MarcToUTF8Record( $marcdata, $marc_type, $encoding[$k] );
604                             }
605                             my $heading;
606                             my $heading_authtype_code;
607                             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
608                             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
609
610                             my $breedingid = ImportBreedingAuth( $marcrecord, $serverhost[$k], $encoding[$k], $heading );
611                             my %row_data;
612                             $row_data{server}       = $servers[$k]->{'servername'};
613                             $row_data{breedingid}   = $breedingid;
614                             $row_data{heading}      = $heading;
615                             $row_data{authid}       = $authid;
616                             $row_data{heading_code}      = $heading_authtype_code;
617                             push( @breeding_loop, \%row_data );
618                         }
619                         else {
620                             push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1});
621                         }
622                     }
623                 }    #if $numresults
624             }
625         }    # if $k !=0
626
627         $template->param(
628             numberpending => $nremaining,
629             current_page => $page,
630             total_pages => $total_pages,
631             show_nextbutton => $show_next?1:0,
632             show_prevbutton => $page!=1,
633         );
634     } # while nremaining
635
636     #close result sets and connections
637     foreach(0..$s-1) {
638         $oResult[$_]->destroy();
639         $oConnection[$_]->destroy();
640     }
641
642     @servers = ();
643     foreach my $id (@id) {
644         push @servers, {id => $id};
645     }
646     $template->param(
647         breeding_loop => \@breeding_loop,
648         servers => \@servers,
649         errconn       => \@errconn
650     );
651 }
652
653 1;
654 __END__
655