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