Spelling correction per convention: cataloguing -> cataloging (Bug 3277)
[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::Output;
31 use C4::Biblio;
32 use C4::ImportBatch;
33 use C4::Matcher;
34 use C4::BackgroundJob;
35 use C4::Labels qw(add_batch);  
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') || 25; 
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 => {tools => 'manage_staged_marc'},
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 eq "create_labels") {
63         #create a batch of labels, then lose $op & $import_batch_id so we get back to import batch list.
64         my $label_batch_id = create_labelbatch_from_importbatch($import_batch_id);
65         $template->param( label_batch => $label_batch_id );
66         $op='';
67         $import_batch_id='';
68 }
69 if ($op) {
70     $template->param(script_name => $script_name, $op => 1);
71 } else {
72     $template->param(script_name => $script_name);
73 }
74
75 if ($op eq "") {
76     # displaying a list
77     if ($import_batch_id eq "") {
78         import_batches_list($template, $offset, $results_per_page);
79     } else {
80         import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
81     }
82 } elsif ($op eq "commit-batch") {
83     if ($completedJobID) {
84         add_saved_job_results_to_template($template, $completedJobID);
85     } else {
86         commit_batch($template, $import_batch_id);
87     }
88     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
89 } elsif ($op eq "revert-batch") {
90     if ($completedJobID) {
91         add_saved_job_results_to_template($template, $completedJobID);
92     } else {
93         revert_batch($template, $import_batch_id);
94     }
95     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
96 } elsif ($op eq "clean-batch") {
97     ;
98 } elsif ($op eq "redo-matching") {
99     my $new_matcher_id = $input->param('new_matcher_id');
100     my $current_matcher_id = $input->param('current_matcher_id');
101     my $overlay_action = $input->param('overlay_action');
102     my $nomatch_action = $input->param('nomatch_action');
103     my $item_action = $input->param('item_action');
104     redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id, 
105                   $overlay_action, $nomatch_action, $item_action);
106     import_biblios_list($template, $import_batch_id, $offset, $results_per_page);
107
108
109 output_html_with_http_headers $input, $cookie, $template->output;
110
111 exit 0;
112
113 sub redo_matching {
114     my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, $item_action) = @_;
115     my $rematch_failed = 0;
116     return if not defined $new_matcher_id and not defined $current_matcher_id;
117     my $old_overlay_action = GetImportBatchOverlayAction($import_batch_id);
118     my $old_nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
119     my $old_item_action = GetImportBatchItemAction($import_batch_id);
120     return if $new_matcher_id == $current_matcher_id and 
121               $old_overlay_action eq $overlay_action and 
122               $old_nomatch_action eq $nomatch_action and 
123               $old_item_action eq $item_action;
124  
125     if ($old_overlay_action ne $overlay_action) {
126         SetImportBatchOverlayAction($import_batch_id, $overlay_action);
127         $template->param('changed_overlay_action' => 1);
128     }
129     if ($old_nomatch_action ne $nomatch_action) {
130         SetImportBatchNoMatchAction($import_batch_id, $nomatch_action);
131         $template->param('changed_nomatch_action' => 1);
132     }
133     if ($old_item_action ne $item_action) {
134         SetImportBatchItemAction($import_batch_id, $item_action);
135         $template->param('changed_item_action' => 1);
136     }
137
138     if ($new_matcher_id == $current_matcher_id) {
139         return;
140     } 
141
142     my $num_with_matches = 0;
143     if (defined $new_matcher_id and $new_matcher_id ne "") {
144         my $matcher = C4::Matcher->fetch($new_matcher_id);
145         if (defined $matcher) {
146             $num_with_matches = BatchFindBibDuplicates($import_batch_id, $matcher);
147             SetImportBatchMatcher($import_batch_id, $new_matcher_id);
148         } else {
149             $rematch_failed = 1;
150         }
151     } else {
152         $num_with_matches = BatchFindBibDuplicates($import_batch_id, undef);
153         SetImportBatchMatcher($import_batch_id, undef);
154         SetImportBatchOverlayAction('create_new');
155     }
156     $template->param(rematch_failed => $rematch_failed);
157     $template->param(rematch_attempted => 1);
158     $template->param(num_with_matches => $num_with_matches);
159 }
160
161 sub create_labelbatch_from_importbatch {
162         my ($batch_id) = @_;
163         my @items = GetItemNumbersFromImportBatch($batch_id);
164         my $labelbatch = add_batch('labels',\@items);
165         return $labelbatch; 
166 }
167
168 sub import_batches_list {
169     my ($template, $offset, $results_per_page) = @_;
170     my $batches = GetImportBatchRangeDesc($offset, $results_per_page);
171
172     my @list = ();
173     foreach my $batch (@$batches) {
174         push @list, {
175             import_batch_id => $batch->{'import_batch_id'},
176             num_biblios => $batch->{'num_biblios'},
177             num_items => $batch->{'num_items'},
178             upload_timestamp => $batch->{'upload_timestamp'},
179             import_status => $batch->{'import_status'},
180             file_name => $batch->{'file_name'},
181             comments => $batch->{'comments'}
182         };
183     }
184     $template->param(batch_list => \@list); 
185     my $num_batches = GetNumberOfNonZ3950ImportBatches();
186     add_page_numbers($template, $offset, $results_per_page, $num_batches);
187     $template->param(offset => $offset);
188     $template->param(range_top => $offset + $results_per_page - 1);
189     $template->param(num_results => $num_batches);
190     $template->param(results_per_page => $results_per_page);
191
192 }
193
194 sub commit_batch {
195     my ($template, $import_batch_id) = @_;
196
197     my $job = undef;
198     $dbh->{AutoCommit} = 0;
199     my $callback = sub {};
200     if ($runinbackground) {
201         $job = put_in_background($import_batch_id);
202         $callback = progress_callback($job, $dbh);
203     }
204     my ($num_added, $num_updated, $num_items_added, $num_items_errored, $num_ignored) = 
205         BatchCommitBibRecords($import_batch_id, 50, $callback);
206     $dbh->commit();
207
208     my $results = {
209         did_commit => 1,
210         num_added => $num_added,
211         num_updated => $num_updated,
212         num_items_added => $num_items_added,
213         num_items_errored => $num_items_errored,
214         num_ignored => $num_ignored
215     };
216     if ($runinbackground) {
217         $job->finish($results);
218     } else {
219         add_results_to_template($template, $results);
220     }
221 }
222
223 sub revert_batch {
224     my ($template, $import_batch_id) = @_;
225
226     $dbh->{AutoCommit} = 0;
227     my $job = undef;
228     my $callback = sub {};
229     if ($runinbackground) {
230         $job = put_in_background($import_batch_id);
231         $callback = progress_callback($job, $dbh);
232     }
233     my ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored) = 
234         BatchRevertBibRecords($import_batch_id, 50, $callback);
235     $dbh->commit();
236
237     my $results = {
238         did_revert => 1,
239         num_deleted => $num_deleted,
240         num_items_deleted => $num_items_deleted,
241         num_errors => $num_errors,
242         num_reverted => $num_reverted,
243         num_ignored => $num_ignored,
244     };
245     if ($runinbackground) {
246         $job->finish($results);
247     } else {
248         add_results_to_template($template, $results);
249     }
250 }
251
252 sub put_in_background {
253     my $import_batch_id = shift;
254
255     my $batch = GetImportBatch($import_batch_id);
256     my $job = C4::BackgroundJob->new($sessionID, $batch->{'file_name'}, $ENV{'SCRIPT_NAME'}, $batch->{'num_biblios'});
257     my $jobID = $job->id();
258
259     # fork off
260     if (my $pid = fork) {
261         # parent
262         # return job ID as JSON
263
264         # prevent parent exiting from
265         # destroying the kid's database handle
266         # FIXME: according to DBI doc, this may not work for Oracle
267         $dbh->{InactiveDestroy}  = 1;
268
269         my $reply = CGI->new("");
270         print $reply->header(-type => 'text/html');
271         print "{ jobID: '$jobID' }";
272         exit 0;
273     } elsif (defined $pid) {
274         # child
275         # close STDOUT to signal to Apache that
276         # we're now running in the background
277         close STDOUT;
278         close STDERR;
279     } else {
280         # fork failed, so exit immediately
281         warn "fork failed while attempting to run $ENV{'SCRIPT_NAME'} as a background job";
282         exit 0;
283     }
284     return $job;
285 }
286
287 sub progress_callback {
288     my $job = shift;
289     my $dbh = shift;
290     return sub {
291         my $progress = shift;
292         $job->progress($progress);
293         $dbh->commit();
294     }
295 }
296
297 sub add_results_to_template {
298     my $template = shift;
299     my $results = shift;
300     $template->param(map { $_ => $results->{$_} } keys %{ $results });
301 }
302
303 sub add_saved_job_results_to_template {
304     my $template = shift;
305     my $completedJobID = shift;
306     my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
307     my $results = $job->results();
308     add_results_to_template($template, $results);
309 }
310
311 sub import_biblios_list {
312     my ($template, $import_batch_id, $offset, $results_per_page) = @_;
313
314     my $batch = GetImportBatch($import_batch_id);
315     my $biblios = GetImportBibliosRange($import_batch_id, $offset, $results_per_page);
316     my @list = ();
317     foreach my $biblio (@$biblios) {
318         my $citation = $biblio->{'title'};
319         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
320         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
321         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
322         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
323         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
324         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
325         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
326         push @list,
327           { import_record_id         => $biblio->{'import_record_id'},
328             final_match_biblionumber => $biblio->{'matched_biblionumber'},
329             citation                 => $citation,
330             status                   => $biblio->{'status'},
331             record_sequence          => $biblio->{'record_sequence'},
332             overlay_status           => $biblio->{'overlay_status'},
333             match_biblionumber       => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
334             match_citation           => $#$match > -1 ? $match->[0]->{'title'} . ' ' . $match->[0]->{'author'} : '',
335             match_score              => $#$match > -1 ? $match->[0]->{'score'} : 0,
336           };
337     }
338     my $num_biblios = $batch->{'num_biblios'};
339     $template->param(biblio_list => \@list); 
340     add_page_numbers($template, $offset, $results_per_page, $num_biblios);
341     $template->param(offset => $offset);
342     $template->param(range_top => $offset + $results_per_page - 1);
343     $template->param(num_results => $num_biblios);
344     $template->param(results_per_page => $results_per_page);
345     $template->param(import_batch_id => $import_batch_id);
346     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
347     $template->param("overlay_action_${overlay_action}" => 1);
348     $template->param(overlay_action => $overlay_action);
349     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
350     $template->param("nomatch_action_${nomatch_action}" => 1);
351     $template->param(nomatch_action => $nomatch_action);
352     my $item_action = GetImportBatchItemAction($import_batch_id);
353     $template->param("item_action_${item_action}" => 1);
354     $template->param(item_action => $item_action);
355     batch_info($template, $batch);
356     
357 }
358
359 sub batch_info {
360     my ($template, $batch) = @_;
361     $template->param(batch_info => 1);
362     $template->param(file_name => $batch->{'file_name'});
363     $template->param(comments => $batch->{'comments'});
364     $template->param(import_status => $batch->{'import_status'});
365     $template->param(upload_timestamp => $batch->{'upload_timestamp'});
366     $template->param(num_biblios => $batch->{'num_biblios'});
367     $template->param(num_items => $batch->{'num_biblios'});
368     if ($batch->{'num_biblios'} > 0) {
369         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
370             $template->param(can_commit => 1);
371         }
372         if ($batch->{'import_status'} eq 'imported') {
373             $template->param(can_revert => 1);
374         }
375     }
376     if (defined $batch->{'matcher_id'}) {
377         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
378         if (defined $matcher) {
379             $template->param('current_matcher_id' => $batch->{'matcher_id'});
380             $template->param('current_matcher_code' => $matcher->code());
381             $template->param('current_matcher_description' => $matcher->description());
382         }
383     }
384     add_matcher_list($batch->{'matcher_id'});
385 }
386
387 sub add_matcher_list {
388     my $current_matcher_id = shift;
389     my @matchers = C4::Matcher::GetMatcherList();
390     if (defined $current_matcher_id) {
391         for (my $i = 0; $i <= $#matchers; $i++) {
392             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
393                 $matchers[$i]->{'selected'} = 1;
394             }
395         }
396     }
397     $template->param(available_matchers => \@matchers);
398 }
399
400 sub add_page_numbers {
401     my ($template, $offset, $results_per_page, $total_results) = @_;
402     my $max_pages = POSIX::ceil($total_results / $results_per_page);
403     return if $max_pages < 2;
404     my $current_page = int($offset / $results_per_page) + 1;
405     my @pages = ();
406     for (my $i = 1; $i <= $max_pages; $i++) {
407         push @pages, {
408             page_number => $i,
409             current_page => ($current_page == $i) ? 1 : 0,
410             offset => ($i - 1) * $results_per_page
411         }
412     }
413     $template->param(pages => \@pages);
414 }
415