Bug 15635: Koha::Patron::Images - Remove RmPatronImage
[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 $deleted = eval {
164         Koha::Patron::Images->find( $borrowernumber )->delete;
165     };
166     if ( $@ or not $deleted ) {
167         warn "Image for patron '$borrowernumber' has not been deleted";
168     }
169 }
170 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
171     print $input->redirect(
172         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
173 }
174 else {
175     output_html_with_http_headers $input, $cookie, $template->output;
176 }
177
178 sub handle_dir {
179     my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
180     my ( %counts, %direrrors );
181     $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
182     if ( $suffix =~ m/zip/i ) {
183         # If we were sent a zip file, process any included data/idlink.txt files
184         my ( $file, $filename );
185         undef $cardnumber;
186         $debug and warn "Passed a zip file.";
187         opendir DIR, $dir;
188         while ( my $filename = readdir DIR ) {
189             $file = "$dir/$filename"
190               if ( $filename =~ m/datalink\.txt/i
191                 || $filename =~ m/idlink\.txt/i );
192         }
193         unless ( open( FILE, $file ) ) {
194             warn "Opening $dir/$file failed!";
195             $direrrors{'OPNLINK'} = $file;
196             # This error is fatal to the import of this directory contents
197             # so bail and return the error to the caller
198             return \%direrrors;
199         }
200
201         while ( my $line = <FILE> ) {
202             $debug and warn "Reading contents of $file";
203             chomp $line;
204             $debug and warn "Examining line: $line";
205             my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
206             $debug and warn "Delimeter is \'$delim\'";
207             unless ( $delim eq "," || $delim eq "\t" ) {
208                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
209                 $direrrors{'DELERR'} = 1;
210                 # This error is fatal to the import of this directory contents
211                 # so bail and return the error to the caller
212                 return \%direrrors;
213             }
214             ( $cardnumber, $filename ) = split $delim, $line;
215             $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
216             $filename   =~ s/[\"\r\n\s]//g;
217             $debug and warn "Cardnumber: $cardnumber Filename: $filename";
218             $source = "$dir/$filename";
219             %counts = handle_file( $cardnumber, $source, $template, %counts );
220         }
221         close FILE;
222         closedir DIR;
223     }
224     else {
225         %counts = handle_file( $cardnumber, $source, $template, %counts );
226     }
227     push @counts, \%counts;
228     return 1;
229 }
230
231 sub handle_file {
232     my ( $cardnumber, $source, $template, %count ) = @_;
233     $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
234     $count{filenames} = ()      if !$count{filenames};
235     $count{source}    = $source if !$count{source};
236     $count{count}     = 0       unless exists $count{count};
237     my %filerrors;
238     my $filename;
239     if ( $filetype eq 'image' ) {
240         $filename = $uploadfilename;
241     }
242     else {
243         $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
244     }
245     if ( $cardnumber && $source ) {
246         # Now process any imagefiles
247         $debug and warn "Source: $source";
248         my $size = ( stat($source) )[7];
249         if ( $size > 550000 ) {
250             # This check is necessary even with image resizing to avoid possible security/performance issues...
251             $filerrors{'OVRSIZ'} = 1;
252             push my @filerrors, \%filerrors;
253             push @{ $count{filenames} },
254               {
255                 filerrors  => \@filerrors,
256                 source     => $filename,
257                 cardnumber => $cardnumber
258               };
259             $template->param( ERRORS => 1 );
260             # this one is fatal so bail here...
261             return %count;
262         }
263         my ( $srcimage, $image );
264         if ( open( IMG, "$source" ) ) {
265             $srcimage = GD::Image->new(*IMG);
266             close(IMG);
267             if ( defined $srcimage ) {
268                 my $imgfile;
269                 my $mimetype = 'image/png';
270                 # GD autodetects three basic image formats: PNG, JPEG, XPM
271                 # we will convert all to PNG which is lossless...
272                 # Check the pixel size of the image we are about to import...
273                 my ( $width, $height ) = $srcimage->getBounds();
274                 $debug and warn "$filename is $width pix X $height pix.";
275                 if ( $width > 200 || $height > 300 ) {
276                     # MAX pixel dims are 200 X 300...
277                     $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
278                     # Percent we will reduce the image dimensions by...
279                     my $percent_reduce;
280                     if ( $width > 200 ) {
281                         # If the width is oversize, scale based on width overage...
282                         $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
283                     }
284                     else {
285                         # otherwise scale based on height overage.
286                         $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
287                     }
288                     my $width_reduce =
289                       sprintf( "%.0f", ( $width * $percent_reduce ) );
290                     my $height_reduce =
291                       sprintf( "%.0f", ( $height * $percent_reduce ) );
292                     $debug
293                       and warn "Reducing $filename by "
294                       . ( $percent_reduce * 100 )
295                       . "\% or to $width_reduce pix X $height_reduce pix";
296                     #'1' creates true color image...
297                     $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
298                     $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
299                         $height_reduce, $width, $height );
300                     $imgfile = $image->png();
301                     $debug
302                       and warn "$filename is "
303                       . length($imgfile)
304                       . " bytes after resizing.";
305                     undef $image;
306                     undef $srcimage; # This object can get big...
307                 }
308                 else {
309                     $image   = $srcimage;
310                     $imgfile = $image->png();
311                     $debug
312                       and warn "$filename is " . length($imgfile) . " bytes.";
313                     undef $image;
314                     undef $srcimage; # This object can get big...
315                 }
316                 $debug and warn "Image is of mimetype $mimetype";
317                 my $dberror;
318                 if ($mimetype) {
319                     my $patron = Koha::Patrons->find({ cardnumber => $cardnumber });
320                     if ( $patron ) {
321                         my $image = $patron->image;
322                         $image ||= Koha::Patron::Image->new({ borrowernumber => $patron->borrowernumber });
323                         $image->set({
324                             mimetype => $mimetype,
325                             imagefile => $imgfile,
326                         });
327                         eval { $image->store };
328                         if ( $@ ) {
329                             # Errors from here on are fatal only to the import of a particular image
330                             #so don't bail, just note the error and keep going
331                             warn "Database returned error: $@";
332                             $filerrors{'DBERR'} = 1;
333                             push my @filerrors, \%filerrors;
334                             push @{ $count{filenames} },
335                               {
336                                 filerrors  => \@filerrors,
337                                 source     => $filename,
338                                 cardnumber => $cardnumber
339                               };
340                             $template->param( ERRORS => 1 );
341                         } else {
342                             $count{count}++;
343                             push @{ $count{filenames} },
344                               { source => $filename, cardnumber => $cardnumber };
345                         }
346                     } else {
347                         warn "Patron with the cardnumber '$cardnumber' does not exist";
348                         $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1;
349                         push my @filerrors, \%filerrors;
350                         push @{ $count{filenames} },
351                           {
352                             filerrors  => \@filerrors,
353                             source     => $filename,
354                             cardnumber => $cardnumber
355                           };
356                         $template->param( ERRORS => 1 );
357                     }
358                 }
359                 else {
360                     warn "Unable to determine mime type of $filename. Please verify mimetype.";
361                     $filerrors{'MIMERR'} = 1;
362                     push my @filerrors, \%filerrors;
363                     push @{ $count{filenames} },
364                       {
365                         filerrors  => \@filerrors,
366                         source     => $filename,
367                         cardnumber => $cardnumber
368                       };
369                     $template->param( ERRORS => 1 );
370                 }
371             }
372             else {
373                 warn "Contents of $filename corrupted!";
374                 #$count{count}--;
375                 $filerrors{'CORERR'} = 1;
376                 push my @filerrors, \%filerrors;
377                 push @{ $count{filenames} },
378                   {
379                     filerrors  => \@filerrors,
380                     source     => $filename,
381                     cardnumber => $cardnumber
382                   };
383                 $template->param( ERRORS => 1 );
384             }
385         }
386         else {
387             warn "Opening $source failed!";
388             $filerrors{'OPNERR'} = 1;
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     }
399     else {
400         # The need for this seems a bit unlikely, however, to maximize error trapping it is included
401         warn "Missing "
402           . (
403             $cardnumber
404             ? "filename"
405             : ( $filename ? "cardnumber" : "cardnumber and filename" )
406           );
407         $filerrors{'CRDFIL'} = (
408             $cardnumber
409             ? "filename"
410             : ( $filename ? "cardnumber" : "cardnumber and filename" )
411         );
412         push my @filerrors, \%filerrors;
413         push @{ $count{filenames} },
414           {
415             filerrors  => \@filerrors,
416             source     => $filename,
417             cardnumber => $cardnumber
418           };
419         $template->param( ERRORS => 1 );
420     }
421     return (%count);
422 }
423
424 =head1 AUTHORS
425
426 Original contributor(s) undocumented
427
428 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
429 Image scaling/resizing contributed by the same.
430
431 =cut