Bug 28959: Add virtualshelves.public as a boolean
[koha.git] / misc / batchRebuildBiblioTables.pl
1 #!/usr/bin/perl
2 # Small script that rebuilds the non-MARC DB
3 # Formerly named rebuildnonmarc.pl
4
5 use strict;
6 #use warnings; FIXME - Bug 2505
7
8 BEGIN {
9     # find Koha's Perl modules
10     # test carefully before changing this
11     use FindBin ();
12     eval { require "$FindBin::Bin/kohalib.pl" };
13 }
14
15 # Koha modules used
16 use Koha::Script;
17 use MARC::Record;
18 use C4::Charset;
19 use C4::Context;
20 use C4::Biblio qw(
21     GetXmlBiblio
22     TransformMarcToKoha
23 );
24 use Time::HiRes qw( gettimeofday );
25
26 use Getopt::Long qw( GetOptions );
27
28 my ($version, $confirm);
29 GetOptions(
30     'c' => \$confirm,
31     'h' => \$version
32 );
33
34 if ($version || (!$confirm)) {
35     print <<EOF
36 This script rebuilds the non-MARC fields from the MARC values.
37 You can/must use it when you change your mapping.
38
39 Example: you decide to map biblio.title to 200\$a (it was previously mapped to 610\$a).
40 Run this script or you will have strange results in the UI!
41
42 Syntax:
43 \t./batchRebuildBiblioTables.pl -h (or without arguments => show this screen)
44 \t./batchRebuildBiblioTables.pl -c (c like confirm => rebuild non-MARC fields (may take long)
45 EOF
46 ;
47     exit;
48 }
49
50 $|=1; # non-buffered output
51
52 my $dbh = C4::Context->dbh;
53 my $i=0;
54 my $starttime = gettimeofday;
55 my $marcflavour = C4::Context->preference('marcflavour');
56 my $sth = $dbh->prepare('SELECT biblionumber, frameworkcode FROM biblio');
57 $sth->execute();
58
59 my @errors;
60 while (my ($biblionumber, $frameworkcode) = $sth->fetchrow) {
61     my $marcxml = GetXmlBiblio($biblionumber);
62     if (not defined $marcxml) {
63         push @errors, $biblionumber;
64         next;
65     }
66
67     $marcxml = C4::Charset::StripNonXmlChars( $marcxml );
68     my $record = eval {
69         MARC::Record::new_from_xml($marcxml, 'UTF-8', $marcflavour);
70     };
71     if ($@) {
72         push @errors, $biblionumber;
73         next;
74     }
75
76     my $biblio = TransformMarcToKoha($record);
77     C4::Biblio::_koha_modify_biblio($dbh, $biblio, $frameworkcode);
78     C4::Biblio::_koha_modify_biblioitem_nonmarc($dbh, $biblio);
79
80     $i++;
81     printf("%lu records processed in %.2f seconds\n", $i, gettimeofday() - $starttime) unless ($i % 100);
82 }
83
84 printf("\n%lu records processed in %.2f seconds\n", $i, gettimeofday() - $starttime);
85 if (scalar(@errors) > 0) {
86     print "Some records could not be processed though: ", join(' ', @errors);
87 }