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