Bug 12412: Add ability for plugins to convert arbitrary files to MARC from record...
[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 C4::UploadedFile;
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 => $ENV{'SCRIPT_NAME'},
76     uploadmarc  => $fileID
77 );
78
79 my %cookies = parse CGI::Cookie($cookie);
80 my $sessionID = $cookies{'CGISESSID'}->value;
81 if ($completedJobID) {
82     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
83     my $results = $job->results();
84     $template->param(map { $_ => $results->{$_} } keys %{ $results });
85 } elsif ($fileID) {
86     my $uploaded_file = C4::UploadedFile->fetch($sessionID, $fileID);
87     my $fh = $uploaded_file->fh();
88         my $marcrecord='';
89     $/ = "\035";
90         while (<$fh>) {
91         s/^\s+//;
92         s/\s+$//;
93                 $marcrecord.=$_;
94         }
95
96     my $filename = $uploaded_file->name();
97     my $job = undef;
98     my $dbh;
99     if ($runinbackground) {
100         my $job_size = () = $marcrecord =~ /\035/g;
101         # if we're matching, job size is doubled
102         $job_size *= 2 if ($matcher_id ne "");
103         $job = C4::BackgroundJob->new($sessionID, $filename, $ENV{'SCRIPT_NAME'}, $job_size);
104         my $jobID = $job->id();
105
106         # fork off
107         if (my $pid = fork) {
108             # parent
109             # return job ID as JSON
110             my $reply = CGI->new("");
111             print $reply->header(-type => 'text/html');
112             print '{"jobID":"' . $jobID . '"}';
113             exit 0;
114         } elsif (defined $pid) {
115             # child
116             # close STDOUT to signal to Apache that
117             # we're now running in the background
118             close STDOUT;
119             # close STDERR; # there is no good reason to close STDERR
120         } else {
121             # fork failed, so exit immediately
122             warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job: $!";
123             exit 0;
124         }
125
126         # if we get here, we're a child that has detached
127         # itself from Apache
128
129     }
130
131     # New handle, as we're a child.
132     $dbh = C4::Context->dbh({new => 1});
133     $dbh->{AutoCommit} = 0;
134     # FIXME branch code
135     my ( $batch_id, $num_valid, $num_items, @import_errors ) =
136       BatchStageMarcRecords(
137         $record_type,    $encoding,
138         $marcrecord,     $filename,
139         $to_marc_plugin, $marc_modification_template,
140         $comments,       '',
141         $parse_items,    0,
142         50, staging_progress_callback( $job, $dbh )
143       );
144
145     my $num_with_matches = 0;
146     my $checked_matches = 0;
147     my $matcher_failed = 0;
148     my $matcher_code = "";
149     if ($matcher_id ne "") {
150         my $matcher = C4::Matcher->fetch($matcher_id);
151         if (defined $matcher) {
152             $checked_matches = 1;
153             $matcher_code = $matcher->code();
154             $num_with_matches =
155               BatchFindDuplicates( $batch_id, $matcher, 10, 50,
156                 matching_progress_callback( $job, $dbh ) );
157             SetImportBatchMatcher($batch_id, $matcher_id);
158             SetImportBatchOverlayAction($batch_id, $overlay_action);
159             SetImportBatchNoMatchAction($batch_id, $nomatch_action);
160             SetImportBatchItemAction($batch_id, $item_action);
161             $dbh->commit();
162         } else {
163             $matcher_failed = 1;
164         }
165     } else {
166         $dbh->commit();
167     }
168
169     my $results = {
170         staged          => $num_valid,
171         matched         => $num_with_matches,
172         num_items       => $num_items,
173         import_errors   => scalar(@import_errors),
174         total           => $num_valid + scalar(@import_errors),
175         checked_matches => $checked_matches,
176         matcher_failed  => $matcher_failed,
177         matcher_code    => $matcher_code,
178         import_batch_id => $batch_id
179     };
180     if ($runinbackground) {
181         $job->finish($results);
182     } else {
183             $template->param(staged => $num_valid,
184                              matched => $num_with_matches,
185                          num_items => $num_items,
186                          import_errors => scalar(@import_errors),
187                          total => $num_valid + scalar(@import_errors),
188                          checked_matches => $checked_matches,
189                          matcher_failed => $matcher_failed,
190                          matcher_code => $matcher_code,
191                          import_batch_id => $batch_id
192                         );
193     }
194
195 } else {
196     # initial form
197     if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) {
198         $template->param( "UNIMARC" => 1 );
199     }
200     my @matchers = C4::Matcher::GetMatcherList();
201     $template->param( available_matchers => \@matchers );
202
203     my @templates = GetModificationTemplates();
204     $template->param( MarcModificationTemplatesLoop => \@templates );
205
206     my @plugins = Koha::Plugins->new()->GetPlugins('to_marc');
207     $template->param( plugins => \@plugins );
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 }