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