Bug 15542: Always display the patron's info the same way.
[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');
60 my $to_marc_plugin             = $input->param('to_marc_plugin');
61 my $marc_modification_template = $input->param('marc_modification_template_id');
62
63 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
64     {
65         template_name   => "tools/stage-marc-import.tt",
66         query           => $input,
67         type            => "intranet",
68         authnotrequired => 0,
69         flagsrequired   => { tools => 'stage_marc_import' },
70         debug           => 1,
71     }
72 );
73
74 $template->param(
75     SCRIPT_NAME => '/cgi-bin/koha/tools/stage-marc-import.pl',
76     uploadmarc  => $fileID,
77     record_type => $record_type,
78 );
79
80 my %cookies = parse CGI::Cookie($cookie);
81 my $sessionID = $cookies{'CGISESSID'}->value;
82 if ($completedJobID) {
83     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
84     my $results = $job->results();
85     $template->param(map { $_ => $results->{$_} } keys %{ $results });
86 } elsif ($fileID) {
87     my $upload = Koha::Upload->new->get({ id => $fileID, filehandle => 1 });
88     my $fh = $upload->{fh};
89     my $filename = $upload->{name}; # filename only, no path
90         my $marcrecord='';
91     $/ = "\035";
92         while (<$fh>) {
93         s/^\s+//;
94         s/\s+$//;
95                 $marcrecord.=$_;
96         }
97     $fh->close;
98
99     my $job = undef;
100     my $dbh;
101     if ($runinbackground) {
102         my $job_size = () = $marcrecord =~ /\035/g;
103         # if we're matching, job size is doubled
104         $job_size *= 2 if ($matcher_id ne "");
105         $job = C4::BackgroundJob->new($sessionID, $filename, '/cgi-bin/koha/tools/stage-marc-import.pl', $job_size);
106         my $jobID = $job->id();
107
108         # fork off
109         if (my $pid = fork) {
110             # parent
111             # return job ID as JSON
112             my $reply = CGI->new("");
113             print $reply->header(-type => 'text/html');
114             print '{"jobID":"' . $jobID . '"}';
115             exit 0;
116         } elsif (defined $pid) {
117             # child
118             # close STDOUT to signal to Apache that
119             # we're now running in the background
120             close STDOUT;
121             # close STDERR; # there is no good reason to close STDERR
122         } else {
123             # fork failed, so exit immediately
124             warn "fork failed while attempting to run tools/stage-marc-import.pl as a background job: $!";
125             exit 0;
126         }
127
128         # if we get here, we're a child that has detached
129         # itself from Apache
130
131     }
132
133     # New handle, as we're a child.
134     $dbh = C4::Context->dbh({new => 1});
135     $dbh->{AutoCommit} = 0;
136     # FIXME branch code
137     my ( $batch_id, $num_valid, $num_items, @import_errors ) =
138       BatchStageMarcRecords(
139         $record_type,    $encoding,
140         $marcrecord,     $filename,
141         $to_marc_plugin, $marc_modification_template,
142         $comments,       '',
143         $parse_items,    0,
144         50, staging_progress_callback( $job, $dbh )
145       );
146
147     my $num_with_matches = 0;
148     my $checked_matches = 0;
149     my $matcher_failed = 0;
150     my $matcher_code = "";
151     if ($matcher_id ne "") {
152         my $matcher = C4::Matcher->fetch($matcher_id);
153         if (defined $matcher) {
154             $checked_matches = 1;
155             $matcher_code = $matcher->code();
156             $num_with_matches =
157               BatchFindDuplicates( $batch_id, $matcher, 10, 50,
158                 matching_progress_callback( $job, $dbh ) );
159             SetImportBatchMatcher($batch_id, $matcher_id);
160             SetImportBatchOverlayAction($batch_id, $overlay_action);
161             SetImportBatchNoMatchAction($batch_id, $nomatch_action);
162             SetImportBatchItemAction($batch_id, $item_action);
163             $dbh->commit();
164         } else {
165             $matcher_failed = 1;
166         }
167     } else {
168         $dbh->commit();
169     }
170
171     my $results = {
172         staged          => $num_valid,
173         matched         => $num_with_matches,
174         num_items       => $num_items,
175         import_errors   => scalar(@import_errors),
176         total           => $num_valid + scalar(@import_errors),
177         checked_matches => $checked_matches,
178         matcher_failed  => $matcher_failed,
179         matcher_code    => $matcher_code,
180         import_batch_id => $batch_id
181     };
182     if ($runinbackground) {
183         $job->finish($results);
184     } else {
185             $template->param(staged => $num_valid,
186                              matched => $num_with_matches,
187                          num_items => $num_items,
188                          import_errors => scalar(@import_errors),
189                          total => $num_valid + scalar(@import_errors),
190                          checked_matches => $checked_matches,
191                          matcher_failed => $matcher_failed,
192                          matcher_code => $matcher_code,
193                          import_batch_id => $batch_id
194                         );
195     }
196
197 } else {
198     # initial form
199     if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
200         $template->param( "UNIMARC" => 1 );
201     }
202     my @matchers = C4::Matcher::GetMatcherList();
203     $template->param( available_matchers => \@matchers );
204
205     my @templates = GetModificationTemplates();
206     $template->param( MarcModificationTemplatesLoop => \@templates );
207
208     if ( C4::Context->preference('UseKohaPlugins') &&
209          C4::Context->config('enable_plugins') ) {
210
211         my @plugins = Koha::Plugins->new()->GetPlugins('to_marc');
212         $template->param( plugins => \@plugins );
213     }
214 }
215
216 output_html_with_http_headers $input, $cookie, $template->output;
217
218 exit 0;
219
220 sub staging_progress_callback {
221     my $job = shift;
222     my $dbh = shift;
223     return sub {
224         my $progress = shift;
225         $job->progress($progress);
226     }
227 }
228
229 sub matching_progress_callback {
230     my $job = shift;
231     my $dbh = shift;
232     my $start_progress = $job->progress();
233     return sub {
234         my $progress = shift;
235         $job->progress($start_progress + $progress);
236     }
237 }