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>.
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'},
54 our $filetype = $input->param('filetype') || '';
55 my $cardnumber = $input->param('cardnumber');
56 our $uploadfilename = $input->param('uploadfile') || '';
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 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
69 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
77 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.
78 Files greater than 100K will be refused. Images should be 140x200 pixels. If they are larger they will be auto-resized to comply.
82 $debug and warn "Operation requested: $op";
84 my ( $total, $handled, $tempfile, $tfh );
88 # Case is important in these operational values as the template must use case to be visually pleasing!
89 if ( ( $op eq 'Upload' ) && $uploadfile ) {
91 output_and_exit
( $input, $cookie, $template, 'wrong_csrf_token' )
92 unless Koha
::Token
->new->check_csrf({
93 session_id
=> scalar $input->cookie('CGISESSID'),
94 token
=> scalar $input->param('csrf_token'),
97 my $dirname = File
::Temp
::tempdir
( CLEANUP
=> 1 );
98 $debug and warn "dirname = $dirname";
100 if ( $uploadfilename =~ m/(\..+)$/i ) {
103 ( $tfh, $tempfile ) =
104 File
::Temp
::tempfile
( SUFFIX
=> $filesuffix, UNLINK
=> 1 );
105 $debug and warn "tempfile = $tempfile";
106 my ( @directories, $results );
108 $errors{'NOTZIP'} = 1
109 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
110 $errors{'NOWRITETEMP'} = 1 unless ( -w
$dirname );
111 $errors{'EMPTYUPLOAD'} = 1 unless ( length($uploadfile) > 0 );
114 $template->param( ERRORS
=> [ \
%errors ] );
115 output_html_with_http_headers
$input, $cookie, $template->output;
118 while (<$uploadfile>) {
122 if ( $filetype eq 'zip' ) {
123 qx/unzip $tempfile -d $dirname/;
125 unless ( $exit_code == 0 ) {
126 $errors{'UZIPFAIL'} = $uploadfilename;
127 $template->param( ERRORS
=> [ \
%errors ] );
128 # This error is fatal to the import, so bail out here
129 output_html_with_http_headers
$input, $cookie, $template->output;
132 push @directories, "$dirname";
133 foreach my $recursive_dir (@directories) {
134 opendir RECDIR
, $recursive_dir;
135 while ( my $entry = readdir RECDIR
) {
136 push @directories, "$recursive_dir/$entry"
137 if ( -d
"$recursive_dir/$entry" and $entry !~ /^\
./ );
138 $debug and warn "$recursive_dir/$entry";
142 foreach my $dir (@directories) {
143 $results = handle_dir
( $dir, $filesuffix, $template );
144 $handled++ if $results == 1;
146 $total = scalar @directories;
149 #if ($filetype eq 'zip' )
150 $results = handle_dir
( $dirname, $filesuffix, $template, $cardnumber,
152 $handled++ if $results == 1;
156 if ( $results!=1 || %errors ) {
157 $template->param( ERRORS
=> [$results] );
161 map { $filecount += $_->{count
} } @counts;
162 $debug and warn "Total directories processed: $total";
163 $debug and warn "Total files processed: $filecount";
168 TCOUNTS
=> ( $filecount > 0 ?
$filecount : undef ),
170 $template->param( borrowernumber
=> $borrowernumber )
174 elsif ( ( $op eq 'Upload' ) && !$uploadfile ) {
175 warn "Problem uploading file or no file uploaded.";
176 $template->param( cardnumber
=> $cardnumber );
177 $template->param( filetype
=> $filetype );
179 elsif ( $op eq 'Delete' ) {
180 output_and_exit
( $input, $cookie, $template, 'wrong_csrf_token' )
181 unless Koha
::Token
->new->check_csrf({
182 session_id
=> scalar $input->cookie('CGISESSID'),
183 token
=> scalar $input->param('csrf_token'),
187 Koha
::Patron
::Images
->find( $borrowernumber )->delete;
189 if ( $@
or not $deleted ) {
190 warn "Image for patron '$borrowernumber' has not been deleted";
193 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
194 print $input->redirect(
195 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
199 csrf_token
=> Koha
::Token
->new->generate_csrf({
200 session_id
=> scalar $input->cookie('CGISESSID'),
203 output_html_with_http_headers
$input, $cookie, $template->output;
207 my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
208 my ( %counts, %direrrors );
209 $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
210 if ( $suffix =~ m/zip/i ) {
211 # If we were sent a zip file, process any included data/idlink.txt files
212 my ( $file, $filename );
214 $debug and warn "Passed a zip file.";
216 while ( my $filename = readdir DIR
) {
217 $file = "$dir/$filename"
218 if ( $filename =~ m/datalink\.txt/i
219 || $filename =~ m/idlink\.txt/i );
222 unless ( open( $fh, '<', $file ) ) {
223 warn "Opening $dir/$file failed!";
224 $direrrors{'OPNLINK'} = $file;
225 # This error is fatal to the import of this directory contents
226 # so bail and return the error to the caller
230 while ( my $line = <$fh> ) {
231 $debug and warn "Reading contents of $file";
233 $debug and warn "Examining line: $line";
234 my $delim = ( $line =~ /\t/ ) ?
"\t" : ( $line =~ /,/ ) ?
"," : "";
235 $debug and warn "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 $debug and warn "Cardnumber: $cardnumber Filename: $filename";
247 $source = "$dir/$filename";
248 %counts = handle_file
( $cardnumber, $source, $template, %counts );
254 %counts = handle_file
( $cardnumber, $source, $template, %counts );
256 push @counts, \
%counts;
261 my ( $cardnumber, $source, $template, %count ) = @_;
262 $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
263 $count{filenames
} = () if !$count{filenames
};
264 $count{source
} = $source if !$count{source
};
265 $count{count
} = 0 unless exists $count{count
};
268 if ( $filetype eq 'image' ) {
269 $filename = $uploadfilename;
272 $filename = $1 if ( $source && $source =~ /\/([^\
/]+)$/ );
274 if ( $cardnumber && $source ) {
275 # Now process any imagefiles
276 $debug and warn "Source: $source";
277 my $size = ( stat($source) )[7];
278 if ( $size > 550000 ) {
279 # This check is necessary even with image resizing to avoid possible security/performance issues...
280 $filerrors{'OVRSIZ'} = 1;
281 push my @filerrors, \
%filerrors;
282 push @
{ $count{filenames
} },
284 filerrors
=> \
@filerrors,
286 cardnumber
=> $cardnumber
288 $template->param( ERRORS
=> 1 );
289 # this one is fatal so bail here...
292 my ( $srcimage, $image );
293 if ( open( my $fh, '<', $source ) ) {
294 $srcimage = GD
::Image
->new($fh);
296 if ( defined $srcimage ) {
298 my $mimetype = 'image/png';
299 # GD autodetects three basic image formats: PNG, JPEG, XPM
300 # we will convert all to PNG which is lossless...
301 # Check the pixel size of the image we are about to import...
302 my ( $width, $height ) = $srcimage->getBounds();
303 $debug and warn "$filename is $width pix X $height pix.";
304 if ( $width > 200 || $height > 300 ) {
305 # MAX pixel dims are 200 X 300...
306 $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
307 # Percent we will reduce the image dimensions by...
309 if ( $width > 200 ) {
310 # If the width is oversize, scale based on width overage...
311 $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
314 # otherwise scale based on height overage.
315 $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
318 sprintf( "%.0f", ( $width * $percent_reduce ) );
320 sprintf( "%.0f", ( $height * $percent_reduce ) );
322 and warn "Reducing $filename by "
323 . ( $percent_reduce * 100 )
324 . "\% or to $width_reduce pix X $height_reduce pix";
325 #'1' creates true color image...
326 $image = GD
::Image
->new( $width_reduce, $height_reduce, 1 );
327 $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
328 $height_reduce, $width, $height );
329 $imgfile = $image->png();
331 and warn "$filename is "
333 . " bytes after resizing.";
335 undef $srcimage; # This object can get big...
339 $imgfile = $image->png();
341 and warn "$filename is " . length($imgfile) . " bytes.";
343 undef $srcimage; # This object can get big...
345 $debug and warn "Image is of mimetype $mimetype";
347 my $patron = Koha
::Patrons
->find({ cardnumber
=> $cardnumber });
349 my $image = $patron->image;
350 $image ||= Koha
::Patron
::Image
->new({ borrowernumber
=> $patron->borrowernumber });
352 mimetype
=> $mimetype,
353 imagefile
=> $imgfile,
355 eval { $image->store };
357 # Errors from here on are fatal only to the import of a particular image
358 #so don't bail, just note the error and keep going
359 warn "Database returned error: $@";
360 $filerrors{'DBERR'} = 1;
361 push my @filerrors, \
%filerrors;
362 push @
{ $count{filenames
} },
364 filerrors
=> \
@filerrors,
366 cardnumber
=> $cardnumber
368 $template->param( ERRORS
=> 1 );
371 push @
{ $count{filenames
} },
372 { source
=> $filename, cardnumber
=> $cardnumber };
375 warn "Patron with the cardnumber '$cardnumber' does not exist";
376 $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1;
377 push my @filerrors, \
%filerrors;
378 push @
{ $count{filenames
} },
380 filerrors
=> \
@filerrors,
382 cardnumber
=> $cardnumber
384 $template->param( ERRORS
=> 1 );
388 warn "Unable to determine mime type of $filename. Please verify mimetype.";
389 $filerrors{'MIMERR'} = 1;
390 push my @filerrors, \
%filerrors;
391 push @
{ $count{filenames
} },
393 filerrors
=> \
@filerrors,
395 cardnumber
=> $cardnumber
397 $template->param( ERRORS
=> 1 );
401 warn "Contents of $filename corrupted!";
403 $filerrors{'CORERR'} = 1;
404 push my @filerrors, \
%filerrors;
405 push @
{ $count{filenames
} },
407 filerrors
=> \
@filerrors,
409 cardnumber
=> $cardnumber
411 $template->param( ERRORS
=> 1 );
415 warn "Opening $source failed!";
416 $filerrors{'OPNERR'} = 1;
417 push my @filerrors, \
%filerrors;
418 push @
{ $count{filenames
} },
420 filerrors
=> \
@filerrors,
422 cardnumber
=> $cardnumber
424 $template->param( ERRORS
=> 1 );
428 # The need for this seems a bit unlikely, however, to maximize error trapping it is included
433 : ( $filename ?
"cardnumber" : "cardnumber and filename" )
435 $filerrors{'CRDFIL'} = (
438 : ( $filename ?
"cardnumber" : "cardnumber and filename" )
440 push my @filerrors, \
%filerrors;
441 push @
{ $count{filenames
} },
443 filerrors
=> \
@filerrors,
445 cardnumber
=> $cardnumber
447 $template->param( ERRORS
=> 1 );
454 Original contributor(s) undocumented
456 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
457 Image scaling/resizing contributed by the same.