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>.
29 use C4::Auth qw( get_template_and_user );
30 use C4::Output qw( output_and_exit output_html_with_http_headers );
35 use Koha::Patron::Images;
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");
46 my ($template, $loggedinuser, $cookie)
47 = get_template_and_user({template_name => "tools/picture-upload.tt",
50 flagsrequired => { tools => 'batch_upload_patron_images'},
53 our $filetype = $input->param('filetype') || '';
54 my $cardnumber = $input->param('cardnumber');
55 our $uploadfilename = $input->param('uploadfile') || $input->param('uploadfilename') || '';
56 my $uploadfiletext = $input->param('uploadfiletext') || '';
57 my $uploadfile = $input->upload('uploadfile');
58 my $borrowernumber = $input->param('borrowernumber');
59 my $op = $input->param('op') || '';
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
65 our $logger = Koha::Logger->get;
66 $logger->debug("Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename");
70 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
78 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.
79 Files greater than 100K will be refused. Images should be 140x200 pixels. If they are larger they will be auto-resized to comply.
83 my ( $total, $handled, $tempfile, $tfh );
87 # Case is important in these operational values as the template must use case to be visually pleasing!
88 if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) {
90 my $dirname = File::Temp::tempdir( CLEANUP => 1 );
92 if ( $uploadfilename =~ m/(\..+)$/i ) {
96 File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
97 my ( @directories, $results );
99 $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
100 if ( length($uploadfiletext) == 0 ) {
101 $errors{'NOTZIP'} = 1
102 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
103 $errors{'EMPTYUPLOAD'} = 1 unless ( length($uploadfile) > 0 );
107 $template->param( ERRORS => [ \%errors ] );
108 output_html_with_http_headers $input, $cookie, $template->output;
112 if ( length($uploadfiletext) == 0 ) {
113 while (<$uploadfile>) {
117 # data type controlled in toDataURL() in template
118 if ( $uploadfiletext =~ /data:image\/jpeg;base64,(.*)/ ) {
119 my $encoded_picture = $1;
120 my $decoded_picture = decode_base64($encoded_picture);
121 print $tfh $decoded_picture;
123 $errors{'BADPICTUREDATA'} = 1;
124 $template->param( ERRORS => [ \%errors ] );
125 output_html_with_http_headers $input, $cookie, $template->output;
130 if ( $filetype eq 'zip' ) {
131 qx/unzip $tempfile -d $dirname/;
133 unless ( $exit_code == 0 ) {
134 $errors{'UZIPFAIL'} = $uploadfilename;
135 $template->param( ERRORS => [ \%errors ] );
136 # This error is fatal to the import, so bail out here
137 output_html_with_http_headers $input, $cookie, $template->output;
140 push @directories, "$dirname";
141 foreach my $recursive_dir (@directories) {
143 opendir $recdir_h, $recursive_dir;
144 while ( my $entry = readdir $recdir_h ) {
145 push @directories, "$recursive_dir/$entry"
146 if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
150 foreach my $dir (@directories) {
151 $results = handle_dir( $dir, $filesuffix, $template );
152 $handled++ if $results == 1;
154 $total = scalar @directories;
157 #if ($filetype eq 'zip' )
158 $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber,
160 $handled++ if $results == 1;
164 if ( $results!=1 || %errors ) {
165 $template->param( ERRORS => [$results] );
169 map { $filecount += $_->{count} } @counts;
170 $logger->debug("Total directories processed: $total");
171 $logger->debug("Total files processed: $filecount");
176 TCOUNTS => ( $filecount > 0 ? $filecount : undef ),
178 $template->param( borrowernumber => $borrowernumber )
182 elsif ( ( $op eq 'cud-Upload' ) && !$uploadfile ) {
183 warn "Problem uploading file or no file uploaded.";
184 $template->param( cardnumber => $cardnumber );
185 $template->param( filetype => $filetype );
187 elsif ( $op eq 'cud-Delete' ) {
189 Koha::Patron::Images->find( $borrowernumber )->delete;
191 if ( $@ or not $deleted ) {
192 warn "Image for patron '$borrowernumber' has not been deleted";
195 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
196 print $input->redirect(
197 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
200 output_html_with_http_headers $input, $cookie, $template->output;
204 my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
205 my ( %counts, %direrrors );
206 $logger->debug("Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix");
207 if ( $suffix =~ m/zip/i ) {
208 # If we were sent a zip file, process any included data/idlink.txt files
209 my ( $file, $filename );
211 $logger->debug("Passed a zip file.");
213 opendir $dir_h, $dir;
214 while ( my $filename = readdir $dir_h ) {
215 $file = "$dir/$filename"
216 if ( $filename =~ m/datalink\.txt/i
217 || $filename =~ m/idlink\.txt/i );
220 unless ( open( $fh, '<', $file ) ) {
221 warn "Opening $dir/$file failed!";
222 $direrrors{'OPNLINK'} = $file;
223 # This error is fatal to the import of this directory contents
224 # so bail and return the error to the caller
230 foreach my $line (@lines) {
231 $logger->debug("Reading contents of $file");
233 $logger->debug("Examining line: $line");
234 my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
235 $logger->debug("Delimeter is \'$delim\'");
236 unless ( $delim eq "," || $delim eq "\t" ) {
237 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
238 $direrrors{'DELERR'} = 1;
239 # This error is fatal to the import of this directory contents
240 # so bail and return the error to the caller
243 ( $cardnumber, $filename ) = split $delim, $line;
244 $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
245 $filename =~ s/[\"\r\n\s]//g;
246 $logger->debug("Cardnumber: $cardnumber Filename: $filename");
247 $source = "$dir/$filename";
248 %counts = handle_file( $cardnumber, $source, $template, %counts );
253 %counts = handle_file( $cardnumber, $source, $template, %counts );
255 push @counts, \%counts;
260 my ( $cardnumber, $source, $template, %count ) = @_;
261 $logger->debug("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};
267 if ( $filetype eq 'image' ) {
268 $filename = $uploadfilename;
271 $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
273 if ( $cardnumber && $source ) {
274 # Now process any imagefiles
275 $logger->debug("Source: $source");
276 my $size = ( stat($source) )[7];
277 if ( $size > 2097152 ) {
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} },
283 filerrors => \@filerrors,
285 cardnumber => $cardnumber
287 $template->param( ERRORS => 1 );
288 # this one is fatal so bail here...
291 my ( $srcimage, $image );
292 if ( open( my $fh, '<', $source ) ) {
293 $srcimage = GD::Image->new($fh);
295 if ( defined $srcimage ) {
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 $logger->debug("$filename is $width pix X $height pix.");
303 if ( $width > 200 || $height > 300 ) {
304 # MAX pixel dims are 200 X 300...
305 $logger->debug("$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...");
306 # Percent we will reduce the image dimensions by...
308 if ( $width > 200 ) {
309 # If the width is oversize, scale based on width overage...
310 $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
313 # otherwise scale based on height overage.
314 $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
317 sprintf( "%.0f", ( $width * $percent_reduce ) );
319 sprintf( "%.0f", ( $height * $percent_reduce ) );
320 $logger->debug("Reducing $filename by "
321 . ( $percent_reduce * 100 )
322 . "\% or to $width_reduce pix X $height_reduce pix");
323 #'1' creates true color image...
324 $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
325 $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
326 $height_reduce, $width, $height );
327 $imgfile = $image->png();
328 $logger->debug("$filename is "
330 . " bytes after resizing.");
332 undef $srcimage; # This object can get big...
336 $imgfile = $image->png();
337 $logger->debug("$filename is " . length($imgfile) . " bytes.");
339 undef $srcimage; # This object can get big...
341 $logger->debug("Image is of mimetype $mimetype");
343 my $patron = Koha::Patrons->find({ cardnumber => $cardnumber });
345 my $image = $patron->image;
346 $image ||= Koha::Patron::Image->new({ borrowernumber => $patron->borrowernumber });
348 mimetype => $mimetype,
349 imagefile => $imgfile,
351 eval { $image->store };
353 # Errors from here on are fatal only to the import of a particular image
354 #so don't bail, just note the error and keep going
355 warn "Database returned error: $@";
356 $filerrors{'DBERR'} = 1;
357 push my @filerrors, \%filerrors;
358 push @{ $count{filenames} },
360 filerrors => \@filerrors,
362 cardnumber => $cardnumber
364 $template->param( ERRORS => 1 );
367 push @{ $count{filenames} },
368 { source => $filename, cardnumber => $cardnumber };
371 warn "Patron with the cardnumber '$cardnumber' does not exist";
372 $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1;
373 push my @filerrors, \%filerrors;
374 push @{ $count{filenames} },
376 filerrors => \@filerrors,
378 cardnumber => $cardnumber
380 $template->param( ERRORS => 1 );
384 warn "Unable to determine mime type of $filename. Please verify mimetype.";
385 $filerrors{'MIMERR'} = 1;
386 push my @filerrors, \%filerrors;
387 push @{ $count{filenames} },
389 filerrors => \@filerrors,
391 cardnumber => $cardnumber
393 $template->param( ERRORS => 1 );
397 warn "Contents of $filename corrupted!";
399 $filerrors{'CORERR'} = 1;
400 push my @filerrors, \%filerrors;
401 push @{ $count{filenames} },
403 filerrors => \@filerrors,
405 cardnumber => $cardnumber
407 $template->param( ERRORS => 1 );
411 warn "Opening $source failed!";
412 $filerrors{'OPNERR'} = 1;
413 push my @filerrors, \%filerrors;
414 push @{ $count{filenames} },
416 filerrors => \@filerrors,
418 cardnumber => $cardnumber
420 $template->param( ERRORS => 1 );
424 # The need for this seems a bit unlikely, however, to maximize error trapping it is included
429 : ( $filename ? "cardnumber" : "cardnumber and filename" )
431 $filerrors{'CRDFIL'} = (
434 : ( $filename ? "cardnumber" : "cardnumber and filename" )
436 push my @filerrors, \%filerrors;
437 push @{ $count{filenames} },
439 filerrors => \@filerrors,
441 cardnumber => $cardnumber
443 $template->param( ERRORS => 1 );
450 Original contributor(s) undocumented
452 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
453 Image scaling/resizing contributed by the same.