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