removed extraneous comments
[koha.git] / misc / migration_tools / bulkmarcimport.pl
1 #!/usr/bin/perl
2 # small script that import an iso2709 file into koha 2.0
3
4 use strict;
5 # use warnings;
6 BEGIN {
7     # find Koha's Perl modules
8     # test carefully before changing this
9     use FindBin;
10     eval { require "$FindBin::Bin/../kohalib.pl" };
11 }
12
13 # Koha modules used
14 use MARC::File::USMARC;
15 # Uncomment the line below and use MARC::File::XML again when it works better.
16 # -- thd
17 # use MARC::File::XML;
18 use MARC::Record;
19 use MARC::Batch;
20 use MARC::Charset;
21
22 # According to kados, an undocumented feature of setting MARC::Charset to 
23 # ignore_errors(1) is that errors are not ignored.  Instead of deleting the 
24 # whole subfield when a character does not translate properly from MARC8 into 
25 # UTF-8, just the problem characters are deleted.  This should solve at least 
26 # some of the fixme problems for fMARC8ToUTF8().
27
28 # Problems remain if there are MARC 21 records where 000/09 is set incorrectly. 
29 # -- thd.
30 # MARC::Charset->ignore_errors(1);
31
32 use C4::Context;
33 use C4::Biblio;
34 use Time::HiRes qw(gettimeofday);
35 use Getopt::Long;
36 binmode(STDOUT, ":utf8");
37
38 use Getopt::Long;
39
40 my ( $input_marc_file, $number) = ('',0);
41 my ($version, $delete, $test_parameter,$char_encoding, $verbose, $commit,$fk_off);
42
43 $|=1;
44
45 GetOptions(
46     'commit:f'    => \$commit,
47     'file:s'    => \$input_marc_file,
48     'n:f' => \$number,
49     'h' => \$version,
50     'd' => \$delete,
51     't' => \$test_parameter,
52     'c:s' => \$char_encoding,
53     'v:s' => \$verbose,
54     'fk' => \$fk_off,
55 );
56
57 # FIXME:  Management of error conditions needed for record parsing problems
58 # and MARC8 character sets with mappings to Unicode not yet included in 
59 # MARC::Charset.  The real world rarity of these problems is not fully tested.
60 # Unmapped character sets will throw a warning currently and processing will 
61 # continue with the error condition.  A fairly trivial correction should 
62 # address some record parsing and unmapped character set problems but I need 
63 # time to implement a test and correction for undef subfields and revert to 
64 # MARC8 if mappings are missing. -- thd
65 sub fMARC8ToUTF8($$) {
66     my ($record) = shift;
67     my ($verbose) = shift;
68     if ($verbose) {
69         if ($verbose >= 2) {
70             my $leader = $record->leader();
71             $leader =~ s/ /#/g;
72             print "\n000 " . $leader;
73         }
74     }
75     foreach my $field ($record->fields()) {
76         if ($field->is_control_field()) {
77             if ($verbose) {
78                 if ($verbose >= 2) {
79                     my $fieldName = $field->tag();
80                     my $fieldValue = $field->data();
81                     $fieldValue =~ s/ /#/g;
82                     print "\n" . $fieldName;
83                     print ' ' . $fieldValue;
84                 }
85             }
86         } else {
87             my @subfieldsArray;
88             my $fieldName = $field->tag();
89             my $indicator1Value = $field->indicator(1);
90             my $indicator2Value = $field->indicator(2);
91             if ($verbose) {
92                 if ($verbose >= 2) {
93                     $indicator1Value =~ s/ /#/;
94                     $indicator2Value =~ s/ /#/;
95                     print "\n" . $fieldName . ' ' .
96                             $indicator1Value .
97                     $indicator2Value;
98                 }
99             }
100             foreach my $subfield ($field->subfields()) {
101                 my $subfieldName = $subfield->[0];
102                 my $subfieldValue = $subfield->[1];
103                 $subfieldValue = MARC::Charset::marc8_to_utf8($subfieldValue);
104     
105                 # Alas, MARC::Field::update() does not work correctly.
106                 ## push (@subfieldsArray, $subfieldName, $subfieldValue);
107     
108                 push @subfieldsArray, [$subfieldName, $subfieldValue];
109                 if ($verbose) {
110                     if ($verbose >= 2) {
111                         print " \$" . $subfieldName . ' ' . $subfieldValue;
112                     }
113                 }
114             }
115     
116             # Alas, MARC::Field::update() does not work correctly.
117             #
118             # The first instance in the field of a of a repeated subfield
119             # overwrites the content from later instances with the content
120             # from the first instance.
121             ## $field->update(@subfieldsArray);
122     
123             foreach my $subfieldRow(@subfieldsArray) {
124                 my $subfieldName = $subfieldRow->[0];
125                 $field->delete_subfields($subfieldName);
126             }
127             foreach my $subfieldRow(@subfieldsArray) {
128                 $field->add_subfields(@$subfieldRow);
129             }
130     
131             if ($verbose) {
132                 if ($verbose >= 2) {
133                     # Reading the indicator values again is not necessary.
134                     # They were not converted.
135                     # $indicator1Value = $field->indicator(1);
136                     # $indicator2Value = $field->indicator(2);
137                     # $indicator1Value =~ s/ /#/;
138                     # $indicator2Value =~ s/ /#/;
139                     print "\nCONVERTED TO UTF-8:\n" . $fieldName . ' ' .
140                             $indicator1Value .
141                     $indicator2Value;
142                     foreach my $subfield ($field->subfields()) {
143                         my $subfieldName = $subfield->[0];
144                         my $subfieldValue = $subfield->[1];
145                         print " \$" . $subfieldName . ' ' . $subfieldValue;
146                     }
147                 }
148             }
149             if ($verbose) {
150                 if ($verbose >= 2) {
151                     print "\n" if $verbose;
152                 }
153             }
154         }
155     }
156     $record->encoding('UTF-8');
157     return $record;
158 }
159
160
161 if ($version || ($input_marc_file eq '')) {
162     print <<EOF
163 small script to import an iso2709 file into Koha.
164 parameters :
165 \th : this version/help screen
166 \tfile /path/to/file/to/dump : the file to import
167 \tv : verbose mode. 1 means "some infos", 2 means "MARC dumping"
168 \tfk : Turn off foreign key checks during import.
169 \tn : the number of records to import. If missing, all the file is imported
170 \tcommit : the number of records to wait before performing a 'commit' operation
171 \tt : test mode : parses the file, saying what he would do, but doing nothing.
172 \tc : the characteristic MARC flavour. At the moment, only MARC21 and UNIMARC 
173 \tsupported. MARC21 by default.
174 \td : delete EVERYTHING related to biblio in koha-DB before import  :tables :
175 \t\tbiblio, \tbiblioitems,\titems
176 IMPORTANT : don't use this script before you've entered and checked your MARC parameters tables twice (or more!).
177 Otherwise, the import won't work correctly and you will get invalid data.
178
179 SAMPLE : 
180 \t\$ export KOHA_CONF=/etc/koha.conf
181 \t\$ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 -file /home/jmf/koha.mrc -n 3000
182 EOF
183 ;#'
184 exit;
185 }
186
187 my $dbh = C4::Context->dbh;
188
189 # save the CataloguingLog property : we don't want to log a bulkmarcimport. It will slow the import & 
190 # will create problems in the action_logs table, that can't handle more than 1 entry per second per user.
191 my $CataloguingLog = C4::Context->preference('CataloguingLog');
192 $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='CataloguingLog'");
193
194 if ($delete) {
195     print "deleting biblios\n";
196     $dbh->do("truncate biblio");
197     $dbh->do("truncate biblioitems");
198     $dbh->do("truncate items");
199 }
200 if ($fk_off) {
201         $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
202 }
203 if ($test_parameter) {
204     print "TESTING MODE ONLY\n    DOING NOTHING\n===============\n";
205 }
206
207 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
208
209 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
210 my $starttime = gettimeofday;
211 my $batch = MARC::Batch->new( 'USMARC', $input_marc_file );
212 $batch->warnings_off();
213 $batch->strict_off();
214 my $i=0;
215 my $commitnum = 50;
216
217 if ($commit) {
218
219 $commitnum = $commit;
220
221 }
222
223 my $dbh = C4::Context->dbh();
224 $dbh->{AutoCommit} = 0;
225 while ( my $record = $batch->next() ) {
226     $i++;
227     print ".";
228     print "\r$i" unless $i % 100;
229
230     unless ($test_parameter) {
231         my ( $bibid, $oldbibitemnum, $itemnumbers_ref, $errors_ref );
232         eval { ( $bibid, $oldbibitemnum, $itemnumbers_ref, $errors_ref ) = AddBiblioAndItems( $record, '' ); };
233         if ( $@ ) {
234             warn "ERROR: Adding biblio and or items $bibid failed: $@\n";
235         } 
236         if ($#{ $errors_ref } > -1) { 
237             report_item_errors($bibid, $errors_ref);
238         }
239
240         $dbh->commit() if (0 == $i % $commitnum);
241     }
242     last if $i == $number;
243 }
244 $dbh->commit();
245
246
247 if ($fk_off) {
248         $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
249 }
250
251 # restore CataloguingLog
252 $dbh->do("UPDATE systempreferences SET value=$CataloguingLog WHERE variable='CataloguingLog'");
253
254 my $timeneeded = gettimeofday - $starttime;
255 print "$i MARC records done in $timeneeded seconds\n";
256
257 exit 0;
258
259 sub report_item_errors {
260     my $bibid = shift;
261     my $errors_ref = shift;
262
263     foreach my $error (@{ $errors_ref }) {
264         my $msg = "Item not added (bib $bibid, item tag #$error->{'item_sequence'}, barcode $error->{'item_barcode'}): ";
265         my $error_code = $error->{'error_code'};
266         $error_code =~ s/_/ /g;
267         $msg .= "$error_code $error->{'error_information'}";
268         print $msg, "\n";
269     }
270 }