(minor) updating doc & removing warn
[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
7 # Koha modules used
8 use MARC::File::USMARC;
9 # Uncomment the line below and use MARC::File::XML again when it works better.
10 # -- thd
11 # use MARC::File::XML;
12 use MARC::Record;
13 use MARC::Batch;
14 use MARC::Charset;
15
16 # According to kados, an undocumented feature of setting MARC::Charset to 
17 # ignore_errors(1) is that errors are not ignored.  Instead of deleting the 
18 # whole subfield when a character does not translate properly from MARC8 into 
19 # UTF-8, just the problem characters are deleted.  This should solve at least 
20 # some of the fixme problems for fMARC8ToUTF8().
21
22 # Problems remain if there are MARC 21 records where 000/09 is set incorrectly. 
23 # -- thd.
24 # MARC::Charset->ignore_errors(1);
25
26 use C4::Context;
27 use C4::Biblio;
28 use Time::HiRes qw(gettimeofday);
29 use Getopt::Long;
30 binmode(STDOUT, ":utf8");
31
32 use Getopt::Long;
33
34 my ( $input_marc_file, $number) = ('',0);
35 my ($version, $delete, $test_parameter,$char_encoding, $verbose, $commit,$fk_off);
36
37 $|=1;
38
39 GetOptions(
40     'commit:f'    => \$commit,
41     'file:s'    => \$input_marc_file,
42     'n:f' => \$number,
43     'h' => \$version,
44     'd' => \$delete,
45     't' => \$test_parameter,
46     'c:s' => \$char_encoding,
47     'v:s' => \$verbose,
48     'fk' => \$fk_off,
49 );
50
51 # FIXME:  Management of error conditions needed for record parsing problems
52 # and MARC8 character sets with mappings to Unicode not yet included in 
53 # MARC::Charset.  The real world rarity of these problems is not fully tested.
54 # Unmapped character sets will throw a warning currently and processing will 
55 # continue with the error condition.  A fairly trivial correction should 
56 # address some record parsing and unmapped character set problems but I need 
57 # time to implement a test and correction for undef subfields and revert to 
58 # MARC8 if mappings are missing. -- thd
59 sub fMARC8ToUTF8($$) {
60     my ($record) = shift;
61     my ($verbose) = shift;
62     if ($verbose) {
63         if ($verbose >= 2) {
64             my $leader = $record->leader();
65             $leader =~ s/ /#/g;
66             print "\n000 " . $leader;
67         }
68     }
69     foreach my $field ($record->fields()) {
70         if ($field->is_control_field()) {
71             if ($verbose) {
72                 if ($verbose >= 2) {
73                     my $fieldName = $field->tag();
74                     my $fieldValue = $field->data();
75                     $fieldValue =~ s/ /#/g;
76                     print "\n" . $fieldName;
77                     print ' ' . $fieldValue;
78                 }
79             }
80         } else {
81             my @subfieldsArray;
82             my $fieldName = $field->tag();
83             my $indicator1Value = $field->indicator(1);
84             my $indicator2Value = $field->indicator(2);
85             if ($verbose) {
86                 if ($verbose >= 2) {
87                     $indicator1Value =~ s/ /#/;
88                     $indicator2Value =~ s/ /#/;
89                     print "\n" . $fieldName . ' ' .
90                             $indicator1Value .
91                     $indicator2Value;
92                 }
93             }
94             foreach my $subfield ($field->subfields()) {
95                 my $subfieldName = $subfield->[0];
96                 my $subfieldValue = $subfield->[1];
97                 $subfieldValue = MARC::Charset::marc8_to_utf8($subfieldValue);
98     
99                 # Alas, MARC::Field::update() does not work correctly.
100                 ## push (@subfieldsArray, $subfieldName, $subfieldValue);
101     
102                 push @subfieldsArray, [$subfieldName, $subfieldValue];
103                 if ($verbose) {
104                     if ($verbose >= 2) {
105                         print " \$" . $subfieldName . ' ' . $subfieldValue;
106                     }
107                 }
108             }
109     
110             # Alas, MARC::Field::update() does not work correctly.
111             #
112             # The first instance in the field of a of a repeated subfield
113             # overwrites the content from later instances with the content
114             # from the first instance.
115             ## $field->update(@subfieldsArray);
116     
117             foreach my $subfieldRow(@subfieldsArray) {
118                 my $subfieldName = $subfieldRow->[0];
119                 $field->delete_subfields($subfieldName);
120             }
121             foreach my $subfieldRow(@subfieldsArray) {
122                 $field->add_subfields(@$subfieldRow);
123             }
124     
125             if ($verbose) {
126                 if ($verbose >= 2) {
127                     # Reading the indicator values again is not necessary.
128                     # They were not converted.
129                     # $indicator1Value = $field->indicator(1);
130                     # $indicator2Value = $field->indicator(2);
131                     # $indicator1Value =~ s/ /#/;
132                     # $indicator2Value =~ s/ /#/;
133                     print "\nCONVERTED TO UTF-8:\n" . $fieldName . ' ' .
134                             $indicator1Value .
135                     $indicator2Value;
136                     foreach my $subfield ($field->subfields()) {
137                         my $subfieldName = $subfield->[0];
138                         my $subfieldValue = $subfield->[1];
139                         print " \$" . $subfieldName . ' ' . $subfieldValue;
140                     }
141                 }
142             }
143             if ($verbose) {
144                 if ($verbose >= 2) {
145                     print "\n" if $verbose;
146                 }
147             }
148         }
149     }
150     $record->encoding('UTF-8');
151     return $record;
152 }
153
154
155 if ($version || ($input_marc_file eq '')) {
156     print <<EOF
157 small script to import an iso2709 file into Koha.
158 parameters :
159 \th : this version/help screen
160 \tfile /path/to/file/to/dump : the file to import
161 \tv : verbose mode. 1 means "some infos", 2 means "MARC dumping"
162 \tfk : Turn off foreign key checks during import.
163 \tn : the number of records to import. If missing, all the file is imported
164 \tcommit : the number of records to wait before performing a 'commit' operation
165 \tt : test mode : parses the file, saying what he would do, but doing nothing.
166 \tc : the characteristic MARC flavour. At the moment, only MARC21 and UNIMARC 
167 \tsupported. MARC21 by default.
168 \td : delete EVERYTHING related to biblio in koha-DB before import  :tables :
169 \t\tbiblio, \tbiblioitems,\titems
170 IMPORTANT : don't use this script before you've entered and checked your MARC parameters tables twice (or more!).
171 Otherwise, the import won't work correctly and you will get invalid data.
172
173 SAMPLE : 
174 \t\$ export KOHA_CONF=/etc/koha.conf
175 \t\$ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 -file /home/jmf/koha.mrc -n 3000
176 EOF
177 ;#'
178 exit;
179 }
180
181 my $dbh = C4::Context->dbh;
182
183 if ($delete) {
184     print "deleting biblios\n";
185     $dbh->do("truncate biblio");
186     $dbh->do("truncate biblioitems");
187     $dbh->do("truncate items");
188 }
189 if ($fk_off) {
190         $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
191 }
192 if ($test_parameter) {
193     print "TESTING MODE ONLY\n    DOING NOTHING\n===============\n";
194 }
195
196 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
197
198 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
199 # die;
200 my $starttime = gettimeofday;
201 my $batch = MARC::Batch->new( 'USMARC', $input_marc_file );
202 $batch->warnings_off();
203 $batch->strict_off();
204 my $i=0;
205 my $commitnum = 50;
206
207 if ($commit) {
208
209 $commitnum = $commit;
210
211 }
212
213 #1st of all, find item MARC tag.
214 my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
215 # $dbh->do("lock tables biblio write, biblioitems write, items write, marc_biblio write, marc_subfield_table write, marc_blob_subfield write, marc_word write, marc_subfield_structure write, stopwords write");
216 while ( my $record = $batch->next() ) {
217 # warn "=>".$record->as_formatted;
218 # warn "I:".$i;
219 # warn "NUM:".$number;
220     $i++;
221     print ".";
222     print "\r$i" unless $i % 100;
223 #     if ($i==$number) {
224 #         z3950_extended_services('commit',set_service_options('commit'));
225 #         print "COMMIT OPERATION SUCCESSFUL\n";
226
227 #         my $timeneeded = gettimeofday - $starttime;
228 #         die "$i MARC records imported in $timeneeded seconds\n";
229 #     }
230 #     # perform the commit operation ever so often
231 #     if ($i==$commit) {
232 #         z3950_extended_services('commit',set_service_options('commit'));
233 #         $commit+=$commitnum;
234 #         print "COMMIT OPERATION SUCCESSFUL\n";
235 #     }
236     #now, parse the record, extract the item fields, and store them in somewhere else.
237
238     ## create an empty record object to populate
239     my $newRecord = MARC::Record->new();
240     $newRecord->leader($record->leader());
241
242     # go through each field in the existing record
243     foreach my $oldField ( $record->fields() ) {
244
245     # just reproduce tags < 010 in our new record
246     #
247     # Fields are not necessarily only numeric in the actual world of records
248     # nor in what I would recommend for additonal safe non-interfering local
249     # use fields.  The following regular expression match is much safer than
250     # a numeric evaluation. -- thd
251     if ( $oldField->tag() =~ m/^00/ ) {
252         $newRecord->append_fields( $oldField );
253         next();
254     }
255
256     # store our new subfield data in this list
257     my @newSubfields = ();
258
259     # go through each subfield code/data pair
260     foreach my $pair ( $oldField->subfields() ) {
261         #$pair->[1] =~ s/\<//g;
262         #$pair->[1] =~ s/\>//g;
263         push( @newSubfields, $pair->[0], $pair->[1] ); #char_decode($pair->[1],$char_encoding) );
264     }
265
266     # add the new field to our new record
267     my $newField = MARC::Field->new(
268         $oldField->tag(),
269         $oldField->indicator(1),
270         $oldField->indicator(2),
271         @newSubfields
272     );
273
274     $newRecord->append_fields( $newField );
275
276     }
277
278     warn "$i ==>".$newRecord->as_formatted() if $verbose eq 2;
279     my @fields = $newRecord->field($tagfield);
280     my @items;
281     my $nbitems=0;
282
283     foreach my $field (@fields) {
284         my $item = MARC::Record->new();
285         $item->append_fields($field);
286         push @items,$item;
287         $newRecord->delete_field($field);
288         $nbitems++;
289     }
290     print "$i : $nbitems items found\n" if $verbose;
291     # now, create biblio and items with Addbiblio call.
292     unless ($test_parameter) {
293         my ($bibid,$oldbibitemnum) = AddBiblio($newRecord,'');
294         warn "ADDED biblio NB $bibid in DB\n" if $verbose;
295         for (my $i=0;$i<=$#items;$i++) {
296 #             warn "here is the biblioitemnumber $oldbibitemnum";
297             AddItem($items[$i],$bibid,$oldbibitemnum);
298         }
299     }
300 }
301 if ($fk_off) {
302         $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
303 }
304 # final commit of the changes
305 #z3950_extended_services('commit',set_service_options('commit'));
306 #print "COMMIT OPERATION SUCCESSFUL\n";
307
308 my $timeneeded = gettimeofday - $starttime;
309 print "$i MARC records done in $timeneeded seconds\n";