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