Bug 10407: Allow MARCXML records to be imported via GUI (groundwork)
[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-community.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
15 # under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 3 of the License, or
17 # (at your option) any later version.
18 #
19 # Koha is distributed in the hope that it will be useful, but
20 # WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26
27 use strict;
28 #use warnings; FIXME - Bug 2505
29
30 # standard or CPAN modules used
31 use CGI qw ( -utf8 );
32 use CGI::Cookie;
33 use MARC::File::USMARC;
34
35 # Koha modules used
36 use C4::Context;
37 use C4::Auth;
38 use C4::Output;
39 use C4::Biblio;
40 use C4::ImportBatch;
41 use C4::Matcher;
42 use Koha::Upload;
43 use C4::BackgroundJob;
44 use C4::MarcModificationTemplates;
45 use Koha::Plugins;
46
47 my $input = new CGI;
48
49 my $fileID                     = $input->param('uploadedfileid');
50 my $runinbackground            = $input->param('runinbackground');
51 my $completedJobID             = $input->param('completedJobID');
52 my $matcher_id                 = $input->param('matcher');
53 my $overlay_action             = $input->param('overlay_action');
54 my $nomatch_action             = $input->param('nomatch_action');
55 my $parse_items                = $input->param('parse_items');
56 my $item_action                = $input->param('item_action');
57 my $comments                   = $input->param('comments');
58 my $record_type                = $input->param('record_type');
59 my $encoding                   = $input->param('encoding') || 'utf8';
60 my $format                     = $input->param('format') || 'ISO2709';
61 my $to_marc_plugin             = $input->param('to_marc_plugin');
62 my $marc_modification_template = $input->param('marc_modification_template_id');
63
64 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
65     {
66         template_name   => "tools/stage-marc-import.tt",
67         query           => $input,
68         type            => "intranet",
69         authnotrequired => 0,
70         flagsrequired   => { tools => 'stage_marc_import' },
71         debug           => 1,
72     }
73 );
74
75 $template->param(
76     SCRIPT_NAME => '/cgi-bin/koha/tools/stage-marc-import.pl',
77     uploadmarc  => $fileID,
78     record_type => $record_type,
79 );
80
81 my %cookies = parse CGI::Cookie($cookie);
82 my $sessionID = $cookies{'CGISESSID'}->value;
83 if ($completedJobID) {
84     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
85     my $results = $job->results();
86     $template->param(map { $_ => $results->{$_} } keys %{ $results });
87 } elsif ($fileID) {
88     my $upload = Koha::Upload->new->get({ id => $fileID });
89     my $filename = $upload->{path};
90         my $marcrecord='';
91     my ($errors, $marcrecords) = C4::ImportBatch::RecordsFromISO2709File($uploaded_file->filename(), $record_type, $encoding);
92
93     my $job = undef;
94     my $dbh;
95     if ($runinbackground) {
96         my $job_size = scalar(@$marcrecords);
97         # if we're matching, job size is doubled
98         $job_size *= 2 if ($matcher_id ne "");
99         $job = C4::BackgroundJob->new($sessionID, $filename, '/cgi-bin/koha/tools/stage-marc-import.pl', $job_size);
100         my $jobID = $job->id();
101
102         # fork off
103         if (my $pid = fork) {
104             # parent
105             # return job ID as JSON
106             my $reply = CGI->new("");
107             print $reply->header(-type => 'text/html');
108             print '{"jobID":"' . $jobID . '"}';
109             exit 0;
110         } elsif (defined $pid) {
111             # child
112             # close STDOUT to signal to Apache that
113             # we're now running in the background
114             close STDOUT;
115             # close STDERR; # there is no good reason to close STDERR
116         } else {
117             # fork failed, so exit immediately
118             warn "fork failed while attempting to run tools/stage-marc-import.pl as a background job: $!";
119             exit 0;
120         }
121
122         # if we get here, we're a child that has detached
123         # itself from Apache
124
125     }
126
127     # New handle, as we're a child.
128     $dbh = C4::Context->dbh({new => 1});
129     $dbh->{AutoCommit} = 0;
130     # FIXME branch code
131     my ( $batch_id, $num_valid, $num_items, @import_errors ) =
132       BatchStageMarcRecords(
133         $record_type,    $encoding,
134         $marcrecords,    $filename,
135         $to_marc_plugin, $marc_modification_template,
136         $comments,       '',
137         $parse_items,    0,
138         50, staging_progress_callback( $job, $dbh )
139       );
140
141     my $num_with_matches = 0;
142     my $checked_matches = 0;
143     my $matcher_failed = 0;
144     my $matcher_code = "";
145     if ($matcher_id ne "") {
146         my $matcher = C4::Matcher->fetch($matcher_id);
147         if (defined $matcher) {
148             $checked_matches = 1;
149             $matcher_code = $matcher->code();
150             $num_with_matches =
151               BatchFindDuplicates( $batch_id, $matcher, 10, 50,
152                 matching_progress_callback( $job, $dbh ) );
153             SetImportBatchMatcher($batch_id, $matcher_id);
154             SetImportBatchOverlayAction($batch_id, $overlay_action);
155             SetImportBatchNoMatchAction($batch_id, $nomatch_action);
156             SetImportBatchItemAction($batch_id, $item_action);
157             $dbh->commit();
158         } else {
159             $matcher_failed = 1;
160         }
161     } else {
162         $dbh->commit();
163     }
164
165     my $results = {
166         staged          => $num_valid,
167         matched         => $num_with_matches,
168         num_items       => $num_items,
169         import_errors   => scalar(@import_errors),
170         total           => $num_valid + scalar(@import_errors),
171         checked_matches => $checked_matches,
172         matcher_failed  => $matcher_failed,
173         matcher_code    => $matcher_code,
174         import_batch_id => $batch_id
175     };
176     if ($runinbackground) {
177         $job->finish($results);
178     } else {
179             $template->param(staged => $num_valid,
180                              matched => $num_with_matches,
181                          num_items => $num_items,
182                          import_errors => scalar(@import_errors),
183                          total => $num_valid + scalar(@import_errors),
184                          checked_matches => $checked_matches,
185                          matcher_failed => $matcher_failed,
186                          matcher_code => $matcher_code,
187                          import_batch_id => $batch_id
188                         );
189     }
190
191 } else {
192     # initial form
193     if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
194         $template->param( "UNIMARC" => 1 );
195     }
196     my @matchers = C4::Matcher::GetMatcherList();
197     $template->param( available_matchers => \@matchers );
198
199     my @templates = GetModificationTemplates();
200     $template->param( MarcModificationTemplatesLoop => \@templates );
201
202     if ( C4::Context->preference('UseKohaPlugins') &&
203          C4::Context->config('enable_plugins') ) {
204
205         my @plugins = Koha::Plugins->new()->GetPlugins('to_marc');
206         $template->param( plugins => \@plugins );
207     }
208 }
209
210 output_html_with_http_headers $input, $cookie, $template->output;
211
212 exit 0;
213
214 sub staging_progress_callback {
215     my $job = shift;
216     my $dbh = shift;
217     return sub {
218         my $progress = shift;
219         $job->progress($progress);
220     }
221 }
222
223 sub matching_progress_callback {
224     my $job = shift;
225     my $dbh = shift;
226     my $start_progress = $job->progress();
227     return sub {
228         my $progress = shift;
229         $job->progress($start_progress + $progress);
230     }
231 }