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