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;
27 use Unicode::Normalize;
28 use Time::HiRes qw(gettimeofday);
33 binmode STDOUT, ':encoding(UTF-8)';
34 my ( $input_marc_file, $number, $offset) = ('',0,0);
35 my ($version, $delete, $test_parameter, $skip_marc8_conversion, $char_encoding, $verbose, $commit, $fk_off,$format,$biblios,$authorities,$keepids,$match, $isbn_check, $logfile);
37 my ($sourcetag,$sourcesubfield,$idmapfl, $dedup_barcode);
42 'commit:f' => \$commit,
43 'file:s' => \$input_marc_file,
45 'o|offset:f' => \$offset,
48 't' => \$test_parameter,
49 's' => \$skip_marc8_conversion,
50 'c:s' => \$char_encoding,
55 'k|keepids:s' => \$keepids,
56 'b|biblios' => \$biblios,
57 'a|authorities' => \$authorities,
58 'match=s@' => \$match,
59 'i|isbn' => \$isbn_check,
61 'y:s' => \$sourcesubfield,
62 'idmap:s' => \$idmapfl,
63 'cleanisbn!' => \$cleanisbn,
64 'dedupbarcode' => \$dedup_barcode,
66 $biblios=!$authorities||$biblios;
68 if ($version || ($input_marc_file eq '')) {
69 pod2usage( -verbose => 2 );
73 if (defined $idmapfl) {
74 open(IDMAP,">$idmapfl") or die "cannot open $idmapfl \n";
77 if ((not defined $sourcesubfield) && (not defined $sourcetag)){
82 my $dbh = C4::Context->dbh;
84 # save the CataloguingLog property : we don't want to log a bulkmarcimport. It will slow the import &
85 # will create problems in the action_logs table, that can't handle more than 1 entry per second per user.
86 my $CataloguingLog = C4::Context->preference('CataloguingLog');
87 $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='CataloguingLog'");
90 $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
96 print "deleting biblios\n";
97 $dbh->do("truncate biblio");
98 $dbh->do("truncate biblioitems");
99 $dbh->do("truncate items");
102 print "deleting authorities\n";
103 $dbh->do("truncate auth_header");
105 $dbh->do("truncate zebraqueue");
110 if ($test_parameter) {
111 print "TESTING MODE ONLY\n DOING NOTHING\n===============\n";
114 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
116 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
117 my $starttime = gettimeofday;
119 my $fh = IO::File->new($input_marc_file); # don't let MARC::Batch open the file, as it applies the ':utf8' IO layer
120 if (defined $format && $format =~ /XML/i) {
121 # ugly hack follows -- MARC::File::XML, when used by MARC::Batch,
122 # appears to try to convert incoming XML records from MARC-8
123 # to UTF-8. Setting the BinaryEncoding key turns that off
124 # TODO: see what happens to ISO-8859-1 XML files.
125 # TODO: determine if MARC::Batch can be fixed to handle
126 # XML records properly -- it probably should be
127 # be using a proper push or pull XML parser to
128 # extract the records, not using regexes to look
129 # for <record>.*</record>.
130 $MARC::File::XML::_load_args{BinaryEncoding} = 'utf-8';
131 my $recordformat= ($marcFlavour eq "MARC21"?"USMARC":uc($marcFlavour));
132 #UNIMARC Authorities have a different way to manage encoding than UNIMARC biblios.
133 $recordformat=$recordformat."AUTH" if ($authorities and $marcFlavour ne "MARC21");
134 $MARC::File::XML::_load_args{RecordFormat} = $recordformat;
135 $batch = MARC::Batch->new( 'XML', $fh );
137 $batch = MARC::Batch->new( 'USMARC', $fh );
139 $batch->warnings_off();
140 $batch->strict_off();
142 my $commitnum = $commit ? $commit : 50;
147 print "Skipping file offset: $offset records\n";
148 $batch->next() while ($offset--);
151 my ($tagid,$subfieldid);
156 ( $tagid, $subfieldid ) =
157 GetMarcFromKohaField( "biblio.biblionumber", '' );
161 # the SQL query to search on isbn
162 my $sth_isbn = $dbh->prepare("SELECT biblionumber,biblioitemnumber FROM biblioitems WHERE isbn=?");
164 $dbh->{AutoCommit} = 0;
167 $loghandle= IO::File->new($logfile,"w") ;
168 print $loghandle "id;operation;status\n";
173 eval { $record = $batch->next() };
175 print "Bad MARC record $i: $@ skipped\n";
176 # FIXME - because MARC::Batch->next() combines grabbing the next
177 # blob and parsing it into one operation, a correctable condition
178 # such as a MARC-8 record claiming that it's UTF-8 can't be recovered
179 # from because we don't have access to the original blob. Note
180 # that the staging import can deal with this condition (via
181 # C4::Charset::MarcToUTF8Record) because it doesn't use MARC::Batch.
184 # skip if we get an empty record (that is MARC valid, but will result in AddBiblio failure
185 last unless ( $record );
188 print "\r$i" unless $i % 100;
190 # transcode the record to UTF8 if needed & applicable.
191 if ($record->encoding() eq 'MARC-8' and not $skip_marc8_conversion) {
192 # FIXME update condition
193 my ($guessed_charset, $charset_errors);
194 ($record, $guessed_charset, $charset_errors) = MarcToUTF8Record($record, $marcFlavour.(($authorities and $marcFlavour ne "MARC21")?'AUTH':''));
195 if ($guessed_charset eq 'failed') {
196 warn "ERROR: failed to perform character conversion for record $i\n";
201 # remove trailing - in isbn (only for biblios, of course)
202 if ($biblios && $cleanisbn) {
203 my $tag = $marcFlavour eq 'UNIMARC' ? '010' : '020';
204 my $field = $record->field($tag);
205 my $isbn = $field && $field->subfield('a');
208 $field->update('a' => $isbn);
212 # search for duplicates (based on Local-number)
215 my $query=build_query($match,$record);
216 my $server=($authorities?'authorityserver':'biblioserver');
217 my ($error, $results,$totalhits)=C4::Search::SimpleSearch( $query, 0, 3, [$server] );
218 die "unable to search the database for duplicates : $error" if (defined $error);
219 #warn "$query $server : $totalhits";
220 if ( @{$results} == 1 ){
221 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
222 $id=GetRecordId($marcrecord,$tagid,$subfieldid);
224 elsif ( @{$results} > 1){
225 $debug && warn "more than one match for $query";
228 $debug && warn "nomatch for $query";
233 $originalid=GetRecordId($record,$tagid,$subfieldid);
236 if (length($keepids)==3){
237 $storeidfield=MARC::Field->new($keepids,$originalid);
240 $storeidfield=MARC::Field->new(substr($keepids,0,3),"","",substr($keepids,3,1),$originalid);
242 $record->insert_fields_ordered($storeidfield);
243 $record->delete_field($record->field($tagid));
246 unless ($test_parameter) {
248 use C4::AuthoritiesMarc;
249 my $authtypecode=GuessAuthTypeCode($record);
250 my $authid= ($id?$id:GuessAuthId($record));
251 if ($authid && GetAuthority($authid)){
252 ## Authority has an id and is in database : Replace
253 eval { ( $authid ) = ModAuthority($authid,$record, $authtypecode) };
255 warn "Problem with authority $authid Cannot Modify";
256 printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ERROR"}) if ($logfile);
259 printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ok"}) if ($logfile);
262 elsif (defined $authid) {
263 ## An authid is defined but no authority in database : add
264 eval { ( $authid ) = AddAuthority($record,$authid, $authtypecode) };
266 warn "Problem with authority $authid Cannot Add ".$@;
267 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
270 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
274 ## True insert in database
275 eval { ( $authid ) = AddAuthority($record,"", $authtypecode) };
277 warn "Problem with authority $authid Cannot Add".$@;
278 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
281 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
286 my ( $biblionumber, $biblioitemnumber, $itemnumbers_ref, $errors_ref );
288 # check for duplicate, based on ISBN (skip it if we already have found a duplicate with match parameter
289 if (!$biblionumber && $isbn_check && $isbn) {
290 # warn "search ISBN : $isbn";
291 $sth_isbn->execute($isbn);
292 ($biblionumber,$biblioitemnumber) = $sth_isbn->fetchrow;
294 if (defined $idmapfl) {
295 if ($sourcetag < "010"){
296 if ($record->field($sourcetag)){
297 my $source = $record->field($sourcetag)->data();
298 printf(IDMAP "%s|%s\n",$source,$biblionumber);
301 my $source=$record->subfield($sourcetag,$sourcesubfield);
302 printf(IDMAP "%s|%s\n",$source,$biblionumber);
305 # create biblio, unless we already have it ( either match or isbn )
307 eval{$biblioitemnumber=GetBiblioData($biblionumber)->{biblioitemnumber};}
311 eval { ( $biblionumber, $biblioitemnumber ) = AddBiblio($record, '', { defer_marc_save => 1 }) };
314 warn "ERROR: Adding biblio $biblionumber failed: $@\n";
315 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ERROR"}) if ($logfile);
319 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
321 eval { ( $itemnumbers_ref, $errors_ref ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
322 my $error_adding = $@;
323 # Work on a clone so that if there are real errors, we can maybe
325 my $clone_record = $record->clone();
326 C4::Biblio::_strip_item_fields($clone_record, '');
327 # This sets the marc fields if there was an error, and also calls
329 ModBiblioMarc( $clone_record, $biblionumber, '' );
330 if ( $error_adding ) {
331 warn "ERROR: Adding items to bib $biblionumber failed: $error_adding";
332 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
333 # if we failed because of an exception, assume that
334 # the MARC columns in biblioitems were not set.
338 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
340 if ($dedup_barcode && grep { exists $_->{error_code} && $_->{error_code} eq 'duplicate_barcode' } @$errors_ref) {
341 # Find the record called 'barcode'
342 my ($tag, $sub) = C4::Biblio::GetMarcFromKohaField('items.barcode', '');
343 # Now remove any items that didn't have a duplicate_barcode error,
344 # erase the barcodes on items that did, and re-add those items.
346 foreach my $i (0 .. $#{$errors_ref}) {
347 my $ref = $errors_ref->[$i];
348 if ($ref && ($ref->{error_code} eq 'duplicate_barcode')) {
349 $dupes{$ref->{item_sequence}} = 1;
350 # Delete the error message because we're going to
352 delete $errors_ref->[$i];
356 foreach my $field ($record->field($tag)) {
359 # Here we remove the barcode
360 $field->delete_subfield(code => $sub);
362 # otherwise we delete the field because we don't want
364 $record->delete_fields($field);
367 # Now re-add the record as before, adding errors to the prev list
369 eval { ( $itemnumbers_ref, $more_errors ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
371 warn "ERROR: Adding items to bib $biblionumber failed: $@\n";
372 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
373 # if we failed because of an exception, assume that
374 # the MARC columns in biblioitems were not set.
375 ModBiblioMarc( $record, $biblionumber, '' );
378 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
380 push @$errors_ref, @{ $more_errors };
382 if ($#{ $errors_ref } > -1) {
383 report_item_errors($biblionumber, $errors_ref);
386 $dbh->commit() if (0 == $i % $commitnum);
388 last if $i == $number;
395 $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
398 # restore CataloguingLog
399 $dbh->do("UPDATE systempreferences SET value=$CataloguingLog WHERE variable='CataloguingLog'");
401 my $timeneeded = gettimeofday - $starttime;
402 print "\n$i MARC records done in $timeneeded seconds\n";
404 print $loghandle "file : $input_marc_file\n";
405 print $loghandle "$i MARC records done in $timeneeded seconds\n";
411 my $marcrecord=shift;
416 return $marcrecord->field($tag)->data() if $marcrecord->field($tag);
419 if ($marcrecord->field($tag)){
420 return $marcrecord->subfield($tag,$subfield);
429 foreach my $matchingpoint (@$match){
430 my $string = build_simplequery($matchingpoint,$record);
431 push @searchstrings,$string if (length($string)>0);
433 return join(" and ",@searchstrings);
435 sub build_simplequery {
438 my ($index,$recorddata)=split /,/,$element;
439 my ($tag,$subfields) =($1,$2) if ($recorddata=~/(\d{3})(.*)/);
441 foreach my $field ($record->field($tag)){
442 if (length($field->as_string("$subfields"))>0){
443 push @searchstrings,"$index,wrdl=\"".$field->as_string("$subfields")."\"";
446 return join(" and ",@searchstrings);
448 sub report_item_errors {
449 my $biblionumber = shift;
450 my $errors_ref = shift;
452 foreach my $error (@{ $errors_ref }) {
454 my $msg = "Item not added (bib $biblionumber, item tag #$error->{'item_sequence'}, barcode $error->{'item_barcode'}): ";
455 my $error_code = $error->{'error_code'};
456 $error_code =~ s/_/ /g;
457 $msg .= "$error_code $error->{'error_information'}";
462 my $logelements=shift;
463 print $loghandle join (";",@$logelements{qw<id op status>}),"\n";
469 bulkmarcimport.pl - Import bibliographic/authority records into Koha
473 $ export KOHA_CONF=/etc/koha.conf
474 $ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 \\
475 -file /home/jmf/koha.mrc -n 3000
479 Don't use this script before you've entered and checked your MARC parameters
480 tables twice (or more!). Otherwise, the import won't work correctly and you
481 will get invalid data.
489 This version/help screen
491 =item B<-b, -biblios>
493 Type of import: bibliographic records
495 =item B<-a, -authorities>
497 Type of import: authority records
499 =item B<-file>=I<FILE>
501 The I<FILE> to import
505 Verbose mode. 1 means "some infos", 2 means "MARC dumping"
509 Turn off foreign key checks during import.
511 =item B<-n>=I<NUMBER>
513 The I<NUMBER> of records to import. If missing, all the file is imported
515 =item B<-o, -offset>=I<NUMBER>
517 File offset before importing, ie I<NUMBER> of records to skip.
519 =item B<-commit>=I<NUMBER>
521 The I<NUMBER> of records to wait before performing a 'commit' operation
525 File logs actions done for each record and their status into file
529 Test mode: parses the file, saying what he would do, but doing nothing.
533 Skip automatic conversion of MARC-8 to UTF-8. This option is provided for
536 =item B<-c>=I<CHARACTERISTIC>
538 The I<CHARACTERISTIC> MARC flavour. At the moment, only I<MARC21> and
539 I<UNIMARC> are supported. MARC21 by default.
543 Delete EVERYTHING related to biblio in koha-DB before import. Tables: biblio,
546 =item B<-m>=I<FORMAT>
548 Input file I<FORMAT>: I<MARCXML> or I<ISO2709> (defaults to ISO2709)
550 =item B<-k, -keepids>=<FIELD>
552 Field store ids in I<FIELD> (usefull for authorities, where 001 contains the
553 authid for Koha, that can contain a very valuable info for authorities coming
554 from LOC or BNF. useless for biblios probably)
556 =item B<-match>=<FIELD>
558 I<FIELD> matchindex,fieldtomatch matchpoint to use to deduplicate fieldtomatch
559 can be either 001 to 999 or field and list of subfields as such 100abcde
563 If set, a search will be done on isbn, and, if the same isbn is found, the
564 biblio is not added. It's another method to deduplicate. B<-match> & B<-isbn>
569 Clean ISBN fields from entering biblio records, ie removes hyphens. By default,
570 ISBN are cleaned. --nocleanisbn will keep ISBN unchanged.
574 Source bib I<TAG> for reporting the source bib number
576 =item B<-y>=I<SUBFIELD>
578 Source I<SUBFIELD> for reporting the source bib number
580 =item B<-idmap>=I<FILE>
582 I<FILE> for the koha bib and source id
586 Store ids in 009 (usefull for authorities, where 001 contains the authid for
587 Koha, that can contain a very valuable info for authorities coming from LOC or
588 BNF. useless for biblios probably)
590 =item B<-dedupbarcode>
592 If set, whenever a duplicate barcode is detected, it is removed and the attempt
593 to add the record is retried, thereby giving the record a blank barcode. This
594 is useful when something has set barcodes to be a biblio ID, or similar
595 (usually other software.)