Bug 11944: use CGI( -utf8 ) everywhere
[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 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 option) 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
24 # with Koha; if not, write to the Free Software Foundation, Inc.,
25 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 C4::UploadedFile;
43 use C4::BackgroundJob;
44 use C4::MarcModificationTemplates;
45
46 my $input = new CGI;
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 $overlay_action = $input->param('overlay_action');
53 my $nomatch_action = $input->param('nomatch_action');
54 my $parse_items = $input->param('parse_items');
55 my $item_action = $input->param('item_action');
56 my $comments = $input->param('comments');
57 my $record_type = $input->param('record_type');
58 my $encoding = $input->param('encoding');
59 my $marc_modification_template = $input->param('marc_modification_template_id');
60
61 my ($template, $loggedinuser, $cookie)
62     = get_template_and_user({template_name => "tools/stage-marc-import.tt",
63                                         query => $input,
64                                         type => "intranet",
65                                         authnotrequired => 0,
66                                         flagsrequired => {tools => 'stage_marc_import'},
67                                         debug => 1,
68                                         });
69
70 $template->param(SCRIPT_NAME => $ENV{'SCRIPT_NAME'},
71                                                 uploadmarc => $fileID);
72
73 my %cookies = parse CGI::Cookie($cookie);
74 my $sessionID = $cookies{'CGISESSID'}->value;
75 if ($completedJobID) {
76     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
77     my $results = $job->results();
78     $template->param(map { $_ => $results->{$_} } keys %{ $results });
79 } elsif ($fileID) {
80     my $uploaded_file = C4::UploadedFile->fetch($sessionID, $fileID);
81     my $fh = $uploaded_file->fh();
82         my $marcrecord='';
83     $/ = "\035";
84         while (<$fh>) {
85         s/^\s+//;
86         s/\s+$//;
87                 $marcrecord.=$_;
88         }
89
90     my $filename = $uploaded_file->name();
91     my $job = undef;
92     my $dbh;
93     if ($runinbackground) {
94         my $job_size = () = $marcrecord =~ /\035/g;
95         # if we're matching, job size is doubled
96         $job_size *= 2 if ($matcher_id ne "");
97         $job = C4::BackgroundJob->new($sessionID, $filename, $ENV{'SCRIPT_NAME'}, $job_size);
98         my $jobID = $job->id();
99
100         # fork off
101         if (my $pid = fork) {
102             # parent
103             # return job ID as JSON
104             my $reply = CGI->new("");
105             print $reply->header(-type => 'text/html');
106             print '{"jobID":"' . $jobID . '"}';
107             exit 0;
108         } elsif (defined $pid) {
109             # child
110             # close STDOUT to signal to Apache that
111             # we're now running in the background
112             close STDOUT;
113             # close STDERR; # there is no good reason to close STDERR
114         } else {
115             # fork failed, so exit immediately
116             warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job: $!";
117             exit 0;
118         }
119
120         # if we get here, we're a child that has detached
121         # itself from Apache
122
123     }
124
125     # New handle, as we're a child.
126     $dbh = C4::Context->dbh({new => 1});
127     $dbh->{AutoCommit} = 0;
128     # FIXME branch code
129     my ( $batch_id, $num_valid, $num_items, @import_errors ) =
130       BatchStageMarcRecords(
131         $record_type,                $encoding,
132         $marcrecord,                 $filename,
133         $marc_modification_template, $comments,
134         '',                          $parse_items,
135         0,                           50,
136         staging_progress_callback( $job, $dbh )
137       );
138
139     my $num_with_matches = 0;
140     my $checked_matches = 0;
141     my $matcher_failed = 0;
142     my $matcher_code = "";
143     if ($matcher_id ne "") {
144         my $matcher = C4::Matcher->fetch($matcher_id);
145         if (defined $matcher) {
146             $checked_matches = 1;
147             $matcher_code = $matcher->code();
148             $num_with_matches =
149               BatchFindDuplicates( $batch_id, $matcher, 10, 50,
150                 matching_progress_callback( $job, $dbh ) );
151             SetImportBatchMatcher($batch_id, $matcher_id);
152             SetImportBatchOverlayAction($batch_id, $overlay_action);
153             SetImportBatchNoMatchAction($batch_id, $nomatch_action);
154             SetImportBatchItemAction($batch_id, $item_action);
155             $dbh->commit();
156         } else {
157             $matcher_failed = 1;
158         }
159     }
160
161     my $results = {
162         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     if ($runinbackground) {
173         $job->finish($results);
174     } else {
175             $template->param(staged => $num_valid,
176                              matched => $num_with_matches,
177                          num_items => $num_items,
178                          import_errors => scalar(@import_errors),
179                          total => $num_valid + scalar(@import_errors),
180                          checked_matches => $checked_matches,
181                          matcher_failed => $matcher_failed,
182                          matcher_code => $matcher_code,
183                          import_batch_id => $batch_id
184                         );
185     }
186
187 } else {
188     # initial form
189     if (C4::Context->preference("marcflavour") eq "UNIMARC") {
190         $template->param("UNIMARC" => 1);
191     }
192     my @matchers = C4::Matcher::GetMatcherList();
193     $template->param(available_matchers => \@matchers);
194
195     my @templates = GetModificationTemplates();
196     $template->param( MarcModificationTemplatesLoop => \@templates );
197
198 }
199
200 output_html_with_http_headers $input, $cookie, $template->output;
201
202 exit 0;
203
204 sub staging_progress_callback {
205     my $job = shift;
206     my $dbh = shift;
207     return sub {
208         my $progress = shift;
209         $job->progress($progress);
210     }
211 }
212
213 sub matching_progress_callback {
214     my $job = shift;
215     my $dbh = shift;
216     my $start_progress = $job->progress();
217     return sub {
218         my $progress = shift;
219         $job->progress($start_progress + $progress);
220     }
221 }