Bug 15635: Koha::Patron::Images - Remove PutPatronImage
[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
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
18 #
19 #
20 #
21
22 use Modern::Perl;
23
24 use File::Temp;
25 use File::Copy;
26 use CGI qw ( -utf8 );
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 use Koha::Patrons;
35 use Koha::Patron::Image;
36
37 my $input = new CGI;
38
39 my ($template, $loggedinuser, $cookie)
40     = get_template_and_user({template_name => "tools/picture-upload.tt",
41                                         query => $input,
42                                         type => "intranet",
43                                         authnotrequired => 0,
44                                         flagsrequired => { tools => 'batch_upload_patron_images'},
45                                         debug => 0,
46                                         });
47
48 my $filetype       = $input->param('filetype');
49 my $cardnumber     = $input->param('cardnumber');
50 my $uploadfilename = $input->param('uploadfile');
51 my $uploadfile     = $input->upload('uploadfile');
52 my $borrowernumber = $input->param('borrowernumber');
53 my $op             = $input->param('op') || '';
54
55 #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.
56 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
57 #       coded. -fbcit
58
59 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
60
61 =head1 NAME
62
63 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
64
65 =head1 SYNOPSIS
66
67 picture-upload.pl
68
69 =head1 DESCRIPTION
70
71 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.
72 Files greater than 100K will be refused. Images should be 140x200 pixels. If they are larger they will be auto-resized to comply.
73
74 =cut
75
76 $debug and warn "Operation requested: $op";
77
78 my ( $total, $handled, @counts, $tempfile, $tfh, %errors );
79
80 # Case is important in these operational values as the template must use case to be visually pleasing!
81 if ( ( $op eq 'Upload' ) && $uploadfile ) {
82     my $dirname = File::Temp::tempdir( CLEANUP => 1 );
83     $debug and warn "dirname = $dirname";
84     my $filesuffix;
85     if ( $uploadfilename =~ m/(\..+)$/i ) {
86         $filesuffix = $1;
87     }
88     ( $tfh, $tempfile ) =
89       File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
90     $debug and warn "tempfile = $tempfile";
91     my ( @directories, $results );
92
93     $errors{'NOTZIP'} = 1
94       if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
95     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
96     $errors{'EMPTYUPLOAD'} = 1 unless ( length($uploadfile) > 0 );
97
98     if (%errors) {
99         $template->param( ERRORS => [ \%errors ] );
100         output_html_with_http_headers $input, $cookie, $template->output;
101         exit;
102     }
103     while (<$uploadfile>) {
104         print $tfh $_;
105     }
106     close $tfh;
107     if ( $filetype eq 'zip' ) {
108         unless ( system( "unzip", $tempfile, '-d', $dirname ) == 0 ) {
109             $errors{'UZIPFAIL'} = $uploadfilename;
110             $template->param( ERRORS => [ \%errors ] );
111             # This error is fatal to the import, so bail out here
112             output_html_with_http_headers $input, $cookie, $template->output;
113             exit;
114         }
115         push @directories, "$dirname";
116         foreach my $recursive_dir (@directories) {
117             opendir RECDIR, $recursive_dir;
118             while ( my $entry = readdir RECDIR ) {
119                 push @directories, "$recursive_dir/$entry"
120                   if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
121                 $debug and warn "$recursive_dir/$entry";
122             }
123             closedir RECDIR;
124         }
125         foreach my $dir (@directories) {
126             $results = handle_dir( $dir, $filesuffix, $template );
127             $handled++ if $results == 1;
128         }
129         $total = scalar @directories;
130     }
131     else {
132         #if ($filetype eq 'zip' )
133         $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber,
134             $tempfile );
135         $handled++ if $results == 1;
136         $total   = 1;
137     }
138
139     if ( $results!=1 || %errors ) {
140         $template->param( ERRORS => [$results] );
141     }
142     else {
143         my $filecount;
144         map { $filecount += $_->{count} } @counts;
145         $debug and warn "Total directories processed: $total";
146         $debug and warn "Total files processed: $filecount";
147         $template->param(
148             TOTAL   => $total,
149             HANDLED => $handled,
150             COUNTS  => \@counts,
151             TCOUNTS => ( $filecount > 0 ? $filecount : undef ),
152         );
153         $template->param( borrowernumber => $borrowernumber )
154           if $borrowernumber;
155     }
156 }
157 elsif ( ( $op eq 'Upload' ) && !$uploadfile ) {
158     warn "Problem uploading file or no file uploaded.";
159     $template->param( cardnumber => $cardnumber );
160     $template->param( filetype   => $filetype );
161 }
162 elsif ( $op eq 'Delete' ) {
163     my $dberror = RmPatronImage($borrowernumber);
164     $debug and warn "Patron image deleted for $borrowernumber";
165     warn "Database returned $dberror" if $dberror;
166 }
167 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
168     print $input->redirect(
169         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
170 }
171 else {
172     output_html_with_http_headers $input, $cookie, $template->output;
173 }
174
175 sub handle_dir {
176     my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
177     my ( %counts, %direrrors );
178     $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
179     if ( $suffix =~ m/zip/i ) {
180         # If we were sent a zip file, process any included data/idlink.txt files
181         my ( $file, $filename );
182         undef $cardnumber;
183         $debug and warn "Passed a zip file.";
184         opendir DIR, $dir;
185         while ( my $filename = readdir DIR ) {
186             $file = "$dir/$filename"
187               if ( $filename =~ m/datalink\.txt/i
188                 || $filename =~ m/idlink\.txt/i );
189         }
190         unless ( open( FILE, $file ) ) {
191             warn "Opening $dir/$file failed!";
192             $direrrors{'OPNLINK'} = $file;
193             # This error is fatal to the import of this directory contents
194             # so bail and return the error to the caller
195             return \%direrrors;
196         }
197
198         while ( my $line = <FILE> ) {
199             $debug and warn "Reading contents of $file";
200             chomp $line;
201             $debug and warn "Examining line: $line";
202             my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
203             $debug and warn "Delimeter is \'$delim\'";
204             unless ( $delim eq "," || $delim eq "\t" ) {
205                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
206                 $direrrors{'DELERR'} = 1;
207                 # This error is fatal to the import of this directory contents
208                 # so bail and return the error to the caller
209                 return \%direrrors;
210             }
211             ( $cardnumber, $filename ) = split $delim, $line;
212             $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
213             $filename   =~ s/[\"\r\n\s]//g;
214             $debug and warn "Cardnumber: $cardnumber Filename: $filename";
215             $source = "$dir/$filename";
216             %counts = handle_file( $cardnumber, $source, $template, %counts );
217         }
218         close FILE;
219         closedir DIR;
220     }
221     else {
222         %counts = handle_file( $cardnumber, $source, $template, %counts );
223     }
224     push @counts, \%counts;
225     return 1;
226 }
227
228 sub handle_file {
229     my ( $cardnumber, $source, $template, %count ) = @_;
230     $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
231     $count{filenames} = ()      if !$count{filenames};
232     $count{source}    = $source if !$count{source};
233     $count{count}     = 0       unless exists $count{count};
234     my %filerrors;
235     my $filename;
236     if ( $filetype eq 'image' ) {
237         $filename = $uploadfilename;
238     }
239     else {
240         $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
241     }
242     if ( $cardnumber && $source ) {
243         # Now process any imagefiles
244         $debug and warn "Source: $source";
245         my $size = ( stat($source) )[7];
246         if ( $size > 550000 ) {
247             # This check is necessary even with image resizing to avoid possible security/performance issues...
248             $filerrors{'OVRSIZ'} = 1;
249             push my @filerrors, \%filerrors;
250             push @{ $count{filenames} },
251               {
252                 filerrors  => \@filerrors,
253                 source     => $filename,
254                 cardnumber => $cardnumber
255               };
256             $template->param( ERRORS => 1 );
257             # this one is fatal so bail here...
258             return %count;
259         }
260         my ( $srcimage, $image );
261         if ( open( IMG, "$source" ) ) {
262             $srcimage = GD::Image->new(*IMG);
263             close(IMG);
264             if ( defined $srcimage ) {
265                 my $imgfile;
266                 my $mimetype = 'image/png';
267                 # GD autodetects three basic image formats: PNG, JPEG, XPM
268                 # we will convert all to PNG which is lossless...
269                 # Check the pixel size of the image we are about to import...
270                 my ( $width, $height ) = $srcimage->getBounds();
271                 $debug and warn "$filename is $width pix X $height pix.";
272                 if ( $width > 200 || $height > 300 ) {
273                     # MAX pixel dims are 200 X 300...
274                     $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
275                     # Percent we will reduce the image dimensions by...
276                     my $percent_reduce;
277                     if ( $width > 200 ) {
278                         # If the width is oversize, scale based on width overage...
279                         $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
280                     }
281                     else {
282                         # otherwise scale based on height overage.
283                         $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
284                     }
285                     my $width_reduce =
286                       sprintf( "%.0f", ( $width * $percent_reduce ) );
287                     my $height_reduce =
288                       sprintf( "%.0f", ( $height * $percent_reduce ) );
289                     $debug
290                       and warn "Reducing $filename by "
291                       . ( $percent_reduce * 100 )
292                       . "\% or to $width_reduce pix X $height_reduce pix";
293                     #'1' creates true color image...
294                     $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
295                     $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
296                         $height_reduce, $width, $height );
297                     $imgfile = $image->png();
298                     $debug
299                       and warn "$filename is "
300                       . length($imgfile)
301                       . " bytes after resizing.";
302                     undef $image;
303                     undef $srcimage; # This object can get big...
304                 }
305                 else {
306                     $image   = $srcimage;
307                     $imgfile = $image->png();
308                     $debug
309                       and warn "$filename is " . length($imgfile) . " bytes.";
310                     undef $image;
311                     undef $srcimage; # This object can get big...
312                 }
313                 $debug and warn "Image is of mimetype $mimetype";
314                 my $dberror;
315                 if ($mimetype) {
316                     my $patron = Koha::Patrons->find({ cardnumber => $cardnumber });
317                     if ( $patron ) {
318                         my $image = $patron->image;
319                         $image ||= Koha::Patron::Image->new({ borrowernumber => $patron->borrowernumber });
320                         $image->set({
321                             mimetype => $mimetype,
322                             imagefile => $imgfile,
323                         });
324                         eval { $image->store };
325                         if ( $@ ) {
326                             # Errors from here on are fatal only to the import of a particular image
327                             #so don't bail, just note the error and keep going
328                             warn "Database returned error: $@";
329                             $filerrors{'DBERR'} = 1;
330                             push my @filerrors, \%filerrors;
331                             push @{ $count{filenames} },
332                               {
333                                 filerrors  => \@filerrors,
334                                 source     => $filename,
335                                 cardnumber => $cardnumber
336                               };
337                             $template->param( ERRORS => 1 );
338                         } else {
339                             $count{count}++;
340                             push @{ $count{filenames} },
341                               { source => $filename, cardnumber => $cardnumber };
342                         }
343                     } else {
344                         warn "Patron with the cardnumber '$cardnumber' does not exist";
345                         $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1;
346                         push my @filerrors, \%filerrors;
347                         push @{ $count{filenames} },
348                           {
349                             filerrors  => \@filerrors,
350                             source     => $filename,
351                             cardnumber => $cardnumber
352                           };
353                         $template->param( ERRORS => 1 );
354                     }
355                 }
356                 else {
357                     warn "Unable to determine mime type of $filename. Please verify mimetype.";
358                     $filerrors{'MIMERR'} = 1;
359                     push my @filerrors, \%filerrors;
360                     push @{ $count{filenames} },
361                       {
362                         filerrors  => \@filerrors,
363                         source     => $filename,
364                         cardnumber => $cardnumber
365                       };
366                     $template->param( ERRORS => 1 );
367                 }
368             }
369             else {
370                 warn "Contents of $filename corrupted!";
371                 #$count{count}--;
372                 $filerrors{'CORERR'} = 1;
373                 push my @filerrors, \%filerrors;
374                 push @{ $count{filenames} },
375                   {
376                     filerrors  => \@filerrors,
377                     source     => $filename,
378                     cardnumber => $cardnumber
379                   };
380                 $template->param( ERRORS => 1 );
381             }
382         }
383         else {
384             warn "Opening $source failed!";
385             $filerrors{'OPNERR'} = 1;
386             push my @filerrors, \%filerrors;
387             push @{ $count{filenames} },
388               {
389                 filerrors  => \@filerrors,
390                 source     => $filename,
391                 cardnumber => $cardnumber
392               };
393             $template->param( ERRORS => 1 );
394         }
395     }
396     else {
397         # The need for this seems a bit unlikely, however, to maximize error trapping it is included
398         warn "Missing "
399           . (
400             $cardnumber
401             ? "filename"
402             : ( $filename ? "cardnumber" : "cardnumber and filename" )
403           );
404         $filerrors{'CRDFIL'} = (
405             $cardnumber
406             ? "filename"
407             : ( $filename ? "cardnumber" : "cardnumber and filename" )
408         );
409         push my @filerrors, \%filerrors;
410         push @{ $count{filenames} },
411           {
412             filerrors  => \@filerrors,
413             source     => $filename,
414             cardnumber => $cardnumber
415           };
416         $template->param( ERRORS => 1 );
417     }
418     return (%count);
419 }
420
421 =head1 AUTHORS
422
423 Original contributor(s) undocumented
424
425 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
426 Image scaling/resizing contributed by the same.
427
428 =cut