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