Completing adding patronimage upload form to patron details screen.
[koha.git] / tools / picture-upload.pl
1 #!/usr/bin/perl
2 #
3 #
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18 #
19 #
20 #
21
22 use File::Temp;
23 use File::Copy;
24 use CGI;
25 use C4::Context;
26 use C4::Auth;
27 use C4::Output;
28 use C4::Members;
29 #use Data::Dumper;
30
31 my $DEBUG = ($ENV{DEBUG}) ? 1 : 0;
32
33 my $input = new CGI;
34
35 my ($template, $loggedinuser, $cookie)
36         = get_template_and_user({template_name => "tools/picture-upload.tmpl",
37                                         query => $input,
38                                         type => "intranet",
39                                         authnotrequired => 0,
40                                         flagsrequired => {management => 1, tools => 1},
41                                         debug => 0,
42                                         });
43
44 my $filetype            = $input->param('filetype');
45 my $cardnumber          = $input->param('cardnumber');
46 my $uploadfilename      = $input->param('uploadfile');
47 my $uploadfile          = $input->upload('uploadfile');
48 my $borrowernumber      = $input->param('borrowernumber');
49
50 #FIXME: This code is really in the rough. The variables need to be re-scoped as the two subs depend on global vars to operate.
51 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
52 #       coded. -fbcit
53
54 warn "Params are: filetype=$filetype, cardnumber=$cardnumber, uploadfile=$uploadfilename" if $DEBUG;
55
56 =head1 NAME
57
58 picture-upload.p. - Script for handling uploading of both single and bulk patronimages and importing them into the database.
59
60 =head1 SYNOPSIS
61
62 picture-upload.pl
63
64 =head1 DESCRIPTION
65
66 THis script is called and presents the user with an interface allowing him/her to upload a single patron image or bulk patron images via a zip file.
67
68 =cut
69
70
71
72 my ( $total, $handled, @counts, $tempfile, $tfh );
73
74 if ( $uploadfile ) {
75     my $dirname = File::Temp::tempdir( CLEANUP => 1);
76     warn "dirname = $dirname" if $DEBUG;
77     my $filesuffix = $1 if $uploadfilename =~ m/(\..+)$/i;
78     ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
79     warn "tempfile = $tempfile" if $DEBUG;
80     my ( @directories, $errors );
81
82     $errors{'NOTZIP'} = 1 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
83     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
84     $errors{'EMPTYUPLOAD'} = 1 unless ( length( $uploadfile ) > 0 );
85
86     if ( %errors ) {
87         $template->param( ERRORS => [ \%errors ] );
88     } else {
89         while ( <$uploadfile> ) {
90             print $tfh $_;
91         }
92
93         close $tfh;
94         if ( $filetype eq 'zip' ) {
95             unless (system("unzip $tempfile -d $dirname") == 0) {
96                 $errors{'UZIPFAIL'} = $uploadfilename;
97                 $template->param( ERRORS => [ \%errors ] );
98                 output_html_with_http_headers $input, $cookie, $template->output;   # This error is fatal to the import, so bail out here
99                 exit;
100             }
101             push @directories, "$dirname";
102             foreach $recursive_dir ( @directories ) {
103                 opendir $dir, $recursive_dir;
104                 while ( my $entry = readdir $dir ) {
105                 push @directories, "$recursive_dir/$entry" if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
106                 warn "$recursive_dir/$entry" if $DEBUG;
107                 }   
108                 closedir $dir;
109             }       
110             my $results;
111             foreach my $dir ( @directories ) {
112                 $results = handle_dir( $dir, $filesuffix );
113                 $handled++ if $results == 1;
114             }
115             $total = scalar @directories;
116         } else {       #if ($filetype eq 'zip' )
117             $result = handle_dir( $dirname, $filesuffix );
118             $handled = 1;
119             $total = 1;
120         }
121
122         if ( %$results || %errors ) {
123             $template->param( ERRORS => [ \%$results ] );
124         } else {
125             warn "Total files processed: $total" if $DEBUG;
126             warn "Errors in \$errors." if $errors;
127             $template->param(
128                  TOTAL => $total,
129                  HANDLED => $handled,
130                  COUNTS => \@counts,
131                  TCOUNTS => scalar(@counts),
132             );
133         }   
134     }
135 } else {
136         $template->param(cardnumber => $cardnumber );
137         $template->param(filetype => $filetype );
138 }
139
140 if ( $borrowernumber ) {
141     my $urlbase = $input->url(-base => 1 -rewrite => 1);
142     print $input->redirect ("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
143 } else {
144     output_html_with_http_headers $input, $cookie, $template->output;
145 }
146
147 sub handle_dir {
148     my ( $dir, $suffix ) = @_;
149     my $source;
150     warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix" if $DEBUG;
151     if ($suffix =~ m/zip/i) {     # If we were sent a zip file, process any included data/idlink.txt files 
152         my ( $file, $filename, $cardnumber );
153         warn "Passed a zip file." if $DEBUG;
154         opendir my $dirhandle, $dir;
155         while ( my $filename = readdir $dirhandle ) {
156             $file = "$dir/$filename" if ($filename =~ m/datalink\.txt/i || $filename =~ m/idlink\.txt/i);
157         }
158         unless (open (FILE, $file)) { 
159                 warn "Opening $dir/$file failed!";
160                 $errors{'OPNLINK'} = $file;
161                 return $errors; # This error is fatal to the import of this directory contents, so bail and return the error to the caller
162         };
163
164         while (my $line = <FILE>) {
165             warn "Reading contents of $file" if $DEBUG;
166             chomp $line;
167             warn "Examining line: $line" if $DEBUG;
168             my $delim = ($line =~ /\t/) ? "\t" : ($line =~ /,/) ? "," : "";
169             warn "Delimeter is \'$delim\'" if $DEBUG;
170             unless ( $delim eq "," || $delim eq "\t" ) {
171                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
172                 $errors{'DELERR'} = 1;      # This error is fatal to the import of this directory contents, so bail and return the error to the caller
173                 return $errors;
174             }
175             ($cardnumber, $filename) = split $delim, $line;
176             $cardnumber =~ s/[\"\r\n]//g;  # remove offensive characters
177             $filename   =~ s/[\"\r\n\s]//g;
178             warn "Cardnumber: $cardnumber Filename: $filename" if $DEBUG;
179             $source = "$dir/$filename";
180             %counts = handle_file($cardnumber, $source, %counts);
181         }
182         close FILE;
183         closedir ($dirhandle);
184     } else {
185         $source = $tempfile;
186         %counts = handle_file($cardnumber, $source, %counts);
187     }
188 push @counts, \%counts;
189 return 1;
190 }
191
192 sub handle_file {
193     my ($cardnumber, $source, %count) = @_;
194     warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source" if $DEBUG;
195     my $mimemap = {
196         "gif"   => "image/gif",
197         "jpg"   => "image/jpeg",
198         "jpeg"  => "image/jpeg",
199         "png"   => "image/png"
200     };
201     $count{filenames} = () if !$count{filenames};
202     $count{source} = $source if !$count{source};
203     if ($cardnumber && $source) {     # Now process any imagefiles
204         my %filerrors;
205         warn "Source: $source" if $DEBUG;
206         if (open (IMG, "$source")) {
207             #binmode (IMG); # Not sure if we need this or not -fbcit
208             my $imgfile;
209             while (<IMG>) {
210                 $imgfile .= $_;
211             }
212             if ($filetype eq 'image') {
213                 $filename = $uploadfilename;
214             } else {
215                 $filename = $1 if ($source =~ /\/([^\/]+)$/);
216             }
217             warn "\$filename=$filename";
218             my $mimetype = $mimemap->{lc ($1)} if $filename =~ m/\.([^.]+)$/i;
219             warn "$filename is mimetype \"$mimetype\"" if $DEBUG;
220             my $dberror = PutPatronImage($cardnumber,$mimetype, $imgfile) if $mimetype;
221             close (IMG);
222             if ( !$dberror && $mimetype ) { # Errors from here on are fatal only to the import of a particular image, so don't bail, just note the error and keep going
223                 $count{count}++;
224                 push @{ $count{filenames} }, { source => $filename, cardnumber => $cardnumber };
225             } elsif ( $dberror ) {
226                 warn "Database returned error: $dberror";
227                 ($dberror =~ /patronimage_fk1/) ? $filerrors{'IMGEXISTS'} = 1 : $filerrors{'DBERR'} = 1;
228                 push my @filerrors, \%filerrors;
229                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
230                 $template->param( ERRORS => 1 );
231             } elsif ( !$mimetype ) {
232                 warn "Unable to determine mime type of $filename. Please verify mimetype and add to \%mimemap if necessary.";
233                 $filerrors{'MIMERR'} = 1;
234                 push my @filerrors, \%filerrors;
235                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
236                 $template->param( ERRORS => 1 );
237             }
238         } else {
239             warn "Opening $dir/$filename failed!";
240             $filerrors{'OPNERR'} = 1;
241             push my @filerrors, \%filerrors;
242             push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
243             $template->param( ERRORS => 1 );
244         }
245     } else {    # The need for this seems a bit unlikely, however, to maximize error trapping it is included
246         warn "Missing " . ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
247         $filerrors{'CRDFIL'} = ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename")); 
248         push my @filerrors, \%filerrors;
249         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
250         $template->param( ERRORS => 1 );
251     }
252     return %count;
253 }
254
255 =back
256
257 =head1 AUTHORS
258
259 Original contributor(s) undocumented
260
261 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
262
263 =cut