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