Bug 17663: Forgotten userpermissions from bug 14686
[koha.git] / tools / picture-upload.pl
blob9892eb5d17834d1cf5485d8f5710cd9701c3a18a
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 use Koha::Patrons;
35 use Koha::Patron::Image;
36 use Koha::Patron::Images;
38 my $input = new CGI;
40 my ($template, $loggedinuser, $cookie)
41 = get_template_and_user({template_name => "tools/picture-upload.tt",
42 query => $input,
43 type => "intranet",
44 authnotrequired => 0,
45 flagsrequired => { tools => 'batch_upload_patron_images'},
46 debug => 0,
47 });
49 our $filetype = $input->param('filetype') || '';
50 my $cardnumber = $input->param('cardnumber');
51 our $uploadfilename = $input->param('uploadfile') || '';
52 my $uploadfile = $input->upload('uploadfile');
53 my $borrowernumber = $input->param('borrowernumber');
54 my $op = $input->param('op') || '';
56 #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.
57 # Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
58 # coded. -fbcit
60 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
62 =head1 NAME
64 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
66 =head1 SYNOPSIS
68 picture-upload.pl
70 =head1 DESCRIPTION
72 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.
73 Files greater than 100K will be refused. Images should be 140x200 pixels. If they are larger they will be auto-resized to comply.
75 =cut
77 $debug and warn "Operation requested: $op";
79 my ( $total, $handled, $tempfile, $tfh );
80 our @counts = ();
81 our %errors = ();
83 # Case is important in these operational values as the template must use case to be visually pleasing!
84 if ( ( $op eq 'Upload' ) && $uploadfile ) {
85 my $dirname = File::Temp::tempdir( CLEANUP => 1 );
86 $debug and warn "dirname = $dirname";
87 my $filesuffix;
88 if ( $uploadfilename =~ m/(\..+)$/i ) {
89 $filesuffix = $1;
91 ( $tfh, $tempfile ) =
92 File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
93 $debug and warn "tempfile = $tempfile";
94 my ( @directories, $results );
96 $errors{'NOTZIP'} = 1
97 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
98 $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
99 $errors{'EMPTYUPLOAD'} = 1 unless ( length($uploadfile) > 0 );
101 if (%errors) {
102 $template->param( ERRORS => [ \%errors ] );
103 output_html_with_http_headers $input, $cookie, $template->output;
104 exit;
106 while (<$uploadfile>) {
107 print $tfh $_;
109 close $tfh;
110 if ( $filetype eq 'zip' ) {
111 unless ( system( "unzip", $tempfile, '-d', $dirname ) == 0 ) {
112 $errors{'UZIPFAIL'} = $uploadfilename;
113 $template->param( ERRORS => [ \%errors ] );
114 # This error is fatal to the import, so bail out here
115 output_html_with_http_headers $input, $cookie, $template->output;
116 exit;
118 push @directories, "$dirname";
119 foreach my $recursive_dir (@directories) {
120 opendir RECDIR, $recursive_dir;
121 while ( my $entry = readdir RECDIR ) {
122 push @directories, "$recursive_dir/$entry"
123 if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
124 $debug and warn "$recursive_dir/$entry";
126 closedir RECDIR;
128 foreach my $dir (@directories) {
129 $results = handle_dir( $dir, $filesuffix, $template );
130 $handled++ if $results == 1;
132 $total = scalar @directories;
134 else {
135 #if ($filetype eq 'zip' )
136 $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber,
137 $tempfile );
138 $handled++ if $results == 1;
139 $total = 1;
142 if ( $results!=1 || %errors ) {
143 $template->param( ERRORS => [$results] );
145 else {
146 my $filecount;
147 map { $filecount += $_->{count} } @counts;
148 $debug and warn "Total directories processed: $total";
149 $debug and warn "Total files processed: $filecount";
150 $template->param(
151 TOTAL => $total,
152 HANDLED => $handled,
153 COUNTS => \@counts,
154 TCOUNTS => ( $filecount > 0 ? $filecount : undef ),
156 $template->param( borrowernumber => $borrowernumber )
157 if $borrowernumber;
160 elsif ( ( $op eq 'Upload' ) && !$uploadfile ) {
161 warn "Problem uploading file or no file uploaded.";
162 $template->param( cardnumber => $cardnumber );
163 $template->param( filetype => $filetype );
165 elsif ( $op eq 'Delete' ) {
166 my $deleted = eval {
167 Koha::Patron::Images->find( $borrowernumber )->delete;
169 if ( $@ or not $deleted ) {
170 warn "Image for patron '$borrowernumber' has not been deleted";
173 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
174 print $input->redirect(
175 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
177 else {
178 output_html_with_http_headers $input, $cookie, $template->output;
181 sub handle_dir {
182 my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
183 my ( %counts, %direrrors );
184 $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
185 if ( $suffix =~ m/zip/i ) {
186 # If we were sent a zip file, process any included data/idlink.txt files
187 my ( $file, $filename );
188 undef $cardnumber;
189 $debug and warn "Passed a zip file.";
190 opendir DIR, $dir;
191 while ( my $filename = readdir DIR ) {
192 $file = "$dir/$filename"
193 if ( $filename =~ m/datalink\.txt/i
194 || $filename =~ m/idlink\.txt/i );
196 unless ( open( FILE, $file ) ) {
197 warn "Opening $dir/$file failed!";
198 $direrrors{'OPNLINK'} = $file;
199 # This error is fatal to the import of this directory contents
200 # so bail and return the error to the caller
201 return \%direrrors;
204 while ( my $line = <FILE> ) {
205 $debug and warn "Reading contents of $file";
206 chomp $line;
207 $debug and warn "Examining line: $line";
208 my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
209 $debug and warn "Delimeter is \'$delim\'";
210 unless ( $delim eq "," || $delim eq "\t" ) {
211 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
212 $direrrors{'DELERR'} = 1;
213 # This error is fatal to the import of this directory contents
214 # so bail and return the error to the caller
215 return \%direrrors;
217 ( $cardnumber, $filename ) = split $delim, $line;
218 $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
219 $filename =~ s/[\"\r\n\s]//g;
220 $debug and warn "Cardnumber: $cardnumber Filename: $filename";
221 $source = "$dir/$filename";
222 %counts = handle_file( $cardnumber, $source, $template, %counts );
224 close FILE;
225 closedir DIR;
227 else {
228 %counts = handle_file( $cardnumber, $source, $template, %counts );
230 push @counts, \%counts;
231 return 1;
234 sub handle_file {
235 my ( $cardnumber, $source, $template, %count ) = @_;
236 $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
237 $count{filenames} = () if !$count{filenames};
238 $count{source} = $source if !$count{source};
239 $count{count} = 0 unless exists $count{count};
240 my %filerrors;
241 my $filename;
242 if ( $filetype eq 'image' ) {
243 $filename = $uploadfilename;
245 else {
246 $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
248 if ( $cardnumber && $source ) {
249 # Now process any imagefiles
250 $debug and warn "Source: $source";
251 my $size = ( stat($source) )[7];
252 if ( $size > 550000 ) {
253 # This check is necessary even with image resizing to avoid possible security/performance issues...
254 $filerrors{'OVRSIZ'} = 1;
255 push my @filerrors, \%filerrors;
256 push @{ $count{filenames} },
258 filerrors => \@filerrors,
259 source => $filename,
260 cardnumber => $cardnumber
262 $template->param( ERRORS => 1 );
263 # this one is fatal so bail here...
264 return %count;
266 my ( $srcimage, $image );
267 if ( open( IMG, "$source" ) ) {
268 $srcimage = GD::Image->new(*IMG);
269 close(IMG);
270 if ( defined $srcimage ) {
271 my $imgfile;
272 my $mimetype = 'image/png';
273 # GD autodetects three basic image formats: PNG, JPEG, XPM
274 # we will convert all to PNG which is lossless...
275 # Check the pixel size of the image we are about to import...
276 my ( $width, $height ) = $srcimage->getBounds();
277 $debug and warn "$filename is $width pix X $height pix.";
278 if ( $width > 200 || $height > 300 ) {
279 # MAX pixel dims are 200 X 300...
280 $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
281 # Percent we will reduce the image dimensions by...
282 my $percent_reduce;
283 if ( $width > 200 ) {
284 # If the width is oversize, scale based on width overage...
285 $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
287 else {
288 # otherwise scale based on height overage.
289 $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
291 my $width_reduce =
292 sprintf( "%.0f", ( $width * $percent_reduce ) );
293 my $height_reduce =
294 sprintf( "%.0f", ( $height * $percent_reduce ) );
295 $debug
296 and warn "Reducing $filename by "
297 . ( $percent_reduce * 100 )
298 . "\% or to $width_reduce pix X $height_reduce pix";
299 #'1' creates true color image...
300 $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
301 $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
302 $height_reduce, $width, $height );
303 $imgfile = $image->png();
304 $debug
305 and warn "$filename is "
306 . length($imgfile)
307 . " bytes after resizing.";
308 undef $image;
309 undef $srcimage; # This object can get big...
311 else {
312 $image = $srcimage;
313 $imgfile = $image->png();
314 $debug
315 and warn "$filename is " . length($imgfile) . " bytes.";
316 undef $image;
317 undef $srcimage; # This object can get big...
319 $debug and warn "Image is of mimetype $mimetype";
320 my $dberror;
321 if ($mimetype) {
322 my $patron = Koha::Patrons->find({ cardnumber => $cardnumber });
323 if ( $patron ) {
324 my $image = $patron->image;
325 $image ||= Koha::Patron::Image->new({ borrowernumber => $patron->borrowernumber });
326 $image->set({
327 mimetype => $mimetype,
328 imagefile => $imgfile,
330 eval { $image->store };
331 if ( $@ ) {
332 # Errors from here on are fatal only to the import of a particular image
333 #so don't bail, just note the error and keep going
334 warn "Database returned error: $@";
335 $filerrors{'DBERR'} = 1;
336 push my @filerrors, \%filerrors;
337 push @{ $count{filenames} },
339 filerrors => \@filerrors,
340 source => $filename,
341 cardnumber => $cardnumber
343 $template->param( ERRORS => 1 );
344 } else {
345 $count{count}++;
346 push @{ $count{filenames} },
347 { source => $filename, cardnumber => $cardnumber };
349 } else {
350 warn "Patron with the cardnumber '$cardnumber' does not exist";
351 $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1;
352 push my @filerrors, \%filerrors;
353 push @{ $count{filenames} },
355 filerrors => \@filerrors,
356 source => $filename,
357 cardnumber => $cardnumber
359 $template->param( ERRORS => 1 );
362 else {
363 warn "Unable to determine mime type of $filename. Please verify mimetype.";
364 $filerrors{'MIMERR'} = 1;
365 push my @filerrors, \%filerrors;
366 push @{ $count{filenames} },
368 filerrors => \@filerrors,
369 source => $filename,
370 cardnumber => $cardnumber
372 $template->param( ERRORS => 1 );
375 else {
376 warn "Contents of $filename corrupted!";
377 #$count{count}--;
378 $filerrors{'CORERR'} = 1;
379 push my @filerrors, \%filerrors;
380 push @{ $count{filenames} },
382 filerrors => \@filerrors,
383 source => $filename,
384 cardnumber => $cardnumber
386 $template->param( ERRORS => 1 );
389 else {
390 warn "Opening $source failed!";
391 $filerrors{'OPNERR'} = 1;
392 push my @filerrors, \%filerrors;
393 push @{ $count{filenames} },
395 filerrors => \@filerrors,
396 source => $filename,
397 cardnumber => $cardnumber
399 $template->param( ERRORS => 1 );
402 else {
403 # The need for this seems a bit unlikely, however, to maximize error trapping it is included
404 warn "Missing "
406 $cardnumber
407 ? "filename"
408 : ( $filename ? "cardnumber" : "cardnumber and filename" )
410 $filerrors{'CRDFIL'} = (
411 $cardnumber
412 ? "filename"
413 : ( $filename ? "cardnumber" : "cardnumber and filename" )
415 push my @filerrors, \%filerrors;
416 push @{ $count{filenames} },
418 filerrors => \@filerrors,
419 source => $filename,
420 cardnumber => $cardnumber
422 $template->param( ERRORS => 1 );
424 return (%count);
427 =head1 AUTHORS
429 Original contributor(s) undocumented
431 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
432 Image scaling/resizing contributed by the same.
434 =cut