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