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