Bugfix 2339 - Place hold button display with AllowOnShelfHolds OFF (Part 2)
[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 under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18 #
19 #
20 #
21
22 use File::Temp;
23 use File::Copy;
24 use CGI;
25 use GD;
26 use C4::Context;
27 use C4::Auth;
28 use C4::Output;
29 use C4::Members;
30 use C4::Debug;
31
32 my $input = new CGI;
33
34 my ($template, $loggedinuser, $cookie)
35         = get_template_and_user({template_name => "tools/picture-upload.tmpl",
36                                         query => $input,
37                                         type => "intranet",
38                                         authnotrequired => 0,
39                                         flagsrequired => { tools => 'batch_upload_patron_images'},
40                                         debug => 0,
41                                         });
42
43 my $filetype            = $input->param('filetype');
44 my $cardnumber          = $input->param('cardnumber');
45 my $uploadfilename      = $input->param('uploadfile');
46 my $uploadfile          = $input->upload('uploadfile');
47 my $borrowernumber      = $input->param('borrowernumber');
48 my $op                  = $input->param('op');
49
50 #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.
51 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
52 #       coded. -fbcit
53
54 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
55
56 =head1 NAME
57
58 picture-upload.p. - Script for handling uploading of both single and bulk patronimages and importing them into the database.
59
60 =head1 SYNOPSIS
61
62 picture-upload.pl
63
64 =head1 DESCRIPTION
65
66 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.
67 Files greater than 100K will be refused. Images should be 140x200 pixels. If they are larger they will be auto-resized to comply.
68
69 =cut
70
71 $debug and warn "Operation requested: $op";
72
73 my ( $total, $handled, @counts, $tempfile, $tfh );
74
75 if ( ($op eq 'Upload') && $uploadfile ) {       # Case is important in these operational values as the template must use case to be visually pleasing!
76     my $dirname = File::Temp::tempdir( CLEANUP => 1);
77     $debug and warn "dirname = $dirname";
78     my $filesuffix = $1 if $uploadfilename =~ m/(\..+)$/i;
79     ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
80     $debug and warn "tempfile = $tempfile";
81     my ( @directories, $errors );
82
83     $errors{'NOTZIP'} = 1 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
84     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
85     $errors{'EMPTYUPLOAD'} = 1 unless ( length( $uploadfile ) > 0 );
86
87     if ( %errors ) {
88         $template->param( ERRORS => [ \%errors ] );
89     } else {
90         while ( <$uploadfile> ) {
91             print $tfh $_;
92         }
93         close $tfh;
94         if ( $filetype eq 'zip' ) {
95             unless (system("unzip $tempfile -d $dirname") == 0) {
96                 $errors{'UZIPFAIL'} = $uploadfilename;
97                 $template->param( ERRORS => [ \%errors ] );
98                 output_html_with_http_headers $input, $cookie, $template->output;   # This error is fatal to the import, so bail out here
99                 exit;
100             }
101             push @directories, "$dirname";
102             foreach $recursive_dir ( @directories ) {
103                 opendir $dir, $recursive_dir;
104                 while ( my $entry = readdir $dir ) {
105                 push @directories, "$recursive_dir/$entry" if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
106                 $debug and warn "$recursive_dir/$entry";
107                 }   
108                 closedir $dir;
109             }       
110             my $results;
111             foreach my $dir ( @directories ) {
112                 $results = handle_dir( $dir, $filesuffix );
113                 $handled++ if $results == 1;
114             }
115             $total = scalar @directories;
116         } else {       #if ($filetype eq 'zip' )
117             $results = handle_dir( $dirname, $filesuffix );
118             $handled = 1;
119             $total = 1;
120         }
121
122         if ( %$results || %errors ) {
123             $template->param( ERRORS => [ \%$results ] );
124         } else {
125                         my $filecount;
126                         map {$filecount += $_->{count}} @counts;
127             $debug and warn "Total directories processed: $total";
128             $debug and warn "Total files processed: $filecount";
129             $template->param(
130                         TOTAL => $total,
131                         HANDLED => $handled,
132                         COUNTS => \@counts,
133                         TCOUNTS => ($filecount > 0 ? $filecount : undef),
134             );
135                         $template->param( borrowernumber => $borrowernumber ) if $borrowernumber;
136         }   
137     }
138 } elsif ( ($op eq 'Upload') && !$uploadfile ) {
139     warn "Problem uploading file or no file uploaded.";
140     $template->param(cardnumber => $cardnumber);
141     $template->param(filetype => $filetype);
142 } elsif ( $op eq 'Delete' ) {
143     my $dberror = RmPatronImage($cardnumber);
144         $debug and warn "Patron image deleted for $cardnumber";
145     warn "Database returned $dberror" if $dberror;
146 }
147 if ( $borrowernumber && !$errors && !$template->param('ERRORS') ) {
148     print $input->redirect ("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
149 } else {
150     output_html_with_http_headers $input, $cookie, $template->output;
151 }
152
153 sub handle_dir {
154     my ( $dir, $suffix ) = @_;
155     my $source;
156     $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
157     if ($suffix =~ m/zip/i) {     # If we were sent a zip file, process any included data/idlink.txt files 
158         my ( $file, $filename, $cardnumber );
159         $debug and warn "Passed a zip file.";
160         opendir my $dirhandle, $dir;
161         while ( my $filename = readdir $dirhandle ) {
162             $file = "$dir/$filename" if ($filename =~ m/datalink\.txt/i || $filename =~ m/idlink\.txt/i);
163         }
164         unless (open (FILE, $file)) { 
165                 warn "Opening $dir/$file failed!";
166                 $errors{'OPNLINK'} = $file;
167                 return $errors; # This error is fatal to the import of this directory contents, so bail and return the error to the caller
168         };
169
170         while (my $line = <FILE>) {
171             $debug and warn "Reading contents of $file";
172             chomp $line;
173             $debug and warn "Examining line: $line";
174             my $delim = ($line =~ /\t/) ? "\t" : ($line =~ /,/) ? "," : "";
175             $debug and warn "Delimeter is \'$delim\'";
176             unless ( $delim eq "," || $delim eq "\t" ) {
177                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
178                 $errors{'DELERR'} = 1;      # This error is fatal to the import of this directory contents, so bail and return the error to the caller
179                 return $errors;
180             }
181             ($cardnumber, $filename) = split $delim, $line;
182             $cardnumber =~ s/[\"\r\n]//g;  # remove offensive characters
183             $filename   =~ s/[\"\r\n\s]//g;
184             $debug and warn "Cardnumber: $cardnumber Filename: $filename";
185             $source = "$dir/$filename";
186             %counts = handle_file($cardnumber, $source, %counts);
187         }
188         close FILE;
189         closedir ($dirhandle);
190     } else {
191         $source = $tempfile;
192         %counts = handle_file($cardnumber, $source, %counts);
193     }
194 push @counts, \%counts;
195 return 1;
196 }
197
198 sub handle_file {
199     my ($cardnumber, $source, %count) = @_;
200     $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
201     $count{filenames} = () if !$count{filenames};
202     $count{source} = $source if !$count{source};
203     if ($cardnumber && $source) {     # Now process any imagefiles
204         my %filerrors;
205         my $filename;
206         if ($filetype eq 'image') {
207             $filename = $uploadfilename;
208         } else {
209             $filename = $1 if ($source =~ /\/([^\/]+)$/);
210         }
211         $debug and warn "Source: $source";
212         my $size = (stat($source))[7];
213             if ($size > 100000) {    # This check is necessary even with image resizing to avoid possible security/performance issues...
214                 $filerrors{'OVRSIZ'} = 1;
215                 push my @filerrors, \%filerrors;
216                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
217                 $template->param( ERRORS => 1 );
218                 return %count;    # this one is fatal so bail here...
219             }
220         my ($srcimage, $image);
221         if (open (IMG, "$source")) {
222             $srcimage = GD::Image->new(*IMG);
223             close (IMG);
224                         if (defined $srcimage) {
225                                 my $mimetype = 'image/jpeg';    # GD autodetects three basic image formats: PNG, JPEG, XPM; we will convert all to JPEG...
226                                 # Check the pixel size of the image we are about to import...
227                                 my ($width, $height) = $srcimage->getBounds();
228                                 $debug and warn "$filename is $width pix X $height pix.";
229                                 if ($width > 140 || $height > 200) {    # MAX pixel dims are 140 X 200...
230                                         $debug and warn "$filename exceeds the maximum pixel dimensions of 140 X 200. Resizing...";
231                                         my $percent_reduce;    # Percent we will reduce the image dimensions by...
232                                         if ($width > 140) {
233                                                 $percent_reduce = sprintf("%.5f",(140/$width));    # If the width is oversize, scale based on width overage...
234                                         } else {
235                                                 $percent_reduce = sprintf("%.5f",(200/$height));    # otherwise scale based on height overage.
236                                         }
237                                         my $width_reduce = sprintf("%.0f", ($width * $percent_reduce));
238                                         my $height_reduce = sprintf("%.0f", ($height * $percent_reduce));
239                                         $debug and warn "Reducing $filename by " . ($percent_reduce * 100) . "\% or to $width_reduce pix X $height_reduce pix";
240                                         $image = GD::Image->new($width_reduce, $height_reduce, 1); #'1' creates true color image...
241                                         $image->copyResampled($srcimage,0,0,0,0,$width_reduce,$height_reduce,$width,$height);
242                                         $imgfile = $image->jpeg(100);
243                                         $debug and warn "$filename is " . length($imgfile) . " bytes after resizing.";
244                                         undef $image;
245                                         undef $srcimage;    # This object can get big...
246                                 } else {
247                                         $image = $srcimage;
248                                         $imgfile = $image->jpeg();
249                                         $debug and warn "$filename is " . length($imgfile) . " bytes.";
250                                         undef $image;
251                                         undef $srcimage;    # This object can get big...
252                                 }
253                                 $debug and warn "Image is of mimetype $mimetype";
254                                 my $dberror = PutPatronImage($cardnumber,$mimetype, $imgfile) if $mimetype;
255                                 if ( !$dberror && $mimetype ) { # Errors from here on are fatal only to the import of a particular image, so don't bail, just note the error and keep going
256                                         $count{count}++;
257                                         push @{ $count{filenames} }, { source => $filename, cardnumber => $cardnumber };
258                                 } elsif ( $dberror ) {
259                                                 warn "Database returned error: $dberror";
260                                                 ($dberror =~ /patronimage_fk1/) ? $filerrors{'IMGEXISTS'} = 1 : $filerrors{'DBERR'} = 1;
261                                                 push my @filerrors, \%filerrors;
262                                                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
263                                                 $template->param( ERRORS => 1 );
264                                 } elsif ( !$mimetype ) {
265                                         warn "Unable to determine mime type of $filename. Please verify mimetype.";
266                                         $filerrors{'MIMERR'} = 1;
267                                         push my @filerrors, \%filerrors;
268                                         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
269                                         $template->param( ERRORS => 1 );
270                                 }
271                         } else {
272                                 warn "Contents of $filename corrupted!";
273                         #       $count{count}--;
274                                 $filerrors{'CORERR'} = 1;
275                                 push my @filerrors, \%filerrors;
276                                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
277                                 $template->param( ERRORS => 1 );
278                         }
279                 } else {
280                         warn "Opening $dir/$filename failed!";
281                         $filerrors{'OPNERR'} = 1;
282                         push my @filerrors, \%filerrors;
283                         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
284                         $template->param( ERRORS => 1 );
285                 }
286     } else {    # The need for this seems a bit unlikely, however, to maximize error trapping it is included
287         warn "Missing " . ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
288         $filerrors{'CRDFIL'} = ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename")); 
289         push my @filerrors, \%filerrors;
290                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
291         $template->param( ERRORS => 1 );
292     }
293     return (%count);
294 }
295
296 =back
297
298 =head1 AUTHORS
299
300 Original contributor(s) undocumented
301
302 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
303 Image scaling/resizing contributed by the same.
304
305 =cut