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