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>.
28 use Digest::MD5 qw(md5_base64);
36 use Koha::Patron::Image;
37 use Koha::Patron::Images;
42 my ($template, $loggedinuser, $cookie)
43 = get_template_and_user({template_name => "tools/picture-upload.tt",
47 flagsrequired => { tools => 'batch_upload_patron_images'},
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') || '';
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
62 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
66 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
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.
79 $debug and warn "Operation requested: $op";
81 my ( $total, $handled, $tempfile, $tfh );
85 # Case is important in these operational values as the template must use case to be visually pleasing!
86 if ( ( $op eq 'Upload' ) && $uploadfile ) {
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'),
95 my $dirname = File::Temp::tempdir( CLEANUP => 1 );
96 $debug and warn "dirname = $dirname";
98 if ( $uploadfilename =~ m/(\..+)$/i ) {
101 ( $tfh, $tempfile ) =
102 File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
103 $debug and warn "tempfile = $tempfile";
104 my ( @directories, $results );
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 );
112 $template->param( ERRORS => [ \%errors ] );
113 output_html_with_http_headers $input, $cookie, $template->output;
116 while (<$uploadfile>) {
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;
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";
138 foreach my $dir (@directories) {
139 $results = handle_dir( $dir, $filesuffix, $template );
140 $handled++ if $results == 1;
142 $total = scalar @directories;
145 #if ($filetype eq 'zip' )
146 $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber,
148 $handled++ if $results == 1;
152 if ( $results!=1 || %errors ) {
153 $template->param( ERRORS => [$results] );
157 map { $filecount += $_->{count} } @counts;
158 $debug and warn "Total directories processed: $total";
159 $debug and warn "Total files processed: $filecount";
164 TCOUNTS => ( $filecount > 0 ? $filecount : undef ),
166 $template->param( borrowernumber => $borrowernumber )
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 );
175 elsif ( $op eq 'Delete' ) {
177 Koha::Patron::Images->find( $borrowernumber )->delete;
179 if ( $@ or not $deleted ) {
180 warn "Image for patron '$borrowernumber' has not been deleted";
183 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
184 print $input->redirect(
185 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
189 csrf_token => Koha::Token->new->generate_csrf({
190 id => C4::Context->userenv->{id},
191 secret => md5_base64( C4::Context->config('pass') ),
194 output_html_with_http_headers $input, $cookie, $template->output;
198 my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
199 my ( %counts, %direrrors );
200 $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
201 if ( $suffix =~ m/zip/i ) {
202 # If we were sent a zip file, process any included data/idlink.txt files
203 my ( $file, $filename );
205 $debug and warn "Passed a zip file.";
207 while ( my $filename = readdir DIR ) {
208 $file = "$dir/$filename"
209 if ( $filename =~ m/datalink\.txt/i
210 || $filename =~ m/idlink\.txt/i );
212 unless ( open( FILE, $file ) ) {
213 warn "Opening $dir/$file failed!";
214 $direrrors{'OPNLINK'} = $file;
215 # This error is fatal to the import of this directory contents
216 # so bail and return the error to the caller
220 while ( my $line = <FILE> ) {
221 $debug and warn "Reading contents of $file";
223 $debug and warn "Examining line: $line";
224 my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
225 $debug and warn "Delimeter is \'$delim\'";
226 unless ( $delim eq "," || $delim eq "\t" ) {
227 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
228 $direrrors{'DELERR'} = 1;
229 # This error is fatal to the import of this directory contents
230 # so bail and return the error to the caller
233 ( $cardnumber, $filename ) = split $delim, $line;
234 $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
235 $filename =~ s/[\"\r\n\s]//g;
236 $debug and warn "Cardnumber: $cardnumber Filename: $filename";
237 $source = "$dir/$filename";
238 %counts = handle_file( $cardnumber, $source, $template, %counts );
244 %counts = handle_file( $cardnumber, $source, $template, %counts );
246 push @counts, \%counts;
251 my ( $cardnumber, $source, $template, %count ) = @_;
252 $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
253 $count{filenames} = () if !$count{filenames};
254 $count{source} = $source if !$count{source};
255 $count{count} = 0 unless exists $count{count};
258 if ( $filetype eq 'image' ) {
259 $filename = $uploadfilename;
262 $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
264 if ( $cardnumber && $source ) {
265 # Now process any imagefiles
266 $debug and warn "Source: $source";
267 my $size = ( stat($source) )[7];
268 if ( $size > 550000 ) {
269 # This check is necessary even with image resizing to avoid possible security/performance issues...
270 $filerrors{'OVRSIZ'} = 1;
271 push my @filerrors, \%filerrors;
272 push @{ $count{filenames} },
274 filerrors => \@filerrors,
276 cardnumber => $cardnumber
278 $template->param( ERRORS => 1 );
279 # this one is fatal so bail here...
282 my ( $srcimage, $image );
283 if ( open( IMG, "$source" ) ) {
284 $srcimage = GD::Image->new(*IMG);
286 if ( defined $srcimage ) {
288 my $mimetype = 'image/png';
289 # GD autodetects three basic image formats: PNG, JPEG, XPM
290 # we will convert all to PNG which is lossless...
291 # Check the pixel size of the image we are about to import...
292 my ( $width, $height ) = $srcimage->getBounds();
293 $debug and warn "$filename is $width pix X $height pix.";
294 if ( $width > 200 || $height > 300 ) {
295 # MAX pixel dims are 200 X 300...
296 $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
297 # Percent we will reduce the image dimensions by...
299 if ( $width > 200 ) {
300 # If the width is oversize, scale based on width overage...
301 $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
304 # otherwise scale based on height overage.
305 $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
308 sprintf( "%.0f", ( $width * $percent_reduce ) );
310 sprintf( "%.0f", ( $height * $percent_reduce ) );
312 and warn "Reducing $filename by "
313 . ( $percent_reduce * 100 )
314 . "\% or to $width_reduce pix X $height_reduce pix";
315 #'1' creates true color image...
316 $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
317 $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
318 $height_reduce, $width, $height );
319 $imgfile = $image->png();
321 and warn "$filename is "
323 . " bytes after resizing.";
325 undef $srcimage; # This object can get big...
329 $imgfile = $image->png();
331 and warn "$filename is " . length($imgfile) . " bytes.";
333 undef $srcimage; # This object can get big...
335 $debug and warn "Image is of mimetype $mimetype";
338 my $patron = Koha::Patrons->find({ cardnumber => $cardnumber });
340 my $image = $patron->image;
341 $image ||= Koha::Patron::Image->new({ borrowernumber => $patron->borrowernumber });
343 mimetype => $mimetype,
344 imagefile => $imgfile,
346 eval { $image->store };
348 # Errors from here on are fatal only to the import of a particular image
349 #so don't bail, just note the error and keep going
350 warn "Database returned error: $@";
351 $filerrors{'DBERR'} = 1;
352 push my @filerrors, \%filerrors;
353 push @{ $count{filenames} },
355 filerrors => \@filerrors,
357 cardnumber => $cardnumber
359 $template->param( ERRORS => 1 );
362 push @{ $count{filenames} },
363 { source => $filename, cardnumber => $cardnumber };
366 warn "Patron with the cardnumber '$cardnumber' does not exist";
367 $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1;
368 push my @filerrors, \%filerrors;
369 push @{ $count{filenames} },
371 filerrors => \@filerrors,
373 cardnumber => $cardnumber
375 $template->param( ERRORS => 1 );
379 warn "Unable to determine mime type of $filename. Please verify mimetype.";
380 $filerrors{'MIMERR'} = 1;
381 push my @filerrors, \%filerrors;
382 push @{ $count{filenames} },
384 filerrors => \@filerrors,
386 cardnumber => $cardnumber
388 $template->param( ERRORS => 1 );
392 warn "Contents of $filename corrupted!";
394 $filerrors{'CORERR'} = 1;
395 push my @filerrors, \%filerrors;
396 push @{ $count{filenames} },
398 filerrors => \@filerrors,
400 cardnumber => $cardnumber
402 $template->param( ERRORS => 1 );
406 warn "Opening $source failed!";
407 $filerrors{'OPNERR'} = 1;
408 push my @filerrors, \%filerrors;
409 push @{ $count{filenames} },
411 filerrors => \@filerrors,
413 cardnumber => $cardnumber
415 $template->param( ERRORS => 1 );
419 # The need for this seems a bit unlikely, however, to maximize error trapping it is included
424 : ( $filename ? "cardnumber" : "cardnumber and filename" )
426 $filerrors{'CRDFIL'} = (
429 : ( $filename ? "cardnumber" : "cardnumber and filename" )
431 push my @filerrors, \%filerrors;
432 push @{ $count{filenames} },
434 filerrors => \@filerrors,
436 cardnumber => $cardnumber
438 $template->param( ERRORS => 1 );
445 Original contributor(s) undocumented
447 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
448 Image scaling/resizing contributed by the same.