Bug 9312: Perltidying picture-upload.pl
[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 ) {
78     # Case is important in these operational values as the template must use case to be visually pleasing!
79     my $dirname = File::Temp::tempdir( CLEANUP => 1 );
80     $debug and warn "dirname = $dirname";
81     my $filesuffix;
82     if ( $uploadfilename =~ m/(\..+)$/i ) {
83         $filesuffix = $1;
84     }
85     ( $tfh, $tempfile ) =
86       File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
87     $debug and warn "tempfile = $tempfile";
88     my ( @directories, $results );
89
90     $errors{'NOTZIP'} = 1
91       if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
92     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
93     $errors{'EMPTYUPLOAD'} = 1 unless ( length($uploadfile) > 0 );
94
95     if (%errors) {
96         $template->param( ERRORS => [ \%errors ] );
97         output_html_with_http_headers $input, $cookie, $template->output;
98         exit;
99     }
100     while (<$uploadfile>) {
101         print $tfh $_;
102     }
103     close $tfh;
104     if ( $filetype eq 'zip' ) {
105         unless ( system( "unzip", $tempfile, '-d', $dirname ) == 0 ) {
106             $errors{'UZIPFAIL'} = $uploadfilename;
107             $template->param( ERRORS => [ \%errors ] );
108             # This error is fatal to the import, so bail out here
109             output_html_with_http_headers $input, $cookie, $template->output;
110             exit;
111         }
112         push @directories, "$dirname";
113         foreach my $recursive_dir (@directories) {
114             opendir RECDIR, $recursive_dir;
115             while ( my $entry = readdir RECDIR ) {
116                 push @directories, "$recursive_dir/$entry"
117                   if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
118                 $debug and warn "$recursive_dir/$entry";
119             }
120             closedir RECDIR;
121         }
122         foreach my $dir (@directories) {
123             $results = handle_dir( $dir, $filesuffix, $template );
124             $handled++ if $results == 1;
125         }
126         $total = scalar @directories;
127     }
128     else {
129         #if ($filetype eq 'zip' )
130         $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber,
131             $tempfile );
132         $handled = 1;
133         $total   = 1;
134     }
135
136     if ( %$results || %errors ) {
137         $template->param( ERRORS => [$results] );
138     }
139     else {
140         my $filecount;
141         map { $filecount += $_->{count} } @counts;
142         $debug and warn "Total directories processed: $total";
143         $debug and warn "Total files processed: $filecount";
144         $template->param(
145             TOTAL   => $total,
146             HANDLED => $handled,
147             COUNTS  => \@counts,
148             TCOUNTS => ( $filecount > 0 ? $filecount : undef ),
149         );
150         $template->param( borrowernumber => $borrowernumber )
151           if $borrowernumber;
152     }
153 }
154 elsif ( ( $op eq 'Upload' ) && !$uploadfile ) {
155     warn "Problem uploading file or no file uploaded.";
156     $template->param( cardnumber => $cardnumber );
157     $template->param( filetype   => $filetype );
158 }
159 elsif ( $op eq 'Delete' ) {
160     my $dberror = RmPatronImage($cardnumber);
161     $debug and warn "Patron image deleted for $cardnumber";
162     warn "Database returned $dberror" if $dberror;
163 }
164 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
165     print $input->redirect(
166         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
167 }
168 else {
169     output_html_with_http_headers $input, $cookie, $template->output;
170 }
171
172 sub handle_dir {
173     my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
174     my ( %counts, %direrrors );
175     $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
176     if ( $suffix =~ m/zip/i ) {
177         # If we were sent a zip file, process any included data/idlink.txt files
178         my ( $file, $filename );
179         undef $cardnumber;
180         $debug and warn "Passed a zip file.";
181         opendir DIR, $dir;
182         while ( my $filename = readdir DIR ) {
183             $file = "$dir/$filename"
184               if ( $filename =~ m/datalink\.txt/i
185                 || $filename =~ m/idlink\.txt/i );
186         }
187         unless ( open( FILE, $file ) ) {
188             warn "Opening $dir/$file failed!";
189             $direrrors{'OPNLINK'} = $file;
190             # This error is fatal to the import of this directory contents
191             # so bail and return the error to the caller
192             return \%direrrors;
193         }
194
195         while ( my $line = <FILE> ) {
196             $debug and warn "Reading contents of $file";
197             chomp $line;
198             $debug and warn "Examining line: $line";
199             my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
200             $debug and warn "Delimeter is \'$delim\'";
201             unless ( $delim eq "," || $delim eq "\t" ) {
202                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
203                 $direrrors{'DELERR'} = 1;
204                 # This error is fatal to the import of this directory contents
205                 # so bail and return the error to the caller
206                 return \%direrrors;
207             }
208             ( $cardnumber, $filename ) = split $delim, $line;
209             $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
210             $filename   =~ s/[\"\r\n\s]//g;
211             $debug and warn "Cardnumber: $cardnumber Filename: $filename";
212             $source = "$dir/$filename";
213             %counts = handle_file( $cardnumber, $source, $template, %counts );
214         }
215         close FILE;
216         closedir DIR;
217     }
218     else {
219         %counts = handle_file( $cardnumber, $source, $template, %counts );
220     }
221     push @counts, \%counts;
222     return 1;
223 }
224
225 sub handle_file {
226     my ( $cardnumber, $source, $template, %count ) = @_;
227     $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
228     $count{filenames} = ()      if !$count{filenames};
229     $count{source}    = $source if !$count{source};
230     my %filerrors;
231     my $filename;
232     if ( $filetype eq 'image' ) {
233         $filename = $uploadfilename;
234     }
235     else {
236         $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
237     }
238     if ( $cardnumber && $source ) {
239         # Now process any imagefiles
240         $debug and warn "Source: $source";
241         my $size = ( stat($source) )[7];
242         if ( $size > 550000 ) {
243             # This check is necessary even with image resizing to avoid possible security/performance issues...
244             $filerrors{'OVRSIZ'} = 1;
245             push my @filerrors, \%filerrors;
246             push @{ $count{filenames} },
247               {
248                 filerrors  => \@filerrors,
249                 source     => $filename,
250                 cardnumber => $cardnumber
251               };
252             $template->param( ERRORS => 1 );
253             # this one is fatal so bail here...
254             return %count;
255         }
256         my ( $srcimage, $image );
257         if ( open( IMG, "$source" ) ) {
258             $srcimage = GD::Image->new(*IMG);
259             close(IMG);
260             if ( defined $srcimage ) {
261                 my $imgfile;
262                 my $mimetype = 'image/png';
263                 # GD autodetects three basic image formats: PNG, JPEG, XPM
264                 # we will convert all to PNG which is lossless...
265                 # Check the pixel size of the image we are about to import...
266                 my ( $width, $height ) = $srcimage->getBounds();
267                 $debug and warn "$filename is $width pix X $height pix.";
268                 if ( $width > 200 || $height > 300 ) {
269                     # MAX pixel dims are 200 X 300...
270                     $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
271                     # Percent we will reduce the image dimensions by...
272                     my $percent_reduce;
273                     if ( $width > 200 ) {
274                         # If the width is oversize, scale based on width overage...
275                         $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
276                     }
277                     else {
278                         # otherwise scale based on height overage.
279                         $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
280                     }
281                     my $width_reduce =
282                       sprintf( "%.0f", ( $width * $percent_reduce ) );
283                     my $height_reduce =
284                       sprintf( "%.0f", ( $height * $percent_reduce ) );
285                     $debug
286                       and warn "Reducing $filename by "
287                       . ( $percent_reduce * 100 )
288                       . "\% or to $width_reduce pix X $height_reduce pix";
289                     #'1' creates true color image...
290                     $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
291                     $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
292                         $height_reduce, $width, $height );
293                     $imgfile = $image->png();
294                     $debug
295                       and warn "$filename is "
296                       . length($imgfile)
297                       . " bytes after resizing.";
298                     undef $image;
299                     undef $srcimage; # This object can get big...
300                 }
301                 else {
302                     $image   = $srcimage;
303                     $imgfile = $image->png();
304                     $debug
305                       and warn "$filename is " . length($imgfile) . " bytes.";
306                     undef $image;
307                     undef $srcimage; # This object can get big...
308                 }
309                 $debug and warn "Image is of mimetype $mimetype";
310                 my $dberror;
311                 if ($mimetype) {
312                     $dberror =
313                       PutPatronImage( $cardnumber, $mimetype, $imgfile );
314                 }
315                 if ( !$dberror && $mimetype ) {
316                     # Errors from here on are fatal only to the import of a particular image
317                     #so don't bail, just note the error and keep going
318                     $count{count}++;
319                     push @{ $count{filenames} },
320                       { source => $filename, cardnumber => $cardnumber };
321                 }
322                 elsif ($dberror) {
323                     warn "Database returned error: $dberror";
324                     ( $dberror =~ /patronimage_fk1/ )
325                       ? $filerrors{'IMGEXISTS'} = 1
326                       : $filerrors{'DBERR'} = 1;
327                     push my @filerrors, \%filerrors;
328                     push @{ $count{filenames} },
329                       {
330                         filerrors  => \@filerrors,
331                         source     => $filename,
332                         cardnumber => $cardnumber
333                       };
334                     $template->param( ERRORS => 1 );
335                 }
336                 elsif ( !$mimetype ) {
337                     warn "Unable to determine mime type of $filename. Please verify mimetype.";
338                     $filerrors{'MIMERR'} = 1;
339                     push my @filerrors, \%filerrors;
340                     push @{ $count{filenames} },
341                       {
342                         filerrors  => \@filerrors,
343                         source     => $filename,
344                         cardnumber => $cardnumber
345                       };
346                     $template->param( ERRORS => 1 );
347                 }
348             }
349             else {
350                 warn "Contents of $filename corrupted!";
351                 #       $count{count}--;
352                 $filerrors{'CORERR'} = 1;
353                 push my @filerrors, \%filerrors;
354                 push @{ $count{filenames} },
355                   {
356                     filerrors  => \@filerrors,
357                     source     => $filename,
358                     cardnumber => $cardnumber
359                   };
360                 $template->param( ERRORS => 1 );
361             }
362         }
363         else {
364             warn "Opening $source failed!";
365             $filerrors{'OPNERR'} = 1;
366             push my @filerrors, \%filerrors;
367             push @{ $count{filenames} },
368               {
369                 filerrors  => \@filerrors,
370                 source     => $filename,
371                 cardnumber => $cardnumber
372               };
373             $template->param( ERRORS => 1 );
374         }
375     }
376     else {
377         # The need for this seems a bit unlikely, however, to maximize error trapping it is included
378         warn "Missing "
379           . (
380             $cardnumber
381             ? "filename"
382             : ( $filename ? "cardnumber" : "cardnumber and filename" )
383           );
384         $filerrors{'CRDFIL'} = (
385             $cardnumber
386             ? "filename"
387             : ( $filename ? "cardnumber" : "cardnumber and filename" )
388         );
389         push my @filerrors, \%filerrors;
390         push @{ $count{filenames} },
391           {
392             filerrors  => \@filerrors,
393             source     => $filename,
394             cardnumber => $cardnumber
395           };
396         $template->param( ERRORS => 1 );
397     }
398     return (%count);
399 }
400
401 =head1 AUTHORS
402
403 Original contributor(s) undocumented
404
405 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
406 Image scaling/resizing contributed by the same.
407
408 =cut