fa1ae34783051b3021609d03a9e7cf667c9213a3
[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 Modern::Perl;
23
24 use File::Temp;
25 use File::Copy;
26 use CGI;
27 use GD;
28 use C4::Context;
29 use C4::Auth;
30 use C4::Output;
31 use C4::Members;
32 use C4::Debug;
33
34 my $input = new CGI;
35
36 my ($template, $loggedinuser, $cookie)
37     = get_template_and_user({template_name => "tools/picture-upload.tt",
38                                         query => $input,
39                                         type => "intranet",
40                                         authnotrequired => 0,
41                                         flagsrequired => { tools => 'batch_upload_patron_images'},
42                                         debug => 0,
43                                         });
44
45 my $filetype            = $input->param('filetype');
46 my $cardnumber          = $input->param('cardnumber');
47 my $uploadfilename      = $input->param('uploadfile');
48 my $uploadfile          = $input->upload('uploadfile');
49 my $borrowernumber      = $input->param('borrowernumber');
50 my $op                  = $input->param('op');
51
52 #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.
53 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
54 #       coded. -fbcit
55
56 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
57
58 =head1 NAME
59
60 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
61
62 =head1 SYNOPSIS
63
64 picture-upload.pl
65
66 =head1 DESCRIPTION
67
68 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.
69 Files greater than 100K will be refused. Images should be 140x200 pixels. If they are larger they will be auto-resized to comply.
70
71 =cut
72
73 $debug and warn "Operation requested: $op";
74
75 my ( $total, $handled, @counts, $tempfile, $tfh, %errors );
76
77 if ( ($op eq 'Upload') && $uploadfile ) {       # Case is important in these operational values as the template must use case to be visually pleasing!
78     my $dirname = File::Temp::tempdir( CLEANUP => 1);
79     $debug and warn "dirname = $dirname";
80     my $filesuffix;
81     if ( $uploadfilename =~ m/(\..+)$/i ) {
82         $filesuffix = $1;
83     }
84     ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
85     $debug and warn "tempfile = $tempfile";
86     my ( @directories, $results );
87
88     $errors{'NOTZIP'} = 1 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
89     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
90     $errors{'EMPTYUPLOAD'} = 1 unless ( length( $uploadfile ) > 0 );
91
92     if ( %errors ) {
93         $template->param( ERRORS => [ \%errors ] );
94         output_html_with_http_headers $input, $cookie, $template->output;
95         exit;
96     }
97         while ( <$uploadfile> ) {
98             print $tfh $_;
99         }
100         close $tfh;
101         if ( $filetype eq 'zip' ) {
102             unless (system("unzip", $tempfile,  '-d', $dirname) == 0) {
103                 $errors{'UZIPFAIL'} = $uploadfilename;
104                 $template->param( ERRORS => [ \%errors ] );
105                 output_html_with_http_headers $input, $cookie, $template->output;   # This error is fatal to the import, so bail out here
106                 exit;
107             }
108             push @directories, "$dirname";
109             foreach my $recursive_dir ( @directories ) {
110                 opendir RECDIR, $recursive_dir;
111                 while ( my $entry = readdir RECDIR ) {
112                 push @directories, "$recursive_dir/$entry" if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
113                 $debug and warn "$recursive_dir/$entry";
114                 }
115                 closedir RECDIR;
116             }
117             foreach my $dir ( @directories ) {
118                 $results = handle_dir( $dir, $filesuffix, $template );
119                 $handled++ if $results == 1;
120             }
121             $total = scalar @directories;
122         } else {       #if ($filetype eq 'zip' )
123             $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber, $tempfile );
124             $handled = 1;
125             $total = 1;
126         }
127
128         if ( %$results || %errors ) {
129             $template->param( ERRORS => [ $results ] );
130         } else {
131                         my $filecount;
132                         map {$filecount += $_->{count}} @counts;
133             $debug and warn "Total directories processed: $total";
134             $debug and warn "Total files processed: $filecount";
135             $template->param(
136                         TOTAL => $total,
137                         HANDLED => $handled,
138                         COUNTS => \@counts,
139                         TCOUNTS => ($filecount > 0 ? $filecount : undef),
140             );
141                         $template->param( borrowernumber => $borrowernumber ) if $borrowernumber;
142         }
143 } elsif ( ($op eq 'Upload') && !$uploadfile ) {
144     warn "Problem uploading file or no file uploaded.";
145     $template->param(cardnumber => $cardnumber);
146     $template->param(filetype => $filetype);
147 } elsif ( $op eq 'Delete' ) {
148     my $dberror = RmPatronImage($borrowernumber);
149         $debug and warn "Patron image deleted for $cardnumber";
150     warn "Database returned $dberror" if $dberror;
151 }
152 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
153     print $input->redirect ("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
154 } else {
155     output_html_with_http_headers $input, $cookie, $template->output;
156 }
157
158 sub handle_dir {
159     my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
160     my ( %counts, %direrrors );
161     $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
162     if ($suffix =~ m/zip/i) {     # If we were sent a zip file, process any included data/idlink.txt files
163         my ( $file, $filename );
164         undef $cardnumber;
165         $debug and warn "Passed a zip file.";
166         opendir DIR, $dir;
167         while ( my $filename = readdir DIR ) {
168             $file = "$dir/$filename" if ($filename =~ m/datalink\.txt/i || $filename =~ m/idlink\.txt/i);
169         }
170         unless (open (FILE, $file)) {
171                 warn "Opening $dir/$file failed!";
172                 $direrrors{'OPNLINK'} = $file;
173                 return \%direrrors; # This error is fatal to the import of this directory contents, so bail and return the error to the caller
174         };
175
176         while (my $line = <FILE>) {
177             $debug and warn "Reading contents of $file";
178             chomp $line;
179             $debug and warn "Examining line: $line";
180             my $delim = ($line =~ /\t/) ? "\t" : ($line =~ /,/) ? "," : "";
181             $debug and warn "Delimeter is \'$delim\'";
182             unless ( $delim eq "," || $delim eq "\t" ) {
183                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
184                 $direrrors{'DELERR'} = 1;      # This error is fatal to the import of this directory contents, so bail and return the error to the caller
185                 return \%direrrors;
186             }
187             ($cardnumber, $filename) = split $delim, $line;
188             $cardnumber =~ s/[\"\r\n]//g;  # remove offensive characters
189             $filename   =~ s/[\"\r\n\s]//g;
190             $debug and warn "Cardnumber: $cardnumber Filename: $filename";
191             $source = "$dir/$filename";
192             %counts = handle_file($cardnumber, $source, $template, %counts);
193         }
194         close FILE;
195         closedir DIR;
196     } else {
197         %counts = handle_file($cardnumber, $source, $template, %counts);
198     }
199 push @counts, \%counts;
200 return 1;
201 }
202
203 sub handle_file {
204     my ($cardnumber, $source, $template, %count) = @_;
205     $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
206     $count{filenames} = () if !$count{filenames};
207     $count{source} = $source if !$count{source};
208     my %filerrors;
209     my $filename;
210     if ($filetype eq 'image') {
211         $filename = $uploadfilename;
212     } else {
213         $filename = $1 if ($source && $source =~ /\/([^\/]+)$/);
214     }
215     if ($cardnumber && $source) {     # Now process any imagefiles
216         $debug and warn "Source: $source";
217         my $size = (stat($source))[7];
218             if ($size > 550000) {    # This check is necessary even with image resizing to avoid possible security/performance issues...
219                 $filerrors{'OVRSIZ'} = 1;
220                 push my @filerrors, \%filerrors;
221                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
222                 $template->param( ERRORS => 1 );
223                 return %count;    # this one is fatal so bail here...
224             }
225         my ($srcimage, $image);
226         if (open (IMG, "$source")) {
227             $srcimage = GD::Image->new(*IMG);
228             close (IMG);
229                         if (defined $srcimage) {
230                                 my $imgfile;
231                                 my $mimetype = 'image/png';     # GD autodetects three basic image formats: PNG, JPEG, XPM; we will convert all to PNG which is lossless...
232                                 # Check the pixel size of the image we are about to import...
233                                 my ($width, $height) = $srcimage->getBounds();
234                                 $debug and warn "$filename is $width pix X $height pix.";
235                                 if ($width > 200 || $height > 300) {    # MAX pixel dims are 200 X 300...
236                                         $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
237                                         my $percent_reduce;    # Percent we will reduce the image dimensions by...
238                                         if ($width > 200) {
239                                                 $percent_reduce = sprintf("%.5f",(140/$width));    # If the width is oversize, scale based on width overage...
240                                         } else {
241                                                 $percent_reduce = sprintf("%.5f",(200/$height));    # otherwise scale based on height overage.
242                                         }
243                                         my $width_reduce = sprintf("%.0f", ($width * $percent_reduce));
244                                         my $height_reduce = sprintf("%.0f", ($height * $percent_reduce));
245                                         $debug and warn "Reducing $filename by " . ($percent_reduce * 100) . "\% or to $width_reduce pix X $height_reduce pix";
246                                         $image = GD::Image->new($width_reduce, $height_reduce, 1); #'1' creates true color image...
247                                         $image->copyResampled($srcimage,0,0,0,0,$width_reduce,$height_reduce,$width,$height);
248                                         $imgfile = $image->png();
249                                         $debug and warn "$filename is " . length($imgfile) . " bytes after resizing.";
250                                         undef $image;
251                                         undef $srcimage;    # This object can get big...
252                                 } else {
253                                         $image = $srcimage;
254                                         $imgfile = $image->png();
255                                         $debug and warn "$filename is " . length($imgfile) . " bytes.";
256                                         undef $image;
257                                         undef $srcimage;    # This object can get big...
258                                 }
259                                 $debug and warn "Image is of mimetype $mimetype";
260                 my $dberror;
261                 if ($mimetype) {
262                     $dberror = PutPatronImage( $cardnumber, $mimetype, $imgfile );
263                 }
264                 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
265                                         $count{count}++;
266                                         push @{ $count{filenames} }, { source => $filename, cardnumber => $cardnumber };
267                                 } elsif ( $dberror ) {
268                                                 warn "Database returned error: $dberror";
269                                                 ($dberror =~ /patronimage_fk1/) ? $filerrors{'IMGEXISTS'} = 1 : $filerrors{'DBERR'} = 1;
270                                                 push my @filerrors, \%filerrors;
271                                                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
272                                                 $template->param( ERRORS => 1 );
273                                 } elsif ( !$mimetype ) {
274                                         warn "Unable to determine mime type of $filename. Please verify mimetype.";
275                                         $filerrors{'MIMERR'} = 1;
276                                         push my @filerrors, \%filerrors;
277                                         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
278                                         $template->param( ERRORS => 1 );
279                                 }
280                         } else {
281                                 warn "Contents of $filename corrupted!";
282                         #       $count{count}--;
283                                 $filerrors{'CORERR'} = 1;
284                                 push my @filerrors, \%filerrors;
285                                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
286                                 $template->param( ERRORS => 1 );
287                         }
288                 } else {
289                         warn "Opening $source failed!";
290                         $filerrors{'OPNERR'} = 1;
291                         push my @filerrors, \%filerrors;
292                         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
293                         $template->param( ERRORS => 1 );
294                 }
295     } else {    # The need for this seems a bit unlikely, however, to maximize error trapping it is included
296         warn "Missing " . ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
297         $filerrors{'CRDFIL'} = ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
298         push my @filerrors, \%filerrors;
299                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
300         $template->param( ERRORS => 1 );
301     }
302     return (%count);
303 }
304
305 =head1 AUTHORS
306
307 Original contributor(s) undocumented
308
309 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
310 Image scaling/resizing contributed by the same.
311
312 =cut