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, ":utf8");
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);
36 my ($sourcetag,$sourcesubfield,$idmapfl);
41 'commit:f' => \$commit,
42 'file:s' => \$input_marc_file,
44 'o|offset:f' => \$offset,
47 't' => \$test_parameter,
48 's' => \$skip_marc8_conversion,
49 'c:s' => \$char_encoding,
54 'k|keepids:s' => \$keepids,
55 'b|biblios' => \$biblios,
56 'a|authorities' => \$authorities,
57 'match=s@' => \$match,
58 'i|isbn' => \$isbn_check,
60 'y:s' => \$sourcesubfield,
61 'idmap:s' => \$idmapfl,
63 $biblios=!$authorities||$biblios;
65 if ($version || ($input_marc_file eq '')) {
66 pod2usage( -verbose => 2 );
70 if (defined $idmapfl) {
71 open(IDMAP,">$idmapfl") or die "cannot open $idmapfl \n";
74 if ((not defined $sourcesubfield) && (not defined $sourcetag)){
79 my $dbh = C4::Context->dbh;
81 # save the CataloguingLog property : we don't want to log a bulkmarcimport. It will slow the import &
82 # will create problems in the action_logs table, that can't handle more than 1 entry per second per user.
83 my $CataloguingLog = C4::Context->preference('CataloguingLog');
84 $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='CataloguingLog'");
87 $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
93 print "deleting biblios\n";
94 $dbh->do("truncate biblio");
95 $dbh->do("truncate biblioitems");
96 $dbh->do("truncate items");
99 print "deleting authorities\n";
100 $dbh->do("truncate auth_header");
102 $dbh->do("truncate zebraqueue");
107 if ($test_parameter) {
108 print "TESTING MODE ONLY\n DOING NOTHING\n===============\n";
111 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
113 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
114 my $starttime = gettimeofday;
116 my $fh = IO::File->new($input_marc_file); # don't let MARC::Batch open the file, as it applies the ':utf8' IO layer
117 if (defined $format && $format =~ /XML/i) {
118 # ugly hack follows -- MARC::File::XML, when used by MARC::Batch,
119 # appears to try to convert incoming XML records from MARC-8
120 # to UTF-8. Setting the BinaryEncoding key turns that off
121 # TODO: see what happens to ISO-8859-1 XML files.
122 # TODO: determine if MARC::Batch can be fixed to handle
123 # XML records properly -- it probably should be
124 # be using a proper push or pull XML parser to
125 # extract the records, not using regexes to look
126 # for <record>.*</record>.
127 $MARC::File::XML::_load_args{BinaryEncoding} = 'utf-8';
128 my $recordformat= ($marcFlavour eq "MARC21"?"USMARC":uc($marcFlavour));
129 #UNIMARC Authorities have a different way to manage encoding than UNIMARC biblios.
130 $recordformat=$recordformat."AUTH" if ($authorities and $marcFlavour ne "MARC21");
131 $MARC::File::XML::_load_args{RecordFormat} = $recordformat;
132 $batch = MARC::Batch->new( 'XML', $fh );
134 $batch = MARC::Batch->new( 'USMARC', $fh );
136 $batch->warnings_off();
137 $batch->strict_off();
139 my $commitnum = $commit ? $commit : 50;
144 print "Skipping file offset: $offset records\n";
145 $batch->next() while ($offset--);
148 my ($tagid,$subfieldid);
153 ( $tagid, $subfieldid ) =
154 GetMarcFromKohaField( "biblio.biblionumber", '' );
158 # the SQL query to search on isbn
159 my $sth_isbn = $dbh->prepare("SELECT biblionumber,biblioitemnumber FROM biblioitems WHERE isbn=?");
161 $dbh->{AutoCommit} = 0;
164 $loghandle= IO::File->new($logfile,"w") ;
165 print $loghandle "id;operation;status\n";
170 eval { $record = $batch->next() };
172 print "Bad MARC record $i: $@ skipped\n";
173 # FIXME - because MARC::Batch->next() combines grabbing the next
174 # blob and parsing it into one operation, a correctable condition
175 # such as a MARC-8 record claiming that it's UTF-8 can't be recovered
176 # from because we don't have access to the original blob. Note
177 # that the staging import can deal with this condition (via
178 # C4::Charset::MarcToUTF8Record) because it doesn't use MARC::Batch.
182 # skip if we get an empty record (that is MARC valid, but will result in AddBiblio failure
183 last unless ( $record );
186 print "\r$i" unless $i % 100;
188 # transcode the record to UTF8 if needed & applicable.
189 if ($record->encoding() eq 'MARC-8' and not $skip_marc8_conversion) {
190 # FIXME update condition
191 my ($guessed_charset, $charset_errors);
192 ($record, $guessed_charset, $charset_errors) = MarcToUTF8Record($record, $marcFlavour.(($authorities and $marcFlavour ne "MARC21")?'AUTH':''));
193 if ($guessed_charset eq 'failed') {
194 warn "ERROR: failed to perform character conversion for record $i\n";
199 # remove trailing - in isbn (only for biblios, of course)
201 if ($marcFlavour eq 'UNIMARC') {
202 if (my $f010 = $record->field('010')) {
203 $isbn = $f010->subfield('a');
205 $f010->update('a' => $isbn);
208 if (my $f020 = $record->field('020')) {
209 $isbn = $f020->subfield('a');
211 $f020->update('a' => $isbn);
216 # search for duplicates (based on Local-number)
219 my $query=build_query($match,$record);
220 my $server=($authorities?'authorityserver':'biblioserver');
221 my ($error, $results,$totalhits)=C4::Search::SimpleSearch( $query, 0, 3, [$server] );
222 die "unable to search the database for duplicates : $error" if (defined $error);
223 #warn "$query $server : $totalhits";
224 if ($results && scalar(@$results)==1){
225 my $marcrecord = MARC::File::USMARC::decode($results->[0]);
226 $id=GetRecordId($marcrecord,$tagid,$subfieldid);
228 elsif ($results && scalar(@$results)>1){
229 $debug && warn "more than one match for $query";
232 $debug && warn "nomatch for $query";
237 $originalid=GetRecordId($record,$tagid,$subfieldid);
240 if (length($keepids)==3){
241 $storeidfield=MARC::Field->new($keepids,$originalid);
244 $storeidfield=MARC::Field->new(substr($keepids,0,3),"","",substr($keepids,3,1),$originalid);
246 $record->insert_fields_ordered($storeidfield);
247 $record->delete_field($record->field($tagid));
250 unless ($test_parameter) {
252 use C4::AuthoritiesMarc;
253 my $authtypecode=GuessAuthTypeCode($record);
254 my $authid= ($id?$id:GuessAuthId($record));
255 if ($authid && GetAuthority($authid)){
256 ## Authority has an id and is in database : Replace
257 eval { ( $authid ) = ModAuthority($authid,$record, $authtypecode) };
259 warn "Problem with authority $authid Cannot Modify";
260 printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ERROR"}) if ($logfile);
263 printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ok"}) if ($logfile);
266 elsif (defined $authid) {
267 ## An authid is defined but no authority in database : add
268 eval { ( $authid ) = AddAuthority($record,$authid, $authtypecode) };
270 warn "Problem with authority $authid Cannot Add ".$@;
271 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
274 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
278 ## True insert in database
279 eval { ( $authid ) = AddAuthority($record,"", $authtypecode) };
281 warn "Problem with authority $authid Cannot Add".$@;
282 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
285 printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
290 my ( $biblionumber, $biblioitemnumber, $itemnumbers_ref, $errors_ref );
292 # check for duplicate, based on ISBN (skip it if we already have found a duplicate with match parameter
293 if (!$biblionumber && $isbn_check && $isbn) {
294 # warn "search ISBN : $isbn";
295 $sth_isbn->execute($isbn);
296 ($biblionumber,$biblioitemnumber) = $sth_isbn->fetchrow;
298 if (defined $idmapfl) {
299 if ($sourcetag < "010"){
300 if ($record->field($sourcetag)){
301 my $source = $record->field($sourcetag)->data();
302 printf(IDMAP "%s|%s\n",$source,$biblionumber);
305 my $source=$record->subfield($sourcetag,$sourcesubfield);
306 printf(IDMAP "%s|%s\n",$source,$biblionumber);
309 # create biblio, unless we already have it ( either match or isbn )
311 eval{$biblioitemnumber=GetBiblioData($biblionumber)->{biblioitemnumber};}
315 eval { ( $biblionumber, $biblioitemnumber ) = AddBiblio($record, '', { defer_marc_save => 1 }) };
318 warn "ERROR: Adding biblio $biblionumber failed: $@\n";
319 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ERROR"}) if ($logfile);
323 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
325 eval { ( $itemnumbers_ref, $errors_ref ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
327 warn "ERROR: Adding items to bib $biblionumber failed: $@\n";
328 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
329 # if we failed because of an exception, assume that
330 # the MARC columns in biblioitems were not set.
331 ModBiblioMarc( $record, $biblionumber, '' );
335 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
337 if ($#{ $errors_ref } > -1) {
338 report_item_errors($biblionumber, $errors_ref);
341 $dbh->commit() if (0 == $i % $commitnum);
343 last if $i == $number;
350 $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
353 # restore CataloguingLog
354 $dbh->do("UPDATE systempreferences SET value=$CataloguingLog WHERE variable='CataloguingLog'");
356 my $timeneeded = gettimeofday - $starttime;
357 print "\n$i MARC records done in $timeneeded seconds\n";
359 print $loghandle "file : $input_marc_file\n";
360 print $loghandle "$i MARC records done in $timeneeded seconds\n";
366 my $marcrecord=shift;
371 return $marcrecord->field($tag)->data() if $marcrecord->field($tag);
374 if ($marcrecord->field($tag)){
375 return $marcrecord->subfield($tag,$subfield);
384 foreach my $matchingpoint (@$match){
385 my $string = build_simplequery($matchingpoint,$record);
386 push @searchstrings,$string if (length($string)>0);
388 return join(" and ",@searchstrings);
390 sub build_simplequery {
393 my ($index,$recorddata)=split /,/,$element;
394 my ($tag,$subfields) =($1,$2) if ($recorddata=~/(\d{3})(.*)/);
396 foreach my $field ($record->field($tag)){
397 if (length($field->as_string("$subfields"))>0){
398 push @searchstrings,"$index,wrdl=\"".$field->as_string("$subfields")."\"";
401 return join(" and ",@searchstrings);
403 sub report_item_errors {
404 my $biblionumber = shift;
405 my $errors_ref = shift;
407 foreach my $error (@{ $errors_ref }) {
408 my $msg = "Item not added (bib $biblionumber, item tag #$error->{'item_sequence'}, barcode $error->{'item_barcode'}): ";
409 my $error_code = $error->{'error_code'};
410 $error_code =~ s/_/ /g;
411 $msg .= "$error_code $error->{'error_information'}";
416 my $logelements=shift;
417 print $loghandle join (";",@$logelements{qw<id op status>}),"\n";
423 bulkmarcimport.pl - Import bibliographic/authority records into Koha
427 $ export KOHA_CONF=/etc/koha.conf
428 $ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 \\
429 -file /home/jmf/koha.mrc -n 3000
433 Don't use this script before you've entered and checked your MARC parameters
434 tables twice (or more!). Otherwise, the import won't work correctly and you
435 will get invalid data.
443 This version/help screen
445 =item B<-b, -biblios>
447 Type of import: bibliographic records
449 =item B<-a, -authorities>
451 Type of import: authority records
453 =item B<-file>=I<FILE>
455 The I<FILE> to import
459 Verbose mode. 1 means "some infos", 2 means "MARC dumping"
463 Turn off foreign key checks during import.
465 =item B<-n>=I<NUMBER>
467 The I<NUMBER> of records to import. If missing, all the file is imported
469 =item B<-o, -offset>=I<NUMBER>
471 File offset before importing, ie I<NUMBER> of records to skip.
473 =item B<-commit>=I<NUMBER>
475 The I<NUMBER> of records to wait before performing a 'commit' operation
479 File logs actions done for each record and their status into file
483 Test mode: parses the file, saying what he would do, but doing nothing.
487 Skip automatic conversion of MARC-8 to UTF-8. This option is provided for
490 =item B<-c>=I<CHARACTERISTIC>
492 The I<CHARACTERISTIC> MARC flavour. At the moment, only I<MARC21> and
493 I<UNIMARC> are supported. MARC21 by default.
497 Delete EVERYTHING related to biblio in koha-DB before import. Tables: biblio,
500 =item B<-m>=I<FORMAT>
502 Input file I<FORMAT>: I<MARCXML> or I<ISO2709> (defaults to ISO2709)
504 =item B<-k, -keepids>=<FIELD>
506 Field store ids in I<FIELD> (usefull for authorities, where 001 contains the
507 authid for Koha, that can contain a very valuable info for authorities coming
508 from LOC or BNF. useless for biblios probably)
510 =item B<-match>=<FIELD>
512 I<FIELD> matchindex,fieldtomatch matchpoint to use to deduplicate fieldtomatch
513 can be either 001 to 999 or field and list of subfields as such 100abcde
517 If set, a search will be done on isbn, and, if the same isbn is found, the
518 biblio is not added. It's another method to deduplicate. B<-match> & B<-isbn>
523 Source bib I<TAG> for reporting the source bib number
525 =item B<-y>=I<SUBFIELD>
527 Source I<SUBFIELD> for reporting the source bib number
529 =item B<-idmap>=I<FILE>
531 I<FILE> for the koha bib and source id
535 Store ids in 009 (usefull for authorities, where 001 contains the authid for
536 Koha, that can contain a very valuable info for authorities coming from LOC or
537 BNF. useless for biblios probably)