2 # Import an iso2709 file into Koha 3
8 # find Koha's Perl modules
9 # test carefully before changing this
11 eval { require "$FindBin::Bin/../kohalib.pl" };
15 use MARC::File::USMARC;
28 use Unicode::Normalize;
29 use Time::HiRes qw(gettimeofday);
34 my $localcust= $FindBin::Bin.'/LocalChanges.pm';
35 $localcust= -e $localcust? $localcust: undef;
36 require $localcust if $localcust;
37 $localcust=\&customize if $localcust;
39 use open qw( :std :encoding(UTF-8) );
40 binmode( STDOUT, ":encoding(UTF-8)" );
41 my ( $input_marc_file, $number, $offset) = ('',0,0);
42 my ($version, $delete, $test_parameter, $skip_marc8_conversion, $char_encoding, $verbose, $commit, $fk_off,$format,$biblios,$authorities,$keepids,$match, $isbn_check, $logfile);
43 my ( $insert, $filters, $update, $all, $yamlfile, $authtypes, $append );
45 my ($sourcetag,$sourcesubfield,$idmapfl, $dedup_barcode);
51 'commit:f' => \$commit,
52 'file:s' => \$input_marc_file,
54 'o|offset:f' => \$offset,
57 't|test' => \$test_parameter,
58 's' => \$skip_marc8_conversion,
59 'c:s' => \$char_encoding,
65 'k|keepids:s' => \$keepids,
66 'b|biblios' => \$biblios,
67 'a|authorities' => \$authorities,
68 'authtypes:s' => \$authtypes,
69 'filter=s@' => \$filters,
73 'match=s@' => \$match,
74 'i|isbn' => \$isbn_check,
76 'y:s' => \$sourcesubfield,
77 'idmap:s' => \$idmapfl,
78 'cleanisbn!' => \$cleanisbn,
79 'yaml:s' => \$yamlfile,
80 'dedupbarcode' => \$dedup_barcode,
81 'framework=s' => \$framework,
83 $biblios ||= !$authorities;
85 my $writemode = ($append) ? "a" : "w";
92 if ($version || ($input_marc_file eq '')) {
93 pod2usage( -verbose => 2 );
97 my $dbh = C4::Context->dbh;
98 my $heading_fields=get_heading_fields();
100 if (defined $idmapfl) {
101 open(IDMAP,">$idmapfl") or die "cannot open $idmapfl \n";
104 if ((not defined $sourcesubfield) && (not defined $sourcetag)){
109 # save the CataloguingLog property : we don't want to log a bulkmarcimport. It will slow the import &
110 # will create problems in the action_logs table, that can't handle more than 1 entry per second per user.
111 my $CataloguingLog = C4::Context->preference('CataloguingLog');
112 $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='CataloguingLog'");
115 $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
121 print "deleting biblios\n";
122 $dbh->do("truncate biblio");
123 $dbh->do("truncate biblioitems");
124 $dbh->do("truncate items");
127 print "deleting authorities\n";
128 $dbh->do("truncate auth_header");
130 $dbh->do("truncate zebraqueue");
135 if ($test_parameter) {
136 print "TESTING MODE ONLY\n DOING NOTHING\n===============\n";
139 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
141 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
142 my $starttime = gettimeofday;
144 my $fh = IO::File->new($input_marc_file); # don't let MARC::Batch open the file, as it applies the ':utf8' IO layer
145 if (defined $format && $format =~ /XML/i) {
146 # ugly hack follows -- MARC::File::XML, when used by MARC::Batch,
147 # appears to try to convert incoming XML records from MARC-8
148 # to UTF-8. Setting the BinaryEncoding key turns that off
149 # TODO: see what happens to ISO-8859-1 XML files.
150 # TODO: determine if MARC::Batch can be fixed to handle
151 # XML records properly -- it probably should be
152 # be using a proper push or pull XML parser to
153 # extract the records, not using regexes to look
154 # for <record>.*</record>.
155 $MARC::File::XML::_load_args{BinaryEncoding} = 'utf-8';
156 my $recordformat= ($marcFlavour eq "MARC21"?"USMARC":uc($marcFlavour));
157 #UNIMARC Authorities have a different way to manage encoding than UNIMARC biblios.
158 $recordformat=$recordformat."AUTH" if ($authorities and $marcFlavour ne "MARC21");
159 $MARC::File::XML::_load_args{RecordFormat} = $recordformat;
160 $batch = MARC::Batch->new( 'XML', $fh );
162 $batch = MARC::Batch->new( 'USMARC', $fh );
164 $batch->warnings_off();
165 $batch->strict_off();
167 my $commitnum = $commit ? $commit : 50;
172 print "Skipping file offset: $offset records\n";
173 $batch->next() while ($offset--);
176 my ($tagid,$subfieldid);
181 ( $tagid, $subfieldid ) =
182 GetMarcFromKohaField( "biblio.biblionumber", $framework );
186 # the SQL query to search on isbn
187 my $sth_isbn = $dbh->prepare("SELECT biblionumber,biblioitemnumber FROM biblioitems WHERE isbn=?");
189 $dbh->{AutoCommit} = 0;
192 $loghandle= IO::File->new($logfile, $writemode) ;
193 print $loghandle "id;operation;status\n";
198 eval { $record = $batch->next() };
200 print "Bad MARC record $i: $@ skipped\n";
201 # FIXME - because MARC::Batch->next() combines grabbing the next
202 # blob and parsing it into one operation, a correctable condition
203 # such as a MARC-8 record claiming that it's UTF-8 can't be recovered
204 # from because we don't have access to the original blob. Note
205 # that the staging import can deal with this condition (via
206 # C4::Charset::MarcToUTF8Record) because it doesn't use MARC::Batch.
209 # skip if we get an empty record (that is MARC valid, but will result in AddBiblio failure
210 last unless ( $record );
212 if( ($verbose//1)==1 ) { #no dot for verbose==2
213 print "." . ( $i % 100==0 ? "\n$i" : '' );
216 # transcode the record to UTF8 if needed & applicable.
217 if ($record->encoding() eq 'MARC-8' and not $skip_marc8_conversion) {
218 # FIXME update condition
219 my ($guessed_charset, $charset_errors);
220 ($record, $guessed_charset, $charset_errors) = MarcToUTF8Record($record, $marcFlavour.(($authorities and $marcFlavour ne "MARC21")?'AUTH':''));
221 if ($guessed_charset eq 'failed') {
222 warn "ERROR: failed to perform character conversion for record $i\n";
226 SetUTF8Flag($record);
227 &$localcust($record) if $localcust;
229 # remove trailing - in isbn (only for biblios, of course)
230 if ($biblios && $cleanisbn) {
231 my $tag = $marcFlavour eq 'UNIMARC' ? '010' : '020';
232 my $field = $record->field($tag);
233 my $isbn = $field && $field->subfield('a');
236 $field->update('a' => $isbn);
240 # search for duplicates (based on Local-number)
242 $originalid = GetRecordId( $record, $tagid, $subfieldid );
245 my $query = build_query( $match, $record );
246 my $server = ( $authorities ? 'authorityserver' : 'biblioserver' );
247 $debug && warn $query;
248 my ( $error, $results, $totalhits ) = C4::Search::SimpleSearch( $query, 0, 3, [$server] );
249 die "unable to search the database for duplicates : $error" if ( defined $error );
250 $debug && warn "$query $server : $totalhits";
251 if ( $results && scalar(@$results) == 1 ) {
252 my $marcrecord = C4::Search::new_record_from_zebra( $server, $results->[0] );
253 SetUTF8Flag($marcrecord);
254 $id = GetRecordId( $marcrecord, $tagid, $subfieldid );
255 if ( $authorities && $marcFlavour ) {
256 #Skip if authority in database is the same as the on in database
257 if ( $marcrecord->field('005') && $record->field('005') &&
258 $marcrecord->field('005')->data && $record->field('005')->data &&
259 $marcrecord->field('005')->data >= $record->field('005')->data ) {
261 $yamlhash->{$originalid}->{'authid'} = $id;
263 # we recover all subfields of the heading authorities
265 foreach my $field ( $marcrecord->field("2..") ) {
266 push @subfields, map { ( $_->[0] =~ /[a-z]/ ? $_->[1] : () ) } $field->subfields();
268 $yamlhash->{$originalid}->{'subfields'} = \@subfields;
273 } elsif ( $results && scalar(@$results) > 1 ) {
274 $debug && warn "more than one match for $query";
276 $debug && warn "nomatch for $query";
279 if ($keepids && $originalid) {
281 if ( length($keepids) == 3 ) {
282 $storeidfield = MARC::Field->new( $keepids, $originalid );
284 $storeidfield = MARC::Field->new( substr( $keepids, 0, 3 ), "", "", substr( $keepids, 3, 1 ), $originalid );
286 $record->insert_fields_ordered($storeidfield);
287 $record->delete_field( $record->field($tagid) );
289 foreach my $stringfilter (@$filters) {
290 if ( length($stringfilter) == 3 ) {
291 foreach my $field ( $record->field($stringfilter) ) {
292 $record->delete_field($field);
293 $debug && warn "removed : ", $field->as_string;
295 } elsif ($stringfilter =~ /([0-9]{3})([a-z0-9])(.*)/) {
297 my $removesubfield = $2;
298 my $removematch = $3;
299 if ( ( $removetag > "010" ) && $removesubfield ) {
300 foreach my $field ( $record->field($removetag) ) {
301 $field->delete_subfield( code => "$removesubfield", match => $removematch );
302 $debug && warn "Potentially removed : ", $field->subfield($removesubfield);
307 unless ($test_parameter) {
309 use C4::AuthoritiesMarc;
310 my $authtypecode=GuessAuthTypeCode($record, $heading_fields);
311 my $authid= ($id?$id:GuessAuthId($record));
312 if ($authid && GetAuthority($authid) && $update ){
313 ## Authority has an id and is in database : Replace
314 eval { ( $authid ) = ModAuthority($authid,$record, $authtypecode) };
316 warn "Problem with authority $authid Cannot Modify";
317 printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ERROR"}) if ($logfile);
320 printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ok"}) if ($logfile);
323 elsif (defined $authid) {
324 ## An authid is defined but no authority in database : add
325 eval { ( $authid ) = AddAuthority($record,$authid, $authtypecode) };
327 warn "Problem with authority $authid Cannot Add ".$@;
328 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
331 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
335 ## True insert in database
336 eval { ( $authid ) = AddAuthority($record,"", $authtypecode) };
338 warn "Problem with authority $authid Cannot Add".$@;
339 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
342 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
346 $yamlhash->{$originalid}->{'authid'} = $authid;
348 foreach my $field ( $record->field("2..") ) {
349 push @subfields, map { ( $_->[0] =~ /[a-z]/ ? $_->[1] : () ) } $field->subfields();
351 $yamlhash->{$originalid}->{'subfields'} = \@subfields;
355 my ( $biblionumber, $biblioitemnumber, $itemnumbers_ref, $errors_ref );
357 # check for duplicate, based on ISBN (skip it if we already have found a duplicate with match parameter
358 if (!$biblionumber && $isbn_check && $isbn) {
359 # warn "search ISBN : $isbn";
360 $sth_isbn->execute($isbn);
361 ($biblionumber,$biblioitemnumber) = $sth_isbn->fetchrow;
363 if (defined $idmapfl) {
364 if ($sourcetag < "010"){
365 if ($record->field($sourcetag)){
366 my $source = $record->field($sourcetag)->data();
367 printf(IDMAP "%s|%s\n",$source,$biblionumber);
370 my $source=$record->subfield($sourcetag,$sourcesubfield);
371 printf(IDMAP "%s|%s\n",$source,$biblionumber);
374 # create biblio, unless we already have it ( either match or isbn )
376 eval{$biblioitemnumber=GetBiblioData($biblionumber)->{biblioitemnumber};};
378 eval { ( $biblionumber, $biblioitemnumber ) = ModBiblio( $record, $biblionumber, GetFrameworkcode($biblionumber) ) };
380 warn "ERROR: Edit biblio $biblionumber failed: $@\n";
381 printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "ERROR" } ) if ($logfile);
384 printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "ok" } ) if ($logfile);
387 printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "warning : already in database" } ) if ($logfile);
391 eval { ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, '', { defer_marc_save => 1 } ) };
393 warn "ERROR: Adding biblio $biblionumber failed: $@\n";
394 printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "ERROR" } ) if ($logfile);
397 printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "ok" } ) if ($logfile);
400 printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "warning : not in database" } ) if ($logfile);
403 eval { ( $itemnumbers_ref, $errors_ref ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
404 my $error_adding = $@;
405 # Work on a clone so that if there are real errors, we can maybe
407 my $clone_record = $record->clone();
408 C4::Biblio::_strip_item_fields($clone_record, '');
409 # This sets the marc fields if there was an error, and also calls
411 ModBiblioMarc( $clone_record, $biblionumber, $framework );
412 if ( $error_adding ) {
413 warn "ERROR: Adding items to bib $biblionumber failed: $error_adding";
414 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
415 # if we failed because of an exception, assume that
416 # the MARC columns in biblioitems were not set.
420 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
422 if ($dedup_barcode && grep { exists $_->{error_code} && $_->{error_code} eq 'duplicate_barcode' } @$errors_ref) {
423 # Find the record called 'barcode'
424 my ($tag, $sub) = C4::Biblio::GetMarcFromKohaField('items.barcode', $framework);
425 # Now remove any items that didn't have a duplicate_barcode error,
426 # erase the barcodes on items that did, and re-add those items.
428 foreach my $i (0 .. $#{$errors_ref}) {
429 my $ref = $errors_ref->[$i];
430 if ($ref && ($ref->{error_code} eq 'duplicate_barcode')) {
431 $dupes{$ref->{item_sequence}} = 1;
432 # Delete the error message because we're going to
434 delete $errors_ref->[$i];
438 foreach my $field ($record->field($tag)) {
441 # Here we remove the barcode
442 $field->delete_subfield(code => $sub);
444 # otherwise we delete the field because we don't want
446 $record->delete_fields($field);
449 # Now re-add the record as before, adding errors to the prev list
451 eval { ( $itemnumbers_ref, $more_errors ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
453 warn "ERROR: Adding items to bib $biblionumber failed: $@\n";
454 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
455 # if we failed because of an exception, assume that
456 # the MARC columns in biblioitems were not set.
457 ModBiblioMarc( $record, $biblionumber, $framework );
460 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
462 push @$errors_ref, @{ $more_errors };
464 if ($#{ $errors_ref } > -1) {
465 report_item_errors($biblionumber, $errors_ref);
467 $yamlhash->{$originalid} = $biblionumber if ($yamlfile);
469 $dbh->commit() if (0 == $i % $commitnum);
471 print $record->as_formatted()."\n" if ($verbose//0)==2;
472 last if $i == $number;
475 $dbh->{AutoCommit} = 1;
479 $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
482 # restore CataloguingLog
483 $dbh->do("UPDATE systempreferences SET value=$CataloguingLog WHERE variable='CataloguingLog'");
485 my $timeneeded = gettimeofday - $starttime;
486 print "\n$i MARC records done in $timeneeded seconds\n";
488 print $loghandle "file : $input_marc_file\n";
489 print $loghandle "$i MARC records done in $timeneeded seconds\n";
493 open my $yamlfileout, q{>}, "$yamlfile" or die "cannot open $yamlfile \n";
494 print $yamlfileout Dump($yamlhash);
499 my $marcrecord=shift;
504 return $marcrecord->field($tag)->data() if $marcrecord->field($tag);
507 if ($marcrecord->field($tag)){
508 return $marcrecord->subfield($tag,$subfield);
517 foreach my $matchingpoint (@$match){
518 my $string = build_simplequery($matchingpoint,$record);
519 push @searchstrings,$string if (length($string)>0);
522 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
529 return join(" $op ",@searchstrings);
531 sub build_simplequery {
535 my ($index,$recorddata)=split /,/,$element;
536 if ($recorddata=~/(\d{3})(.*)/) {
537 my ($tag,$subfields) =($1,$2);
538 foreach my $field ($record->field($tag)){
539 if (length($field->as_string("$subfields"))>0){
540 push @searchstrings,"$index:\"".$field->as_string("$subfields")."\"";
545 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
552 return join(" $op ",@searchstrings);
554 sub report_item_errors {
555 my $biblionumber = shift;
556 my $errors_ref = shift;
558 foreach my $error (@{ $errors_ref }) {
560 my $msg = "Item not added (bib $biblionumber, item tag #$error->{'item_sequence'}, barcode $error->{'item_barcode'}): ";
561 my $error_code = $error->{'error_code'};
562 $error_code =~ s/_/ /g;
563 $msg .= "$error_code $error->{'error_information'}";
568 my $logelements=shift;
569 print $loghandle join( ";", map { defined $_ ? $_ : "" } @$logelements{qw<id op status>} ), "\n";
571 sub get_heading_fields{
574 $headingfields=YAML::LoadFile($authtypes);
575 $headingfields={C4::Context->preference('marcflavour')=>$headingfields};
576 $debug && warn YAML::Dump($headingfields);
578 unless ($headingfields){
579 $headingfields=$dbh->selectall_hashref("SELECT auth_tag_to_report, authtypecode from auth_types",'auth_tag_to_report',{Slice=>{}});
580 $headingfields={C4::Context->preference('marcflavour')=>$headingfields};
582 return $headingfields;
587 bulkmarcimport.pl - Import bibliographic/authority records into Koha
591 $ export KOHA_CONF=/etc/koha.conf
592 $ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 \\
593 -file /home/jmf/koha.mrc -n 3000
597 Don't use this script before you've entered and checked your MARC parameters
598 tables twice (or more!). Otherwise, the import won't work correctly and you
599 will get invalid data.
607 This version/help screen
609 =item B<-b, -biblios>
611 Type of import: bibliographic records
613 =item B<-a, -authorities>
615 Type of import: authority records
617 =item B<-file>=I<FILE>
619 The I<FILE> to import
623 Verbose mode. 1 means "some infos", 2 means "MARC dumping"
627 Turn off foreign key checks during import.
629 =item B<-n>=I<NUMBER>
631 The I<NUMBER> of records to import. If missing, all the file is imported
633 =item B<-o, -offset>=I<NUMBER>
635 File offset before importing, ie I<NUMBER> of records to skip.
637 =item B<-commit>=I<NUMBER>
639 The I<NUMBER> of records to wait before performing a 'commit' operation
643 File logs actions done for each record and their status into file
647 If specified, data will be appended to the logfile. If not, the logfile will be erased for each execution.
651 Test mode: parses the file, saying what he would do, but doing nothing.
655 Skip automatic conversion of MARC-8 to UTF-8. This option is provided for
658 =item B<-c>=I<CHARACTERISTIC>
660 The I<CHARACTERISTIC> MARC flavour. At the moment, only I<MARC21> and
661 I<UNIMARC> are supported. MARC21 by default.
665 Delete EVERYTHING related to biblio in koha-DB before import. Tables: biblio,
668 =item B<-m>=I<FORMAT>
670 Input file I<FORMAT>: I<MARCXML> or I<ISO2709> (defaults to ISO2709)
674 file yamlfile with authoritiesTypes and distinguishable record field in order
675 to store the correct authtype
679 yaml file format a yaml file with ids
683 list of fields that will not be imported. Can be any from 000 to 999 or field,
684 subfield and subfield's matching value such as 200avalue
688 if set, only insert when possible
692 if set, only updates (any biblio should have a matching record)
696 if set, do whatever is required
698 =item B<-k, -keepids>=<FIELD>
700 Field store ids in I<FIELD> (usefull for authorities, where 001 contains the
701 authid for Koha, that can contain a very valuable info for authorities coming
702 from LOC or BNF. useless for biblios probably)
704 =item B<-match>=<FIELD>
706 I<FIELD> matchindex,fieldtomatch matchpoint to use to deduplicate fieldtomatch
707 can be either 001 to 999 or field and list of subfields as such 100abcde
711 If set, a search will be done on isbn, and, if the same isbn is found, the
712 biblio is not added. It's another method to deduplicate. B<-match> & B<-isbn>
717 Clean ISBN fields from entering biblio records, ie removes hyphens. By default,
718 ISBN are cleaned. --nocleanisbn will keep ISBN unchanged.
722 Source bib I<TAG> for reporting the source bib number
724 =item B<-y>=I<SUBFIELD>
726 Source I<SUBFIELD> for reporting the source bib number
728 =item B<-idmap>=I<FILE>
730 I<FILE> for the koha bib and source id
734 Store ids in 009 (usefull for authorities, where 001 contains the authid for
735 Koha, that can contain a very valuable info for authorities coming from LOC or
736 BNF. useless for biblios probably)
738 =item B<-dedupbarcode>
740 If set, whenever a duplicate barcode is detected, it is removed and the attempt
741 to add the record is retried, thereby giving the record a blank barcode. This
742 is useful when something has set barcodes to be a biblio ID, or similar
743 (usually other software.)
747 This is the code for the framework that the requested records will have attached
748 to them when they are created. If not specified, then the default framework