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