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