Merge remote-tracking branch 'kc/master' into new/bug_5683
[koha.git] / misc / migration_tools / bulkmarcimport.pl
1 #!/usr/bin/perl
2 # Import an iso2709 file into Koha 3
3
4 use strict;
5 use warnings;
6 #use diagnostics;
7 BEGIN {
8     # find Koha's Perl modules
9     # test carefully before changing this
10     use FindBin;
11     eval { require "$FindBin::Bin/../kohalib.pl" };
12 }
13
14 # Koha modules used
15 use MARC::File::USMARC;
16 use MARC::File::XML;
17 use MARC::Record;
18 use MARC::Batch;
19 use MARC::Charset;
20
21 use C4::Context;
22 use C4::Biblio;
23 use C4::Koha;
24 use C4::Debug;
25 use C4::Charset;
26 use C4::Items;
27 use Unicode::Normalize;
28 use Time::HiRes qw(gettimeofday);
29 use Getopt::Long;
30 use IO::File;
31 use Pod::Usage;
32
33 binmode(STDOUT, ":utf8");
34 my ( $input_marc_file, $number, $offset) = ('',0,0);
35 my ($version, $delete, $test_parameter, $skip_marc8_conversion, $char_encoding, $verbose, $commit, $fk_off,$format,$biblios,$authorities,$keepids,$match, $isbn_check, $logfile);
36 my ($sourcetag,$sourcesubfield,$idmapfl);
37 my $cleanisbn = 1;
38
39 $|=1;
40
41 GetOptions(
42     'commit:f'    => \$commit,
43     'file:s'    => \$input_marc_file,
44     'n:f' => \$number,
45     'o|offset:f' => \$offset,
46     'h' => \$version,
47     'd' => \$delete,
48     't' => \$test_parameter,
49     's' => \$skip_marc8_conversion,
50     'c:s' => \$char_encoding,
51     'v:s' => \$verbose,
52     'fk' => \$fk_off,
53     'm:s' => \$format,
54     'l:s' => \$logfile,
55     'k|keepids:s' => \$keepids,
56     'b|biblios' => \$biblios,
57     'a|authorities' => \$authorities,
58     'match=s@'    => \$match,
59     'i|isbn' => \$isbn_check,
60     'x:s' => \$sourcetag,
61     'y:s' => \$sourcesubfield,
62     'idmap:s' => \$idmapfl,
63     'cleanisbn!'     => \$cleanisbn,
64 );
65 $biblios=!$authorities||$biblios;
66
67 if ($version || ($input_marc_file eq '')) {
68     pod2usage( -verbose => 2 );
69     exit;
70 }
71
72 if (defined $idmapfl) {
73   open(IDMAP,">$idmapfl") or die "cannot open $idmapfl \n";
74 }
75
76 if ((not defined $sourcesubfield) && (not defined $sourcetag)){
77   $sourcetag="910";
78   $sourcesubfield="a";
79 }
80
81 my $dbh = C4::Context->dbh;
82
83 # save the CataloguingLog property : we don't want to log a bulkmarcimport. It will slow the import & 
84 # will create problems in the action_logs table, that can't handle more than 1 entry per second per user.
85 my $CataloguingLog = C4::Context->preference('CataloguingLog');
86 $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='CataloguingLog'");
87
88 if ($fk_off) {
89         $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
90 }
91
92
93 if ($delete) {
94         if ($biblios){
95         print "deleting biblios\n";
96         $dbh->do("truncate biblio");
97         $dbh->do("truncate biblioitems");
98         $dbh->do("truncate items");
99         }
100         else {
101         print "deleting authorities\n";
102         $dbh->do("truncate auth_header");
103         }
104     $dbh->do("truncate zebraqueue");
105 }
106
107
108
109 if ($test_parameter) {
110     print "TESTING MODE ONLY\n    DOING NOTHING\n===============\n";
111 }
112
113 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
114
115 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
116 my $starttime = gettimeofday;
117 my $batch;
118 my $fh = IO::File->new($input_marc_file); # don't let MARC::Batch open the file, as it applies the ':utf8' IO layer
119 if (defined $format && $format =~ /XML/i) {
120     # ugly hack follows -- MARC::File::XML, when used by MARC::Batch,
121     # appears to try to convert incoming XML records from MARC-8
122     # to UTF-8.  Setting the BinaryEncoding key turns that off
123     # TODO: see what happens to ISO-8859-1 XML files.
124     # TODO: determine if MARC::Batch can be fixed to handle
125     #       XML records properly -- it probably should be
126     #       be using a proper push or pull XML parser to
127     #       extract the records, not using regexes to look
128     #       for <record>.*</record>.
129     $MARC::File::XML::_load_args{BinaryEncoding} = 'utf-8';
130     my $recordformat= ($marcFlavour eq "MARC21"?"USMARC":uc($marcFlavour));
131 #UNIMARC Authorities have a different way to manage encoding than UNIMARC biblios.
132     $recordformat=$recordformat."AUTH" if ($authorities and $marcFlavour ne "MARC21");
133     $MARC::File::XML::_load_args{RecordFormat} = $recordformat;
134     $batch = MARC::Batch->new( 'XML', $fh );
135 } else {
136     $batch = MARC::Batch->new( 'USMARC', $fh );
137 }
138 $batch->warnings_off();
139 $batch->strict_off();
140 my $i=0;
141 my $commitnum = $commit ? $commit : 50;
142
143
144 # Skip file offset
145 if ( $offset ) {
146     print "Skipping file offset: $offset records\n";
147     $batch->next() while ($offset--);
148 }
149
150 my ($tagid,$subfieldid);
151 if ($authorities){
152           $tagid='001';
153 }
154 else {
155    ( $tagid, $subfieldid ) =
156             GetMarcFromKohaField( "biblio.biblionumber", '' );
157         $tagid||="001";
158 }
159
160 # the SQL query to search on isbn
161 my $sth_isbn = $dbh->prepare("SELECT biblionumber,biblioitemnumber FROM biblioitems WHERE isbn=?");
162
163 $dbh->{AutoCommit} = 0;
164 my $loghandle;
165 if ($logfile){
166    $loghandle= IO::File->new($logfile,"w") ;
167    print $loghandle "id;operation;status\n";
168 }
169 RECORD: while (  ) {
170     my $record;
171     # get records
172     eval { $record = $batch->next() };
173     if ( $@ ) {
174         print "Bad MARC record $i: $@ skipped\n";
175         # FIXME - because MARC::Batch->next() combines grabbing the next
176         # blob and parsing it into one operation, a correctable condition
177         # such as a MARC-8 record claiming that it's UTF-8 can't be recovered
178         # from because we don't have access to the original blob.  Note
179         # that the staging import can deal with this condition (via
180         # C4::Charset::MarcToUTF8Record) because it doesn't use MARC::Batch.
181         next;
182     }
183     # skip if we get an empty record (that is MARC valid, but will result in AddBiblio failure
184     last unless ( $record );
185     $i++;
186     print ".";
187     print "\r$i" unless $i % 100;
188     
189     # transcode the record to UTF8 if needed & applicable.
190     if ($record->encoding() eq 'MARC-8' and not $skip_marc8_conversion) {
191         # FIXME update condition
192         my ($guessed_charset, $charset_errors);
193          ($record, $guessed_charset, $charset_errors) = MarcToUTF8Record($record, $marcFlavour.(($authorities and $marcFlavour ne "MARC21")?'AUTH':''));
194         if ($guessed_charset eq 'failed') {
195             warn "ERROR: failed to perform character conversion for record $i\n";
196             next RECORD;            
197         }
198     }
199     my $isbn;
200     # remove trailing - in isbn (only for biblios, of course)
201     if ($biblios && $cleanisbn) {
202         my $tag = $marcFlavour eq 'UNIMARC' ? '010' : '020';
203         my $field = $record->field($tag);
204         my $isbn = $field && $field->subfield('a');
205         if ( $isbn ) {
206             $isbn =~ s/-//g;
207             $field->update('a' => $isbn);
208         }
209     }
210     my $id;
211     # search for duplicates (based on Local-number)
212     if ($match){
213        require C4::Search;
214        my $query=build_query($match,$record);
215        my $server=($authorities?'authorityserver':'biblioserver');
216        my ($error, $results,$totalhits)=C4::Search::SimpleSearch( $query, 0, 3, [$server] );
217        die "unable to search the database for duplicates : $error" if (defined $error);
218        #warn "$query $server : $totalhits";
219        if ( @{$results} == 1 ){
220            my $marcrecord = MARC::File::USMARC::decode($results->[0]);
221                    $id=GetRecordId($marcrecord,$tagid,$subfieldid);
222        } 
223        elsif  ( @{$results} > 1){
224            $debug && warn "more than one match for $query";
225        } 
226        else {
227            $debug && warn "nomatch for $query";
228        }
229     }
230         my $originalid;
231     if ($keepids){
232           $originalid=GetRecordId($record,$tagid,$subfieldid);
233       if ($originalid){
234                  my $storeidfield;
235                  if (length($keepids)==3){
236                         $storeidfield=MARC::Field->new($keepids,$originalid);
237                  }
238                  else  {
239                         $storeidfield=MARC::Field->new(substr($keepids,0,3),"","",substr($keepids,3,1),$originalid);
240                  }
241          $record->insert_fields_ordered($storeidfield);
242              $record->delete_field($record->field($tagid));
243       }
244     }
245     unless ($test_parameter) {
246         if ($authorities){
247             use C4::AuthoritiesMarc;
248             my $authtypecode=GuessAuthTypeCode($record);
249             my $authid= ($id?$id:GuessAuthId($record));
250             if ($authid && GetAuthority($authid)){
251             ## Authority has an id and is in database : Replace
252                 eval { ( $authid ) = ModAuthority($authid,$record, $authtypecode) };
253                 if ($@){
254                     warn "Problem with authority $authid Cannot Modify";
255                                         printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ERROR"}) if ($logfile);
256                 }
257                                 else{
258                                         printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ok"}) if ($logfile);
259                                 }
260             }  
261             elsif (defined $authid) {
262             ## An authid is defined but no authority in database : add
263                 eval { ( $authid ) = AddAuthority($record,$authid, $authtypecode) };
264                 if ($@){
265                     warn "Problem with authority $authid Cannot Add ".$@;
266                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
267                 }
268                                 else{
269                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
270                                 }
271             }
272                 else {
273             ## True insert in database
274                 eval { ( $authid ) = AddAuthority($record,"", $authtypecode) };
275                 if ($@){
276                     warn "Problem with authority $authid Cannot Add".$@;
277                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
278                 }
279                                 else{
280                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
281                                 }
282                 }
283         }
284         else {
285             my ( $biblionumber, $biblioitemnumber, $itemnumbers_ref, $errors_ref );
286             $biblionumber = $id;
287             # check for duplicate, based on ISBN (skip it if we already have found a duplicate with match parameter
288             if (!$biblionumber && $isbn_check && $isbn) {
289     #         warn "search ISBN : $isbn";
290                 $sth_isbn->execute($isbn);
291                 ($biblionumber,$biblioitemnumber) = $sth_isbn->fetchrow;
292             }
293                 if (defined $idmapfl) {
294                                 if ($sourcetag < "010"){
295                                         if ($record->field($sourcetag)){
296                                           my $source = $record->field($sourcetag)->data();
297                                           printf(IDMAP "%s|%s\n",$source,$biblionumber);
298                                         }
299                             } else {
300                                         my $source=$record->subfield($sourcetag,$sourcesubfield);
301                                         printf(IDMAP "%s|%s\n",$source,$biblionumber);
302                           }
303                         }
304                                         # create biblio, unless we already have it ( either match or isbn )
305             if ($biblionumber) {
306                                 eval{$biblioitemnumber=GetBiblioData($biblionumber)->{biblioitemnumber};}
307                         }
308                         else 
309                         {
310                 eval { ( $biblionumber, $biblioitemnumber ) = AddBiblio($record, '', { defer_marc_save => 1 }) };
311             }
312             if ( $@ ) {
313                 warn "ERROR: Adding biblio $biblionumber failed: $@\n";
314                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ERROR"}) if ($logfile);
315                 next RECORD;
316             } 
317                         else{
318                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
319                         }
320             eval { ( $itemnumbers_ref, $errors_ref ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
321             if ( $@ ) {
322                 warn "ERROR: Adding items to bib $biblionumber failed: $@\n";
323                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
324                 # if we failed because of an exception, assume that 
325                 # the MARC columns in biblioitems were not set.
326                 C4::Biblio::_strip_item_fields($record, '');
327                 ModBiblioMarc( $record, $biblionumber, '' );
328                 next RECORD;
329             } 
330                         else{
331                 C4::Biblio::_strip_item_fields($record, '');
332                 ModBiblioMarc( $record, $biblionumber, '' ); # need to call because of defer_marc_save
333                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
334                         }
335             if ($#{ $errors_ref } > -1) { 
336                 report_item_errors($biblionumber, $errors_ref);
337             }
338         }
339         $dbh->commit() if (0 == $i % $commitnum);
340     }
341     last if $i == $number;
342 }
343 $dbh->commit();
344
345
346
347 if ($fk_off) {
348         $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
349 }
350
351 # restore CataloguingLog
352 $dbh->do("UPDATE systempreferences SET value=$CataloguingLog WHERE variable='CataloguingLog'");
353
354 my $timeneeded = gettimeofday - $starttime;
355 print "\n$i MARC records done in $timeneeded seconds\n";
356 if ($logfile){
357   print $loghandle "file : $input_marc_file\n";
358   print $loghandle "$i MARC records done in $timeneeded seconds\n";
359   $loghandle->close;
360 }
361 exit 0;
362
363 sub GetRecordId{
364         my $marcrecord=shift;
365         my $tag=shift;
366         my $subfield=shift;
367         my $id;
368         if ($tag lt "010"){
369                 return $marcrecord->field($tag)->data() if $marcrecord->field($tag);
370         } 
371         elsif ($subfield){
372                 if ($marcrecord->field($tag)){
373                         return $marcrecord->subfield($tag,$subfield);
374                 }
375         }
376         return $id;
377 }
378 sub build_query {
379         my $match = shift;
380         my $record=shift;
381         my @searchstrings;
382         foreach my $matchingpoint (@$match){
383           my $string = build_simplequery($matchingpoint,$record);
384           push @searchstrings,$string if (length($string)>0);
385         }
386         return join(" and ",@searchstrings);
387 }
388 sub build_simplequery {
389         my $element=shift;
390         my $record=shift;
391         my ($index,$recorddata)=split /,/,$element;
392         my ($tag,$subfields) =($1,$2) if ($recorddata=~/(\d{3})(.*)/);
393         my @searchstrings;
394         foreach my $field ($record->field($tag)){
395                   if (length($field->as_string("$subfields"))>0){
396                 push @searchstrings,"$index,wrdl=\"".$field->as_string("$subfields")."\"";
397                   }
398         }
399         return join(" and ",@searchstrings);
400 }
401 sub report_item_errors {
402     my $biblionumber = shift;
403     my $errors_ref = shift;
404
405     foreach my $error (@{ $errors_ref }) {
406         my $msg = "Item not added (bib $biblionumber, item tag #$error->{'item_sequence'}, barcode $error->{'item_barcode'}): ";
407         my $error_code = $error->{'error_code'};
408         $error_code =~ s/_/ /g;
409         $msg .= "$error_code $error->{'error_information'}";
410         print $msg, "\n";
411     }
412 }
413 sub printlog{
414         my $logelements=shift;
415         print $loghandle join (";",@$logelements{qw<id op status>}),"\n";
416 }
417
418
419 =head1 NAME
420
421 bulkmarcimport.pl - Import bibliographic/authority records into Koha
422
423 =head1 USAGE
424
425  $ export KOHA_CONF=/etc/koha.conf
426  $ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 \\
427     -file /home/jmf/koha.mrc -n 3000
428
429 =head1 WARNING
430
431 Don't use this script before you've entered and checked your MARC parameters
432 tables twice (or more!). Otherwise, the import won't work correctly and you
433 will get invalid data.
434
435 =head1 DESCRIPTION
436
437 =over
438
439 =item  B<-h>
440
441 This version/help screen
442
443 =item B<-b, -biblios>
444
445 Type of import: bibliographic records
446
447 =item B<-a, -authorities>
448
449 Type of import: authority records
450
451 =item B<-file>=I<FILE>
452
453 The I<FILE> to import
454
455 =item  B<-v>
456
457 Verbose mode. 1 means "some infos", 2 means "MARC dumping"
458
459 =item B<-fk>
460
461 Turn off foreign key checks during import.
462
463 =item B<-n>=I<NUMBER>
464
465 The I<NUMBER> of records to import. If missing, all the file is imported
466
467 =item B<-o, -offset>=I<NUMBER>
468
469 File offset before importing, ie I<NUMBER> of records to skip.
470
471 =item B<-commit>=I<NUMBER>
472
473 The I<NUMBER> of records to wait before performing a 'commit' operation
474
475 =item B<-l>
476
477 File logs actions done for each record and their status into file
478
479 =item B<-t>
480
481 Test mode: parses the file, saying what he would do, but doing nothing.
482
483 =item B<-s>
484
485 Skip automatic conversion of MARC-8 to UTF-8.  This option is provided for
486 debugging.
487
488 =item B<-c>=I<CHARACTERISTIC>
489
490 The I<CHARACTERISTIC> MARC flavour. At the moment, only I<MARC21> and
491 I<UNIMARC> are supported. MARC21 by default.
492
493 =item B<-d>
494
495 Delete EVERYTHING related to biblio in koha-DB before import. Tables: biblio,
496 biblioitems, items
497
498 =item B<-m>=I<FORMAT>
499
500 Input file I<FORMAT>: I<MARCXML> or I<ISO2709> (defaults to ISO2709)
501
502 =item B<-k, -keepids>=<FIELD>
503
504 Field store ids in I<FIELD> (usefull for authorities, where 001 contains the
505 authid for Koha, that can contain a very valuable info for authorities coming
506 from LOC or BNF. useless for biblios probably)
507
508 =item B<-match>=<FIELD>
509
510 I<FIELD> matchindex,fieldtomatch matchpoint to use to deduplicate fieldtomatch
511 can be either 001 to 999 or field and list of subfields as such 100abcde
512
513 =item B<-i,-isbn>
514
515 If set, a search will be done on isbn, and, if the same isbn is found, the
516 biblio is not added. It's another method to deduplicate.  B<-match> & B<-isbn>
517 can be both set.
518
519 =item B<-cleanisbn>
520
521 Clean ISBN fields from entering biblio records, ie removes hyphens. By default,
522 ISBN are cleaned. --nocleanisbn will keep ISBN unchanged.
523
524 =item B<-x>=I<TAG>
525
526 Source bib I<TAG> for reporting the source bib number
527
528 =item B<-y>=I<SUBFIELD>
529
530 Source I<SUBFIELD> for reporting the source bib number
531
532 =item B<-idmap>=I<FILE>
533
534 I<FILE> for the koha bib and source id
535
536 =item B<-keepids>
537
538 Store ids in 009 (usefull for authorities, where 001 contains the authid for
539 Koha, that can contain a very valuable info for authorities coming from LOC or
540 BNF. useless for biblios probably)
541
542 =back
543
544 =cut
545