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