Adding Update/Delete functions to patron image management on Details page
[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 my $op                  = $input->param('op');
50
51 #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.
52 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
53 #       coded. -fbcit
54
55 warn "Params are: filetype=$filetype, cardnumber=$cardnumber, uploadfile=$uploadfilename" if $DEBUG;
56
57 =head1 NAME
58
59 picture-upload.p. - Script for handling uploading of both single and bulk patronimages and importing them into the database.
60
61 =head1 SYNOPSIS
62
63 picture-upload.pl
64
65 =head1 DESCRIPTION
66
67 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.
68
69 =cut
70
71 warn "Operation requested: $op" if $DEBUG;
72
73 my ( $total, $handled, @counts, $tempfile, $tfh );
74
75 if ( ($op eq 'Upload') && $uploadfile ) {       # Case is important in these operational values as the template must use case to be visually pleasing!
76     my $dirname = File::Temp::tempdir( CLEANUP => 1);
77     warn "dirname = $dirname" if $DEBUG;
78     my $filesuffix = $1 if $uploadfilename =~ m/(\..+)$/i;
79     ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
80     warn "tempfile = $tempfile" if $DEBUG;
81     my ( @directories, $errors );
82
83     $errors{'NOTZIP'} = 1 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
84     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
85     $errors{'EMPTYUPLOAD'} = 1 unless ( length( $uploadfile ) > 0 );
86
87     if ( %errors ) {
88         $template->param( ERRORS => [ \%errors ] );
89     } else {
90         while ( <$uploadfile> ) {
91             print $tfh $_;
92         }
93
94         close $tfh;
95         if ( $filetype eq 'zip' ) {
96             unless (system("unzip $tempfile -d $dirname") == 0) {
97                 $errors{'UZIPFAIL'} = $uploadfilename;
98                 $template->param( ERRORS => [ \%errors ] );
99                 output_html_with_http_headers $input, $cookie, $template->output;   # This error is fatal to the import, so bail out here
100                 exit;
101             }
102             push @directories, "$dirname";
103             foreach $recursive_dir ( @directories ) {
104                 opendir $dir, $recursive_dir;
105                 while ( my $entry = readdir $dir ) {
106                 push @directories, "$recursive_dir/$entry" if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
107                 warn "$recursive_dir/$entry" if $DEBUG;
108                 }   
109                 closedir $dir;
110             }       
111             my $results;
112             foreach my $dir ( @directories ) {
113                 $results = handle_dir( $dir, $filesuffix );
114                 $handled++ if $results == 1;
115             }
116             $total = scalar @directories;
117         } else {       #if ($filetype eq 'zip' )
118             $result = handle_dir( $dirname, $filesuffix );
119             $handled = 1;
120             $total = 1;
121         }
122
123         if ( %$results || %errors ) {
124             $template->param( ERRORS => [ \%$results ] );
125         } else {
126             warn "Total files processed: $total" if $DEBUG;
127             warn "Errors in \$errors." if $errors;
128             $template->param(
129                  TOTAL => $total,
130                  HANDLED => $handled,
131                  COUNTS => \@counts,
132                  TCOUNTS => scalar(@counts),
133             );
134         }   
135     }
136 } elsif ( ($op eq 'Upload') && !$uploadfile ) {
137     warn "Problem uploading file or no file uploaded.";
138     $template->param(cardnumber => $cardnumber);
139     $template->param(filetype => $filetype);
140 } elsif ( $op eq 'Delete' ) {
141     my $dberror = RmPatronImage($cardnumber);
142     warn "Database returned $dberror" if $dberror;
143 } elsif ( $op eq 'Cancel' ) {
144     print $input->redirect ("/cgi-bin/koha/tools/picture-upload.pl");
145 }
146
147 if ( $borrowernumber && !$errors && !$template->param('ERRORS') ) {
148     print $input->redirect ("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
149 } else {
150     output_html_with_http_headers $input, $cookie, $template->output;
151 }
152
153 sub handle_dir {
154     my ( $dir, $suffix ) = @_;
155     my $source;
156     warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix" if $DEBUG;
157     if ($suffix =~ m/zip/i) {     # If we were sent a zip file, process any included data/idlink.txt files 
158         my ( $file, $filename, $cardnumber );
159         warn "Passed a zip file." if $DEBUG;
160         opendir my $dirhandle, $dir;
161         while ( my $filename = readdir $dirhandle ) {
162             $file = "$dir/$filename" if ($filename =~ m/datalink\.txt/i || $filename =~ m/idlink\.txt/i);
163         }
164         unless (open (FILE, $file)) { 
165                 warn "Opening $dir/$file failed!";
166                 $errors{'OPNLINK'} = $file;
167                 return $errors; # This error is fatal to the import of this directory contents, so bail and return the error to the caller
168         };
169
170         while (my $line = <FILE>) {
171             warn "Reading contents of $file" if $DEBUG;
172             chomp $line;
173             warn "Examining line: $line" if $DEBUG;
174             my $delim = ($line =~ /\t/) ? "\t" : ($line =~ /,/) ? "," : "";
175             warn "Delimeter is \'$delim\'" if $DEBUG;
176             unless ( $delim eq "," || $delim eq "\t" ) {
177                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
178                 $errors{'DELERR'} = 1;      # This error is fatal to the import of this directory contents, so bail and return the error to the caller
179                 return $errors;
180             }
181             ($cardnumber, $filename) = split $delim, $line;
182             $cardnumber =~ s/[\"\r\n]//g;  # remove offensive characters
183             $filename   =~ s/[\"\r\n\s]//g;
184             warn "Cardnumber: $cardnumber Filename: $filename" if $DEBUG;
185             $source = "$dir/$filename";
186             %counts = handle_file($cardnumber, $source, %counts);
187         }
188         close FILE;
189         closedir ($dirhandle);
190     } else {
191         $source = $tempfile;
192         %counts = handle_file($cardnumber, $source, %counts);
193     }
194 push @counts, \%counts;
195 return 1;
196 }
197
198 sub handle_file {
199     my ($cardnumber, $source, %count) = @_;
200     warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source" if $DEBUG;
201     my $mimemap = {
202         "gif"   => "image/gif",
203         "jpg"   => "image/jpeg",
204         "jpeg"  => "image/jpeg",
205         "png"   => "image/png"
206     };
207     $count{filenames} = () if !$count{filenames};
208     $count{source} = $source if !$count{source};
209     if ($cardnumber && $source) {     # Now process any imagefiles
210         my %filerrors;
211         warn "Source: $source" if $DEBUG;
212         if (open (IMG, "$source")) {
213             #binmode (IMG); # Not sure if we need this or not -fbcit
214             my $imgfile;
215             while (<IMG>) {
216                 $imgfile .= $_;
217             }
218             if ($filetype eq 'image') {
219                 $filename = $uploadfilename;
220             } else {
221                 $filename = $1 if ($source =~ /\/([^\/]+)$/);
222             }
223             warn "\$filename=$filename";
224             my $mimetype = $mimemap->{lc ($1)} if $filename =~ m/\.([^.]+)$/i;
225             warn "$filename is mimetype \"$mimetype\"" if $DEBUG;
226             my $dberror = PutPatronImage($cardnumber,$mimetype, $imgfile) if $mimetype;
227             close (IMG);
228             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
229                 $count{count}++;
230                 push @{ $count{filenames} }, { source => $filename, cardnumber => $cardnumber };
231             } elsif ( $dberror ) {
232                 warn "Database returned error: $dberror";
233                 ($dberror =~ /patronimage_fk1/) ? $filerrors{'IMGEXISTS'} = 1 : $filerrors{'DBERR'} = 1;
234                 push my @filerrors, \%filerrors;
235                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
236                 $template->param( ERRORS => 1 );
237             } elsif ( !$mimetype ) {
238                 warn "Unable to determine mime type of $filename. Please verify mimetype and add to \%mimemap if necessary.";
239                 $filerrors{'MIMERR'} = 1;
240                 push my @filerrors, \%filerrors;
241                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
242                 $template->param( ERRORS => 1 );
243             }
244         } else {
245             warn "Opening $dir/$filename failed!";
246             $filerrors{'OPNERR'} = 1;
247             push my @filerrors, \%filerrors;
248             push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
249             $template->param( ERRORS => 1 );
250         }
251     } else {    # The need for this seems a bit unlikely, however, to maximize error trapping it is included
252         warn "Missing " . ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
253         $filerrors{'CRDFIL'} = ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename")); 
254         push my @filerrors, \%filerrors;
255         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
256         $template->param( ERRORS => 1 );
257     }
258     return %count;
259 }
260
261 =back
262
263 =head1 AUTHORS
264
265 Original contributor(s) undocumented
266
267 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
268
269 =cut