MARC import: part 5 of large file support
[koha.git] / tools / stage-marc-import.pl
1 #!/usr/bin/perl
2
3 # Script for handling import of MARC data into Koha db
4 #   and Z39.50 lookups
5
6 # Koha library project  www.koha.org
7
8 # Licensed under the GPL
9
10 # Copyright 2000-2002 Katipo Communications
11 #
12 # This file is part of Koha.
13 #
14 # Koha is free software; you can redistribute it and/or modify it under the
15 # terms of the GNU General Public License as published by the Free Software
16 # Foundation; either version 2 of the License, or (at your op) any later
17 # version.
18 #
19 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
20 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
21 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License along with
24 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
25 # Suite 330, Boston, MA  02111-1307 USA
26
27 use strict;
28
29 # standard or CPAN modules used
30 use CGI;
31 use CGI::Cookie;
32 use MARC::File::USMARC;
33
34 # Koha modules used
35 use C4::Context;
36 use C4::Auth;
37 use C4::Input;
38 use C4::Output;
39 use C4::Biblio;
40 use C4::ImportBatch;
41 use C4::Matcher;
42 use C4::UploadedFile;
43 use C4::BackgroundJob;
44
45 my $input = new CGI;
46 my $dbh = C4::Context->dbh;
47
48 my $fileID=$input->param('uploadedfileid');
49 my $runinbackground = $input->param('runinbackground');
50 my $completedJobID = $input->param('completedJobID');
51 my $matcher_id = $input->param('matcher');
52 my $parse_items = $input->param('parse_items');
53 my $comments = $input->param('comments');
54 my $syntax = $input->param('syntax');
55 my ($template, $loggedinuser, $cookie)
56         = get_template_and_user({template_name => "tools/stage-marc-import.tmpl",
57                                         query => $input,
58                                         type => "intranet",
59                                         authnotrequired => 0,
60                                         flagsrequired => {tools => 1},
61                                         debug => 1,
62                                         });
63
64 $template->param(SCRIPT_NAME => $ENV{'SCRIPT_NAME'},
65                                                 uploadmarc => $fileID);
66
67 my %cookies = parse CGI::Cookie($cookie);
68 my $sessionID = $cookies{'CGISESSID'}->value;
69 if ($completedJobID) {
70     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
71     my $results = $job->results();
72     $template->param(map { $_ => $results->{$_} } keys %{ $results });
73 } elsif ($fileID) {
74     my $uploaded_file = C4::UploadedFile->fetch($sessionID, $fileID);
75     my $fh = $uploaded_file->fh();
76         my $marcrecord='';
77         while (<$fh>) {
78                 $marcrecord.=$_;
79         }
80
81     my $filename = $uploaded_file->name();
82     my $job = undef;
83     my $staging_callback = sub { };
84     my $matching_callback = sub { };
85     warn "$matcher_id is the matcher";
86     if ($runinbackground) {
87         my $job_size = () = $marcrecord =~ /\035/g;
88         # if we're matching, job size is doubled
89         $job_size *= 2 if ($matcher_id ne "");
90         $job = C4::BackgroundJob->new($sessionID, $filename, $ENV{'SCRIPT_NAME'}, $job_size);
91         my $jobID = $job->id();
92
93         # fork off
94         if (my $pid = fork) {
95             # parent
96             # return job ID as JSON
97             
98             # prevent parent exiting from
99             # destroying the kid's database handle
100             # FIXME: according to DBI doc, this may not work for Oracle
101             $dbh->{InactiveDestroy}  = 1;
102
103             my $reply = CGI->new("");
104             print $reply->header(-type => 'text/html');
105             print "{ jobID: '$jobID' }";
106             exit 0;
107         } elsif (defined $pid) {
108             # child
109             # close STDOUT to signal to Apache that
110             # we're now running in the background
111             close STDOUT;
112             close STDERR;
113         } else {
114             # fork failed, so exit immediately
115             warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
116             exit 0;
117         }
118
119         # if we get here, we're a child that has detached
120         # itself from Apache
121         $staging_callback = staging_progress_callback($job);
122         $matching_callback = matching_progress_callback($job);
123
124     }
125
126     # FIXME branch code
127     my ($batch_id, $num_valid, $num_items, @import_errors) = BatchStageMarcRecords($syntax, $marcrecord, $filename, 
128                                                                                    $comments, '', $parse_items, 0,
129                                                                                    50, staging_progress_callback($job));
130     my $num_with_matches = 0;
131     my $checked_matches = 0;
132     my $matcher_failed = 0;
133     my $matcher_code = "";
134     if ($matcher_id ne "") {
135         warn "we must match $matcher_id";
136         my $matcher = C4::Matcher->fetch($matcher_id);
137         if (defined $matcher) {
138             warn "failed to retrieve";
139             $checked_matches = 1;
140             $matcher_code = $matcher->code();
141             $num_with_matches = BatchFindBibDuplicates($batch_id, $matcher, 10, 50, matching_progress_callback($job));
142             SetImportBatchMatcher($batch_id, $matcher_id);
143         } else {
144             $matcher_failed = 1;
145         }
146     }
147
148     my $results = {
149             staged => $num_valid,
150             matched => $num_with_matches,
151         num_items => $num_items,
152         import_errors => scalar(@import_errors),
153         total => $num_valid + scalar(@import_errors),
154         checked_matches => $checked_matches,
155         matcher_failed => $matcher_failed,
156         matcher_code => $matcher_code,
157         import_batch_id => $batch_id
158     };
159     if ($runinbackground) {
160         $job->finish($results);
161     } else {
162             $template->param(staged => $num_valid,
163                              matched => $num_with_matches,
164                          num_items => $num_items,
165                          import_errors => scalar(@import_errors),
166                          total => $num_valid + scalar(@import_errors),
167                          checked_matches => $checked_matches,
168                          matcher_failed => $matcher_failed,
169                          matcher_code => $matcher_code,
170                          import_batch_id => $batch_id
171                         );
172     }
173
174 } else {
175     # initial form
176     my @matchers = C4::Matcher::GetMatcherList();
177     $template->param(available_matchers => \@matchers);
178 }
179
180 output_html_with_http_headers $input, $cookie, $template->output;
181
182 exit 0;
183
184 sub staging_progress_callback {
185     my $job = shift;
186     return sub {
187         my $progress = shift;
188         $job->progress($progress);
189     }
190 }
191
192 sub matching_progress_callback {
193     my $job = shift;
194     my $start_progress = $job->progress();
195     return sub {
196         my $progress = shift;
197         $job->progress($start_progress + $progress);
198     }
199 }