start of BIB change -- introduce C4::Items
[koha.git] / tools / manage-marc-import.pl
1 #!/usr/bin/perl
2
3 # Copyright (C) 2007 LibLime
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21
22 # standard or CPAN modules used
23 use CGI;
24 use CGI::Cookie;
25 use MARC::File::USMARC;
26
27 # Koha modules used
28 use C4::Context;
29 use C4::Auth;
30 use C4::Input;
31 use C4::Output;
32 use C4::Biblio;
33 use C4::ImportBatch;
34 use C4::Matcher;
35 use C4::BackgroundJob;
36
37 my $script_name = "/cgi-bin/koha/tools/manage-marc-import.pl";
38
39 my $input = new CGI;
40 my $op = $input->param('op');
41 my $completedJobID = $input->param('completedJobID');
42 my $runinbackground = $input->param('runinbackground');
43 my $import_batch_id = $input->param('import_batch_id');
44
45 # record list displays
46 my $offset = $input->param('offset') || 0;
47 my $results_per_page = $input->param('results_per_page') || 10; 
48
49 my ($template, $loggedinuser, $cookie)
50     = get_template_and_user({template_name => "tools/manage-marc-import.tmpl",
51                  query => $input,
52                  type => "intranet",
53                  authnotrequired => 0,
54                  flagsrequired => {parameters => 1},
55                  debug => 1,
56                  });
57
58 my %cookies = parse CGI::Cookie($cookie);
59 my $sessionID = $cookies{'CGISESSID'}->value;
60 my $dbh = C4::Context->dbh;
61
62 if ($op) {
63     $template->param(script_name => $script_name, $op => 1);
64 } else {
65     $template->param(script_name => $script_name);
66 }
67
68 if ($op eq "") {
69     # displaying a list
70     if ($import_batch_id eq "") {
71         import_batches_list($template, $offset, $results_per_page);
72     } else {
73         import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
74     }
75 } elsif ($op eq "commit-batch") {
76     if ($completedJobID) {
77         add_saved_job_results_to_template($template, $completedJobID);
78     } else {
79         commit_batch($template, $import_batch_id);
80     }
81     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
82 } elsif ($op eq "revert-batch") {
83     if ($completedJobID) {
84         add_saved_job_results_to_template($template, $completedJobID);
85     } else {
86         revert_batch($template, $import_batch_id);
87     }
88     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
89 } elsif ($op eq "clean-batch") {
90     ;
91 } elsif ($op eq "redo-matching") {
92     my $new_matcher_id = $input->param('new_matcher_id');
93     my $current_matcher_id = $input->param('current_matcher_id');
94     redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id);
95     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
96 }
97
98 output_html_with_http_headers $input, $cookie, $template->output;
99
100 exit 0;
101
102 sub redo_matching {
103     my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id) = @_;
104     my $rematch_failed = 0;
105     return if not defined $new_matcher_id and not defined $current_matcher_id;
106     return if $new_matcher_id == $current_matcher_id;
107     my $num_with_matches = 0;
108     if (defined $new_matcher_id and $new_matcher_id ne "") {
109         my $matcher = C4::Matcher->fetch($new_matcher_id);
110         if (defined $matcher) {
111             $num_with_matches = BatchFindBibDuplicates($import_batch_id, $matcher);
112             SetImportBatchMatcher($import_batch_id, $new_matcher_id);
113         } else {
114             $rematch_failed = 1;
115         }
116     } else {
117         $num_with_matches = BatchFindBibDuplicates($import_batch_id, undef);
118          SetImportBatchMatcher($import_batch_id, undef);
119     }
120     $template->param(rematch_failed => $rematch_failed);
121     $template->param(rematch_attempted => 1);
122     $template->param(num_with_matches => $num_with_matches);
123 }
124
125 sub import_batches_list {
126     my ($template, $offset, $results_per_page) = @_;
127     my $batches = GetImportBatchRangeDesc($offset, $results_per_page);
128
129     my @list = ();
130     foreach my $batch (@$batches) {
131         push @list, {
132             import_batch_id => $batch->{'import_batch_id'},
133             num_biblios => $batch->{'num_biblios'},
134             num_items => $batch->{'num_items'},
135             upload_timestamp => $batch->{'upload_timestamp'},
136             import_status => $batch->{'import_status'},
137             file_name => $batch->{'file_name'},
138             comments => $batch->{'comments'}
139         };
140     }
141     $template->param(batch_list => \@list); 
142     my $num_batches = GetNumberOfNonZ3950ImportBatches();
143     add_page_numbers($template, $offset, $results_per_page, $num_batches);
144     $template->param(offset => $offset);
145     $template->param(range_top => $offset + $results_per_page - 1);
146     $template->param(num_results => $num_batches);
147     $template->param(results_per_page => $results_per_page);
148
149 }
150
151 sub commit_batch {
152     my ($template, $import_batch_id) = @_;
153
154     my $job = undef;
155     my $callback = sub {};
156     if ($runinbackground) {
157         $job = put_in_background($import_batch_id);
158         $callback = progress_callback($job);
159     }
160     my ($num_added, $num_updated, $num_items_added, $num_items_errored, $num_ignored) = 
161         BatchCommitBibRecords($import_batch_id, 50, $callback);
162
163     my $results = {
164         did_commit => 1,
165         num_added => $num_added,
166         num_updated => $num_updated,
167         num_items_added => $num_items_added,
168         num_items_errored => $num_items_errored,
169         num_ignored => $num_ignored
170     };
171     if ($runinbackground) {
172         $job->finish($results);
173     } else {
174         add_results_to_template($template, $results);
175     }
176 }
177
178 sub revert_batch {
179     my ($template, $import_batch_id) = @_;
180
181     my $job = undef;
182     my $callback = sub {};
183     if ($runinbackground) {
184         $job = put_in_background($import_batch_id);
185         $callback = progress_callback($job);
186     }
187     my ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored) = 
188         BatchRevertBibRecords($import_batch_id, 50, $callback);
189
190     my $results = {
191         did_revert => 1,
192         num_deleted => $num_deleted,
193         num_items_deleted => $num_items_deleted,
194         num_errors => $num_errors,
195         num_reverted => $num_reverted,
196         num_ignored => $num_ignored,
197     };
198     if ($runinbackground) {
199         $job->finish($results);
200     } else {
201         add_results_to_template($template, $results);
202     }
203 }
204
205 sub put_in_background {
206     my $import_batch_id = shift;
207
208     my $batch = GetImportBatch($import_batch_id);
209     my $job = C4::BackgroundJob->new($sessionID, $batch->{'file_name'}, $ENV{'SCRIPT_NAME'}, $batch->{'num_biblios'});
210     my $jobID = $job->id();
211
212     # fork off
213     if (my $pid = fork) {
214         # parent
215         # return job ID as JSON
216
217         # prevent parent exiting from
218         # destroying the kid's database handle
219         # FIXME: according to DBI doc, this may not work for Oracle
220         $dbh->{InactiveDestroy}  = 1;
221
222         my $reply = CGI->new("");
223         print $reply->header(-type => 'text/html');
224         print "{ jobID: '$jobID' }";
225         exit 0;
226     } elsif (defined $pid) {
227         # child
228         # close STDOUT to signal to Apache that
229         # we're now running in the background
230         close STDOUT;
231         close STDERR;
232     } else {
233         # fork failed, so exit immediately
234         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
235         exit 0;
236     }
237     return $job;
238 }
239
240 sub progress_callback {
241     my $job = shift;
242     return sub {
243         my $progress = shift;
244         $job->progress($progress);
245     }
246 }
247
248 sub add_results_to_template {
249     my $template = shift;
250     my $results = shift;
251     $template->param(map { $_ => $results->{$_} } keys %{ $results });
252 }
253
254 sub add_saved_job_results_to_template {
255     my $template = shift;
256     my $completedJobID = shift;
257     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
258     my $results = $job->results();
259     add_results_to_template($template, $results);
260 }
261
262 sub import_biblios_list {
263     my ($template, $import_batch_id, $offset, $results_per_page) = @_;
264
265     my $batch = GetImportBatch($import_batch_id);
266     my $biblios = GetImportBibliosRange($import_batch_id, $offset, $results_per_page);
267     my @list = ();
268     foreach my $biblio (@$biblios) {
269         my $citation = $biblio->{'title'};
270         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
271         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
272         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
273         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
274         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
275         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
276         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
277         push @list, {
278             import_record_id => $biblio->{'import_record_id'},
279             citation => $citation,
280             status => $biblio->{'status'},
281             record_sequence => $biblio->{'record_sequence'},
282             overlay_status => $biblio->{'overlay_status'},
283             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
284             match_citation => $#$match > -1 ? $match->[0]->{'title'} . ' ' . $match->[0]->{'author'} : '',
285             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
286         };
287     }
288     my $num_biblios = $batch->{'num_biblios'};
289     $template->param(biblio_list => \@list); 
290     add_page_numbers($template, $offset, $results_per_page, $num_biblios);
291     $template->param(offset => $offset);
292     $template->param(range_top => $offset + $results_per_page - 1);
293     $template->param(num_results => $num_biblios);
294     $template->param(results_per_page => $results_per_page);
295     $template->param(import_batch_id => $import_batch_id);
296     batch_info($template, $batch);
297     
298 }
299
300 sub batch_info {
301     my ($template, $batch) = @_;
302     $template->param(batch_info => 1);
303     $template->param(file_name => $batch->{'file_name'});
304     $template->param(comments => $batch->{'comments'});
305     $template->param(import_status => $batch->{'import_status'});
306     $template->param(upload_timestamp => $batch->{'upload_timestamp'});
307     $template->param(num_biblios => $batch->{'num_biblios'});
308     $template->param(num_items => $batch->{'num_biblios'});
309     if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
310         $template->param(can_commit => 1);
311     }
312     if ($batch->{'import_status'} eq 'imported') {
313         $template->param(can_revert => 1);
314     }
315     if (defined $batch->{'matcher_id'}) {
316         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
317         if (defined $matcher) {
318             $template->param('current_matcher_id' => $batch->{'matcher_id'});
319             $template->param('current_matcher_code' => $matcher->code());
320             $template->param('current_matcher_description' => $matcher->description());
321         }
322     }
323     add_matcher_list($batch->{'matcher_id'});
324 }
325
326 sub add_matcher_list {
327     my $current_matcher_id = shift;
328     my @matchers = C4::Matcher::GetMatcherList();
329     if (defined $current_matcher_id) {
330         for (my $i = 0; $i <= $#matchers; $i++) {
331             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
332                 $matchers[$i]->{'selected'} = 1;
333             }
334         }
335     }
336     $template->param(available_matchers => \@matchers);
337 }
338
339 sub add_page_numbers {
340     my ($template, $offset, $results_per_page, $total_results) = @_;
341     my $max_pages = POSIX::ceil($total_results / $results_per_page);
342     return if $max_pages < 2;
343     my $current_page = int($offset / $results_per_page) + 1;
344     my @pages = ();
345     for (my $i = 1; $i <= $max_pages; $i++) {
346         push @pages, {
347             page_number => $i,
348             current_page => ($current_page == $i) ? 1 : 0,
349             offset => ($i - 1) * $results_per_page
350         }
351     }
352     $template->param(pages => \@pages);
353 }
354