Bug 11278: Followup for customize command line parameter
[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 YAML;
28 use Unicode::Normalize;
29 use Time::HiRes qw(gettimeofday);
30 use Getopt::Long;
31 use IO::File;
32 use Pod::Usage;
33
34 use open qw( :std :encoding(UTF-8) );
35 binmode( STDOUT, ":encoding(UTF-8)" );
36 my ( $input_marc_file, $number, $offset) = ('',0,0);
37 my ($version, $delete, $test_parameter, $skip_marc8_conversion, $char_encoding, $verbose, $commit, $fk_off,$format,$biblios,$authorities,$keepids,$match, $isbn_check, $logfile);
38 my ( $insert, $filters, $update, $all, $yamlfile, $authtypes, $append );
39 my $cleanisbn = 1;
40 my ($sourcetag,$sourcesubfield,$idmapfl, $dedup_barcode);
41 my $framework = '';
42 my $localcust;
43
44 $|=1;
45
46 GetOptions(
47     'commit:f'    => \$commit,
48     'file:s'    => \$input_marc_file,
49     'n:f' => \$number,
50     'o|offset:f' => \$offset,
51     'h' => \$version,
52     'd' => \$delete,
53     't|test' => \$test_parameter,
54     's' => \$skip_marc8_conversion,
55     'c:s' => \$char_encoding,
56     'v:i' => \$verbose,
57     'fk' => \$fk_off,
58     'm:s' => \$format,
59     'l:s' => \$logfile,
60     'append' => \$append,
61     'k|keepids:s' => \$keepids,
62     'b|biblios' => \$biblios,
63     'a|authorities' => \$authorities,
64     'authtypes:s' => \$authtypes,
65     'filter=s@'     => \$filters,
66     'insert'        => \$insert,
67     'update'        => \$update,
68     'all'           => \$all,
69     'match=s@'    => \$match,
70     'i|isbn' => \$isbn_check,
71     'x:s' => \$sourcetag,
72     'y:s' => \$sourcesubfield,
73     'idmap:s' => \$idmapfl,
74     'cleanisbn!'     => \$cleanisbn,
75     'yaml:s'        => \$yamlfile,
76     'dedupbarcode' => \$dedup_barcode,
77     'framework=s' => \$framework,
78     'custom:s'    => \$localcust,
79 );
80 $biblios ||= !$authorities;
81 $insert  ||= !$update;
82 my $writemode = ($append) ? "a" : "w";
83
84 if ($all) {
85     $insert = 1;
86     $update = 1;
87 }
88
89 if ($version || ($input_marc_file eq '')) {
90     pod2usage( -verbose => 2 );
91     exit;
92 }
93
94 if(defined $localcust) { #local customize module
95     if(!-e $localcust) {
96         $localcust= $localcust||'LocalChanges'; #default name
97         $localcust=~ s/^.*\/([^\/]+)$/$1/; #extract file name only
98         $localcust=~ s/\.pm$//;           #remove extension
99         my $fqcust= $FindBin::Bin."/$localcust.pm"; #try migration_tools dir
100         if(-e $fqcust) {
101             $localcust= $fqcust;
102         }
103         else {
104             print "WARNING: customize module $localcust.pm not found!\n";
105             exit;
106         }
107     }
108     require $localcust if $localcust;
109     $localcust=\&customize if $localcust;
110 }
111
112 my $dbh = C4::Context->dbh;
113 my $heading_fields=get_heading_fields();
114
115 if (defined $idmapfl) {
116   open(IDMAP,">$idmapfl") or die "cannot open $idmapfl \n";
117 }
118
119 if ((not defined $sourcesubfield) && (not defined $sourcetag)){
120   $sourcetag="910";
121   $sourcesubfield="a";
122 }
123
124 # save the CataloguingLog property : we don't want to log a bulkmarcimport. It will slow the import & 
125 # will create problems in the action_logs table, that can't handle more than 1 entry per second per user.
126 my $CataloguingLog = C4::Context->preference('CataloguingLog');
127 $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='CataloguingLog'");
128
129 if ($fk_off) {
130         $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
131 }
132
133
134 if ($delete) {
135         if ($biblios){
136         print "deleting biblios\n";
137         $dbh->do("truncate biblio");
138         $dbh->do("truncate biblioitems");
139         $dbh->do("truncate items");
140         }
141         else {
142         print "deleting authorities\n";
143         $dbh->do("truncate auth_header");
144         }
145     $dbh->do("truncate zebraqueue");
146 }
147
148
149
150 if ($test_parameter) {
151     print "TESTING MODE ONLY\n    DOING NOTHING\n===============\n";
152 }
153
154 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
155
156 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
157 my $starttime = gettimeofday;
158 my $batch;
159 my $fh = IO::File->new($input_marc_file); # don't let MARC::Batch open the file, as it applies the ':utf8' IO layer
160 if (defined $format && $format =~ /XML/i) {
161     # ugly hack follows -- MARC::File::XML, when used by MARC::Batch,
162     # appears to try to convert incoming XML records from MARC-8
163     # to UTF-8.  Setting the BinaryEncoding key turns that off
164     # TODO: see what happens to ISO-8859-1 XML files.
165     # TODO: determine if MARC::Batch can be fixed to handle
166     #       XML records properly -- it probably should be
167     #       be using a proper push or pull XML parser to
168     #       extract the records, not using regexes to look
169     #       for <record>.*</record>.
170     $MARC::File::XML::_load_args{BinaryEncoding} = 'utf-8';
171     my $recordformat= ($marcFlavour eq "MARC21"?"USMARC":uc($marcFlavour));
172 #UNIMARC Authorities have a different way to manage encoding than UNIMARC biblios.
173     $recordformat=$recordformat."AUTH" if ($authorities and $marcFlavour ne "MARC21");
174     $MARC::File::XML::_load_args{RecordFormat} = $recordformat;
175     $batch = MARC::Batch->new( 'XML', $fh );
176 } else {
177     $batch = MARC::Batch->new( 'USMARC', $fh );
178 }
179 $batch->warnings_off();
180 $batch->strict_off();
181 my $i=0;
182 my $commitnum = $commit ? $commit : 50;
183 my $yamlhash;
184
185 # Skip file offset
186 if ( $offset ) {
187     print "Skipping file offset: $offset records\n";
188     $batch->next() while ($offset--);
189 }
190
191 my ($tagid,$subfieldid);
192 if ($authorities){
193           $tagid='001';
194 }
195 else {
196    ( $tagid, $subfieldid ) =
197             GetMarcFromKohaField( "biblio.biblionumber", $framework );
198         $tagid||="001";
199 }
200
201 # the SQL query to search on isbn
202 my $sth_isbn = $dbh->prepare("SELECT biblionumber,biblioitemnumber FROM biblioitems WHERE isbn=?");
203
204 $dbh->{AutoCommit} = 0;
205 my $loghandle;
206 if ($logfile){
207    $loghandle= IO::File->new($logfile, $writemode) ;
208    print $loghandle "id;operation;status\n";
209 }
210 RECORD: while (  ) {
211     my $record;
212     # get records
213     eval { $record = $batch->next() };
214     if ( $@ ) {
215         print "Bad MARC record $i: $@ skipped\n";
216         # FIXME - because MARC::Batch->next() combines grabbing the next
217         # blob and parsing it into one operation, a correctable condition
218         # such as a MARC-8 record claiming that it's UTF-8 can't be recovered
219         # from because we don't have access to the original blob.  Note
220         # that the staging import can deal with this condition (via
221         # C4::Charset::MarcToUTF8Record) because it doesn't use MARC::Batch.
222         next;
223     }
224     # skip if we get an empty record (that is MARC valid, but will result in AddBiblio failure
225     last unless ( $record );
226     $i++;
227     if( ($verbose//1)==1 ) { #no dot for verbose==2
228         print "." . ( $i % 100==0 ? "\n$i" : '' );
229     }
230
231     # transcode the record to UTF8 if needed & applicable.
232     if ($record->encoding() eq 'MARC-8' and not $skip_marc8_conversion) {
233         # FIXME update condition
234         my ($guessed_charset, $charset_errors);
235          ($record, $guessed_charset, $charset_errors) = MarcToUTF8Record($record, $marcFlavour.(($authorities and $marcFlavour ne "MARC21")?'AUTH':''));
236         if ($guessed_charset eq 'failed') {
237             warn "ERROR: failed to perform character conversion for record $i\n";
238             next RECORD;            
239         }
240     }
241     SetUTF8Flag($record);
242     &$localcust($record) if $localcust;
243     my $isbn;
244     # remove trailing - in isbn (only for biblios, of course)
245     if ($biblios && $cleanisbn) {
246         my $tag = $marcFlavour eq 'UNIMARC' ? '010' : '020';
247         my $field = $record->field($tag);
248         my $isbn = $field && $field->subfield('a');
249         if ( $isbn ) {
250             $isbn =~ s/-//g;
251             $field->update('a' => $isbn);
252         }
253     }
254     my $id;
255     # search for duplicates (based on Local-number)
256     my $originalid;
257     $originalid = GetRecordId( $record, $tagid, $subfieldid );
258     if ($match) {
259         require C4::Search;
260         my $query = build_query( $match, $record );
261         my $server = ( $authorities ? 'authorityserver' : 'biblioserver' );
262         $debug && warn $query;
263         my ( $error, $results, $totalhits ) = C4::Search::SimpleSearch( $query, 0, 3, [$server] );
264         die "unable to search the database for duplicates : $error" if ( defined $error );
265         $debug && warn "$query $server : $totalhits";
266         if ( $results && scalar(@$results) == 1 ) {
267             my $marcrecord = C4::Search::new_record_from_zebra( $server, $results->[0] );
268             SetUTF8Flag($marcrecord);
269             $id = GetRecordId( $marcrecord, $tagid, $subfieldid );
270             if ( $authorities && $marcFlavour ) {
271                 #Skip if authority in database is the same as the on in database
272                 if ( $marcrecord->field('005') && $record->field('005') &&
273                      $marcrecord->field('005')->data && $record->field('005')->data &&
274                      $marcrecord->field('005')->data >= $record->field('005')->data ) {
275                     if ($yamlfile) {
276                         $yamlhash->{$originalid}->{'authid'} = $id;
277
278                         # we recover all subfields of the heading authorities
279                         my @subfields;
280                         foreach my $field ( $marcrecord->field("2..") ) {
281                             push @subfields, map { ( $_->[0] =~ /[a-z]/ ? $_->[1] : () ) } $field->subfields();
282                         }
283                         $yamlhash->{$originalid}->{'subfields'} = \@subfields;
284                     }
285                     next;
286                 }
287             }
288         } elsif ( $results && scalar(@$results) > 1 ) {
289             $debug && warn "more than one match for $query";
290         } else {
291             $debug && warn "nomatch for $query";
292         }
293     }
294     if ($keepids && $originalid) {
295             my $storeidfield;
296             if ( length($keepids) == 3 ) {
297                 $storeidfield = MARC::Field->new( $keepids, $originalid );
298             } else {
299                 $storeidfield = MARC::Field->new( substr( $keepids, 0, 3 ), "", "", substr( $keepids, 3, 1 ), $originalid );
300             }
301             $record->insert_fields_ordered($storeidfield);
302             $record->delete_field( $record->field($tagid) );
303     }
304     foreach my $stringfilter (@$filters) {
305         if ( length($stringfilter) == 3 ) {
306             foreach my $field ( $record->field($stringfilter) ) {
307                 $record->delete_field($field);
308                 $debug && warn "removed : ", $field->as_string;
309             }
310         } elsif ($stringfilter =~ /([0-9]{3})([a-z0-9])(.*)/) {
311             my $removetag = $1;
312             my $removesubfield = $2;
313             my $removematch = $3;
314             if ( ( $removetag > "010" ) && $removesubfield ) {
315                 foreach my $field ( $record->field($removetag) ) {
316                     $field->delete_subfield( code => "$removesubfield", match => $removematch );
317                     $debug && warn "Potentially removed : ", $field->subfield($removesubfield);
318                 }
319             }
320         }
321     }
322     unless ($test_parameter) {
323         if ($authorities){
324             use C4::AuthoritiesMarc;
325             my $authtypecode=GuessAuthTypeCode($record, $heading_fields);
326             my $authid= ($id?$id:GuessAuthId($record));
327             if ($authid && GetAuthority($authid) && $update ){
328             ## Authority has an id and is in database : Replace
329                 eval { ( $authid ) = ModAuthority($authid,$record, $authtypecode) };
330                 if ($@){
331                     warn "Problem with authority $authid Cannot Modify";
332                                         printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ERROR"}) if ($logfile);
333                 }
334                                 else{
335                                         printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ok"}) if ($logfile);
336                                 }
337             }  
338             elsif (defined $authid) {
339             ## An authid is defined but no authority in database : add
340                 eval { ( $authid ) = AddAuthority($record,$authid, $authtypecode) };
341                 if ($@){
342                     warn "Problem with authority $authid Cannot Add ".$@;
343                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
344                 }
345                                 else{
346                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
347                                 }
348             }
349                 else {
350             ## True insert in database
351                 eval { ( $authid ) = AddAuthority($record,"", $authtypecode) };
352                 if ($@){
353                     warn "Problem with authority $authid Cannot Add".$@;
354                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
355                 }
356                                 else{
357                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
358                                 }
359                 }
360             if ($yamlfile) {
361             $yamlhash->{$originalid}->{'authid'} = $authid;
362             my @subfields;
363             foreach my $field ( $record->field("2..") ) {
364                 push @subfields, map { ( $_->[0] =~ /[a-z]/ ? $_->[1] : () ) } $field->subfields();
365             }
366             $yamlhash->{$originalid}->{'subfields'} = \@subfields;
367             }
368         }
369         else {
370             my ( $biblionumber, $biblioitemnumber, $itemnumbers_ref, $errors_ref );
371             $biblionumber = $id;
372             # check for duplicate, based on ISBN (skip it if we already have found a duplicate with match parameter
373             if (!$biblionumber && $isbn_check && $isbn) {
374     #         warn "search ISBN : $isbn";
375                 $sth_isbn->execute($isbn);
376                 ($biblionumber,$biblioitemnumber) = $sth_isbn->fetchrow;
377             }
378                 if (defined $idmapfl) {
379                                 if ($sourcetag < "010"){
380                                         if ($record->field($sourcetag)){
381                                           my $source = $record->field($sourcetag)->data();
382                                           printf(IDMAP "%s|%s\n",$source,$biblionumber);
383                                         }
384                             } else {
385                                         my $source=$record->subfield($sourcetag,$sourcesubfield);
386                                         printf(IDMAP "%s|%s\n",$source,$biblionumber);
387                           }
388                         }
389                                         # create biblio, unless we already have it ( either match or isbn )
390             if ($biblionumber) {
391                 eval{$biblioitemnumber=GetBiblioData($biblionumber)->{biblioitemnumber};};
392                 if ($update) {
393                     eval { ( $biblionumber, $biblioitemnumber ) = ModBiblio( $record, $biblionumber, GetFrameworkcode($biblionumber) ) };
394                     if ($@) {
395                         warn "ERROR: Edit biblio $biblionumber failed: $@\n";
396                         printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "ERROR" } ) if ($logfile);
397                         next RECORD;
398                     } else {
399                         printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "ok" } ) if ($logfile);
400                     }
401                 } else {
402                     printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "warning : already in database" } ) if ($logfile);
403                 }
404             } else {
405                 if ($insert) {
406                     eval { ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, '', { defer_marc_save => 1 } ) };
407                     if ($@) {
408                         warn "ERROR: Adding biblio $biblionumber failed: $@\n";
409                         printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "ERROR" } ) if ($logfile);
410                         next RECORD;
411                     } else {
412                         printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "ok" } ) if ($logfile);
413                     }
414                 } else {
415                     printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "warning : not in database" } ) if ($logfile);
416                 }
417             }
418             eval { ( $itemnumbers_ref, $errors_ref ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
419             my $error_adding = $@;
420             # Work on a clone so that if there are real errors, we can maybe
421             # fix them up later.
422                         my $clone_record = $record->clone();
423             C4::Biblio::_strip_item_fields($clone_record, '');
424             # This sets the marc fields if there was an error, and also calls
425             # defer_marc_save.
426             ModBiblioMarc( $clone_record, $biblionumber, $framework );
427             if ( $error_adding ) {
428                 warn "ERROR: Adding items to bib $biblionumber failed: $error_adding";
429                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
430                 # if we failed because of an exception, assume that 
431                 # the MARC columns in biblioitems were not set.
432                 next RECORD;
433             }
434                         else{
435                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
436                         }
437             if ($dedup_barcode && grep { exists $_->{error_code} && $_->{error_code} eq 'duplicate_barcode' } @$errors_ref) {
438                 # Find the record called 'barcode'
439                 my ($tag, $sub) = C4::Biblio::GetMarcFromKohaField('items.barcode', $framework);
440                 # Now remove any items that didn't have a duplicate_barcode error,
441                 # erase the barcodes on items that did, and re-add those items.
442                 my %dupes;
443                 foreach my $i (0 .. $#{$errors_ref}) {
444                     my $ref = $errors_ref->[$i];
445                     if ($ref && ($ref->{error_code} eq 'duplicate_barcode')) {
446                         $dupes{$ref->{item_sequence}} = 1;
447                         # Delete the error message because we're going to
448                         # retry this one.
449                         delete $errors_ref->[$i];
450                     }
451                 }
452                 my $seq = 0;
453                 foreach my $field ($record->field($tag)) {
454                     $seq++;
455                     if ($dupes{$seq}) {
456                         # Here we remove the barcode
457                         $field->delete_subfield(code => $sub);
458                     } else {
459                         # otherwise we delete the field because we don't want
460                         # two of them
461                         $record->delete_fields($field);
462                     }
463                 }
464                 # Now re-add the record as before, adding errors to the prev list
465                 my $more_errors;
466                 eval { ( $itemnumbers_ref, $more_errors ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
467                 if ( $@ ) {
468                     warn "ERROR: Adding items to bib $biblionumber failed: $@\n";
469                     printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
470                     # if we failed because of an exception, assume that
471                     # the MARC columns in biblioitems were not set.
472                     ModBiblioMarc( $record, $biblionumber, $framework );
473                     next RECORD;
474                 } else {
475                     printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
476                 }
477                 push @$errors_ref, @{ $more_errors };
478             }
479             if ($#{ $errors_ref } > -1) {
480                 report_item_errors($biblionumber, $errors_ref);
481             }
482             $yamlhash->{$originalid} = $biblionumber if ($yamlfile);
483         }
484         $dbh->commit() if (0 == $i % $commitnum);
485     }
486     print $record->as_formatted()."\n" if ($verbose//0)==2;
487     last if $i == $number;
488 }
489 $dbh->commit();
490 $dbh->{AutoCommit} = 1;
491
492
493 if ($fk_off) {
494         $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
495 }
496
497 # restore CataloguingLog
498 $dbh->do("UPDATE systempreferences SET value=$CataloguingLog WHERE variable='CataloguingLog'");
499
500 my $timeneeded = gettimeofday - $starttime;
501 print "\n$i MARC records done in $timeneeded seconds\n";
502 if ($logfile){
503   print $loghandle "file : $input_marc_file\n";
504   print $loghandle "$i MARC records done in $timeneeded seconds\n";
505   $loghandle->close;
506 }
507 if ($yamlfile) {
508     open my $yamlfileout, q{>}, "$yamlfile" or die "cannot open $yamlfile \n";
509     print $yamlfileout Dump($yamlhash);
510 }
511 exit 0;
512
513 sub GetRecordId{
514         my $marcrecord=shift;
515         my $tag=shift;
516         my $subfield=shift;
517         my $id;
518         if ($tag lt "010"){
519                 return $marcrecord->field($tag)->data() if $marcrecord->field($tag);
520         } 
521         elsif ($subfield){
522                 if ($marcrecord->field($tag)){
523                         return $marcrecord->subfield($tag,$subfield);
524                 }
525         }
526         return $id;
527 }
528 sub build_query {
529         my $match = shift;
530         my $record=shift;
531         my @searchstrings;
532         foreach my $matchingpoint (@$match){
533           my $string = build_simplequery($matchingpoint,$record);
534           push @searchstrings,$string if (length($string)>0);
535         }
536     my $QParser;
537     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
538     my $op;
539     if ($QParser) {
540         $op = '&&';
541     } else {
542         $op = 'and';
543     }
544     return join(" $op ",@searchstrings);
545 }
546 sub build_simplequery {
547         my $element=shift;
548         my $record=shift;
549     my @searchstrings;
550     my ($index,$recorddata)=split /,/,$element;
551     if ($recorddata=~/(\d{3})(.*)/) {
552         my ($tag,$subfields) =($1,$2);
553         foreach my $field ($record->field($tag)){
554                   if (length($field->as_string("$subfields"))>0){
555               push @searchstrings,"$index:\"".$field->as_string("$subfields")."\"";
556                   }
557         }
558     }
559     my $QParser;
560     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
561     my $op;
562     if ($QParser) {
563         $op = '&&';
564     } else {
565         $op = 'and';
566     }
567     return join(" $op ",@searchstrings);
568 }
569 sub report_item_errors {
570     my $biblionumber = shift;
571     my $errors_ref = shift;
572
573     foreach my $error (@{ $errors_ref }) {
574         next if !$error;
575         my $msg = "Item not added (bib $biblionumber, item tag #$error->{'item_sequence'}, barcode $error->{'item_barcode'}): ";
576         my $error_code = $error->{'error_code'};
577         $error_code =~ s/_/ /g;
578         $msg .= "$error_code $error->{'error_information'}";
579         print $msg, "\n";
580     }
581 }
582 sub printlog{
583         my $logelements=shift;
584     print $loghandle join( ";", map { defined $_ ? $_ : "" } @$logelements{qw<id op status>} ), "\n";
585 }
586 sub get_heading_fields{
587     my $headingfields;
588     if ($authtypes){
589         $headingfields=YAML::LoadFile($authtypes);
590         $headingfields={C4::Context->preference('marcflavour')=>$headingfields};
591         $debug && warn YAML::Dump($headingfields);
592     }
593     unless ($headingfields){
594         $headingfields=$dbh->selectall_hashref("SELECT auth_tag_to_report, authtypecode from auth_types",'auth_tag_to_report',{Slice=>{}});
595         $headingfields={C4::Context->preference('marcflavour')=>$headingfields};
596     }
597     return $headingfields;
598 }
599
600 =head1 NAME
601
602 bulkmarcimport.pl - Import bibliographic/authority records into Koha
603
604 =head1 USAGE
605
606  $ export KOHA_CONF=/etc/koha.conf
607  $ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 \\
608     -file /home/jmf/koha.mrc -n 3000
609
610 =head1 WARNING
611
612 Don't use this script before you've entered and checked your MARC parameters
613 tables twice (or more!). Otherwise, the import won't work correctly and you
614 will get invalid data.
615
616 =head1 DESCRIPTION
617
618 =over
619
620 =item  B<-h>
621
622 This version/help screen
623
624 =item B<-b, -biblios>
625
626 Type of import: bibliographic records
627
628 =item B<-a, -authorities>
629
630 Type of import: authority records
631
632 =item B<-file>=I<FILE>
633
634 The I<FILE> to import
635
636 =item  B<-v>
637
638 Verbose mode. 1 means "some infos", 2 means "MARC dumping"
639
640 =item B<-fk>
641
642 Turn off foreign key checks during import.
643
644 =item B<-n>=I<NUMBER>
645
646 The I<NUMBER> of records to import. If missing, all the file is imported
647
648 =item B<-o, -offset>=I<NUMBER>
649
650 File offset before importing, ie I<NUMBER> of records to skip.
651
652 =item B<-commit>=I<NUMBER>
653
654 The I<NUMBER> of records to wait before performing a 'commit' operation
655
656 =item B<-l>
657
658 File logs actions done for each record and their status into file
659
660 =item B<-append>
661
662 If specified, data will be appended to the logfile. If not, the logfile will be erased for each execution.
663
664 =item B<-t, -test>
665
666 Test mode: parses the file, saying what he would do, but doing nothing.
667
668 =item B<-s>
669
670 Skip automatic conversion of MARC-8 to UTF-8.  This option is provided for
671 debugging.
672
673 =item B<-c>=I<CHARACTERISTIC>
674
675 The I<CHARACTERISTIC> MARC flavour. At the moment, only I<MARC21> and
676 I<UNIMARC> are supported. MARC21 by default.
677
678 =item B<-d>
679
680 Delete EVERYTHING related to biblio in koha-DB before import. Tables: biblio,
681 biblioitems, items
682
683 =item B<-m>=I<FORMAT>
684
685 Input file I<FORMAT>: I<MARCXML> or I<ISO2709> (defaults to ISO2709)
686
687 =item B<-authtypes>
688
689 file yamlfile with authoritiesTypes and distinguishable record field in order
690 to store the correct authtype
691
692 =item B<-yaml>
693
694 yaml file  format a yaml file with ids
695
696 =item B<-filter>
697
698 list of fields that will not be imported. Can be any from 000 to 999 or field,
699 subfield and subfield's matching value such as 200avalue
700
701 =item B<-insert>
702
703 if set, only insert when possible
704
705 =item B<-update>
706
707 if set, only updates (any biblio should have a matching record)
708
709 =item B<-all>
710
711 if set, do whatever is required
712
713 =item B<-k, -keepids>=<FIELD>
714
715 Field store ids in I<FIELD> (usefull for authorities, where 001 contains the
716 authid for Koha, that can contain a very valuable info for authorities coming
717 from LOC or BNF. useless for biblios probably)
718
719 =item B<-match>=<FIELD>
720
721 I<FIELD> matchindex,fieldtomatch matchpoint to use to deduplicate fieldtomatch
722 can be either 001 to 999 or field and list of subfields as such 100abcde
723
724 =item B<-i,-isbn>
725
726 If set, a search will be done on isbn, and, if the same isbn is found, the
727 biblio is not added. It's another method to deduplicate.  B<-match> & B<-isbn>
728 can be both set.
729
730 =item B<-cleanisbn>
731
732 Clean ISBN fields from entering biblio records, ie removes hyphens. By default,
733 ISBN are cleaned. --nocleanisbn will keep ISBN unchanged.
734
735 =item B<-x>=I<TAG>
736
737 Source bib I<TAG> for reporting the source bib number
738
739 =item B<-y>=I<SUBFIELD>
740
741 Source I<SUBFIELD> for reporting the source bib number
742
743 =item B<-idmap>=I<FILE>
744
745 I<FILE> for the koha bib and source id
746
747 =item B<-keepids>
748
749 Store ids in 009 (usefull for authorities, where 001 contains the authid for
750 Koha, that can contain a very valuable info for authorities coming from LOC or
751 BNF. useless for biblios probably)
752
753 =item B<-dedupbarcode>
754
755 If set, whenever a duplicate barcode is detected, it is removed and the attempt
756 to add the record is retried, thereby giving the record a blank barcode. This
757 is useful when something has set barcodes to be a biblio ID, or similar
758 (usually other software.)
759
760 =item B<-framework>
761
762 This is the code for the framework that the requested records will have attached
763 to them when they are created. If not specified, then the default framework
764 will be used.
765
766 =item B<-custom>=I<MODULE>
767
768 This parameter allows you to use a local module with a customize subroutine
769 that is called for each MARC record.
770 If no filename is passed, LocalChanges.pm is assumed to be in the
771 migration_tools subdirectory. You may pass an absolute file name or a file name
772 from the migration_tools directory.
773
774 =back
775
776 =cut
777