Bug 21395: Fix creation of PO file
[koha.git] / tools / picture-upload.pl
blobc114a86a326bf14f7d03b649a16ff2b62665c374
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::Images;
36 use Koha::Token;
38 my $input = new CGI;
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");
43 exit;
46 my ($template, $loggedinuser, $cookie)
47 = get_template_and_user({template_name => "tools/picture-upload.tt",
48 query => $input,
49 type => "intranet",
50 authnotrequired => 0,
51 flagsrequired => { tools => 'batch_upload_patron_images'},
52 debug => 0,
53 });
55 our $filetype = $input->param('filetype') || '';
56 my $cardnumber = $input->param('cardnumber');
57 our $uploadfilename = $input->param('uploadfile') || '';
58 my $uploadfile = $input->upload('uploadfile');
59 my $borrowernumber = $input->param('borrowernumber');
60 my $op = $input->param('op') || '';
62 #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.
63 # Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
64 # coded. -fbcit
66 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
68 =head1 NAME
70 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
72 =head1 SYNOPSIS
74 picture-upload.pl
76 =head1 DESCRIPTION
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.
81 =cut
83 $debug and warn "Operation requested: $op";
85 my ( $total, $handled, $tempfile, $tfh );
86 our @counts = ();
87 our %errors = ();
89 # Case is important in these operational values as the template must use case to be visually pleasing!
90 if ( ( $op eq 'Upload' ) && $uploadfile ) {
92 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
93 unless Koha::Token->new->check_csrf({
94 session_id => scalar $input->cookie('CGISESSID'),
95 token => scalar $input->param('csrf_token'),
96 });
98 my $dirname = File::Temp::tempdir( CLEANUP => 1 );
99 $debug and warn "dirname = $dirname";
100 my $filesuffix;
101 if ( $uploadfilename =~ m/(\..+)$/i ) {
102 $filesuffix = $1;
104 ( $tfh, $tempfile ) =
105 File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
106 $debug and warn "tempfile = $tempfile";
107 my ( @directories, $results );
109 $errors{'NOTZIP'} = 1
110 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
111 $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
112 $errors{'EMPTYUPLOAD'} = 1 unless ( length($uploadfile) > 0 );
114 if (%errors) {
115 $template->param( ERRORS => [ \%errors ] );
116 output_html_with_http_headers $input, $cookie, $template->output;
117 exit;
119 while (<$uploadfile>) {
120 print $tfh $_;
122 close $tfh;
123 if ( $filetype eq 'zip' ) {
124 qx/unzip $tempfile -d $dirname/;
125 my $exit_code = $?;
126 unless ( $exit_code == 0 ) {
127 $errors{'UZIPFAIL'} = $uploadfilename;
128 $template->param( ERRORS => [ \%errors ] );
129 # This error is fatal to the import, so bail out here
130 output_html_with_http_headers $input, $cookie, $template->output;
131 exit;
133 push @directories, "$dirname";
134 foreach my $recursive_dir (@directories) {
135 opendir RECDIR, $recursive_dir;
136 while ( my $entry = readdir RECDIR ) {
137 push @directories, "$recursive_dir/$entry"
138 if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
139 $debug and warn "$recursive_dir/$entry";
141 closedir RECDIR;
143 foreach my $dir (@directories) {
144 $results = handle_dir( $dir, $filesuffix, $template );
145 $handled++ if $results == 1;
147 $total = scalar @directories;
149 else {
150 #if ($filetype eq 'zip' )
151 $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber,
152 $tempfile );
153 $handled++ if $results == 1;
154 $total = 1;
157 if ( $results!=1 || %errors ) {
158 $template->param( ERRORS => [$results] );
160 else {
161 my $filecount;
162 map { $filecount += $_->{count} } @counts;
163 $debug and warn "Total directories processed: $total";
164 $debug and warn "Total files processed: $filecount";
165 $template->param(
166 TOTAL => $total,
167 HANDLED => $handled,
168 COUNTS => \@counts,
169 TCOUNTS => ( $filecount > 0 ? $filecount : undef ),
171 $template->param( borrowernumber => $borrowernumber )
172 if $borrowernumber;
175 elsif ( ( $op eq 'Upload' ) && !$uploadfile ) {
176 warn "Problem uploading file or no file uploaded.";
177 $template->param( cardnumber => $cardnumber );
178 $template->param( filetype => $filetype );
180 elsif ( $op eq 'Delete' ) {
181 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
182 unless Koha::Token->new->check_csrf({
183 session_id => scalar $input->cookie('CGISESSID'),
184 token => scalar $input->param('csrf_token'),
187 my $deleted = eval {
188 Koha::Patron::Images->find( $borrowernumber )->delete;
190 if ( $@ or not $deleted ) {
191 warn "Image for patron '$borrowernumber' has not been deleted";
194 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
195 print $input->redirect(
196 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
198 else {
199 $template->param(
200 csrf_token => Koha::Token->new->generate_csrf({
201 session_id => scalar $input->cookie('CGISESSID'),
204 output_html_with_http_headers $input, $cookie, $template->output;
207 sub handle_dir {
208 my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
209 my ( %counts, %direrrors );
210 $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
211 if ( $suffix =~ m/zip/i ) {
212 # If we were sent a zip file, process any included data/idlink.txt files
213 my ( $file, $filename );
214 undef $cardnumber;
215 $debug and warn "Passed a zip file.";
216 opendir DIR, $dir;
217 while ( my $filename = readdir DIR ) {
218 $file = "$dir/$filename"
219 if ( $filename =~ m/datalink\.txt/i
220 || $filename =~ m/idlink\.txt/i );
222 my $fh;
223 unless ( open( $fh, '<', $file ) ) {
224 warn "Opening $dir/$file failed!";
225 $direrrors{'OPNLINK'} = $file;
226 # This error is fatal to the import of this directory contents
227 # so bail and return the error to the caller
228 return \%direrrors;
231 while ( my $line = <$fh> ) {
232 $debug and warn "Reading contents of $file";
233 chomp $line;
234 $debug and warn "Examining line: $line";
235 my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
236 $debug and warn "Delimeter is \'$delim\'";
237 unless ( $delim eq "," || $delim eq "\t" ) {
238 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
239 $direrrors{'DELERR'} = 1;
240 # This error is fatal to the import of this directory contents
241 # so bail and return the error to the caller
242 return \%direrrors;
244 ( $cardnumber, $filename ) = split $delim, $line;
245 $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
246 $filename =~ s/[\"\r\n\s]//g;
247 $debug and warn "Cardnumber: $cardnumber Filename: $filename";
248 $source = "$dir/$filename";
249 %counts = handle_file( $cardnumber, $source, $template, %counts );
251 close $fh;
252 closedir DIR;
254 else {
255 %counts = handle_file( $cardnumber, $source, $template, %counts );
257 push @counts, \%counts;
258 return 1;
261 sub handle_file {
262 my ( $cardnumber, $source, $template, %count ) = @_;
263 $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
264 $count{filenames} = () if !$count{filenames};
265 $count{source} = $source if !$count{source};
266 $count{count} = 0 unless exists $count{count};
267 my %filerrors;
268 my $filename;
269 if ( $filetype eq 'image' ) {
270 $filename = $uploadfilename;
272 else {
273 $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
275 if ( $cardnumber && $source ) {
276 # Now process any imagefiles
277 $debug and warn "Source: $source";
278 my $size = ( stat($source) )[7];
279 if ( $size > 550000 ) {
280 # This check is necessary even with image resizing to avoid possible security/performance issues...
281 $filerrors{'OVRSIZ'} = 1;
282 push my @filerrors, \%filerrors;
283 push @{ $count{filenames} },
285 filerrors => \@filerrors,
286 source => $filename,
287 cardnumber => $cardnumber
289 $template->param( ERRORS => 1 );
290 # this one is fatal so bail here...
291 return %count;
293 my ( $srcimage, $image );
294 if ( open( my $fh, '<', $source ) ) {
295 $srcimage = GD::Image->new($fh);
296 close($fh);
297 if ( defined $srcimage ) {
298 my $imgfile;
299 my $mimetype = 'image/png';
300 # GD autodetects three basic image formats: PNG, JPEG, XPM
301 # we will convert all to PNG which is lossless...
302 # Check the pixel size of the image we are about to import...
303 my ( $width, $height ) = $srcimage->getBounds();
304 $debug and warn "$filename is $width pix X $height pix.";
305 if ( $width > 200 || $height > 300 ) {
306 # MAX pixel dims are 200 X 300...
307 $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
308 # Percent we will reduce the image dimensions by...
309 my $percent_reduce;
310 if ( $width > 200 ) {
311 # If the width is oversize, scale based on width overage...
312 $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
314 else {
315 # otherwise scale based on height overage.
316 $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
318 my $width_reduce =
319 sprintf( "%.0f", ( $width * $percent_reduce ) );
320 my $height_reduce =
321 sprintf( "%.0f", ( $height * $percent_reduce ) );
322 $debug
323 and warn "Reducing $filename by "
324 . ( $percent_reduce * 100 )
325 . "\% or to $width_reduce pix X $height_reduce pix";
326 #'1' creates true color image...
327 $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
328 $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
329 $height_reduce, $width, $height );
330 $imgfile = $image->png();
331 $debug
332 and warn "$filename is "
333 . length($imgfile)
334 . " bytes after resizing.";
335 undef $image;
336 undef $srcimage; # This object can get big...
338 else {
339 $image = $srcimage;
340 $imgfile = $image->png();
341 $debug
342 and warn "$filename is " . length($imgfile) . " bytes.";
343 undef $image;
344 undef $srcimage; # This object can get big...
346 $debug and warn "Image is of mimetype $mimetype";
347 if ($mimetype) {
348 my $patron = Koha::Patrons->find({ cardnumber => $cardnumber });
349 if ( $patron ) {
350 my $image = $patron->image;
351 $image ||= Koha::Patron::Image->new({ borrowernumber => $patron->borrowernumber });
352 $image->set({
353 mimetype => $mimetype,
354 imagefile => $imgfile,
356 eval { $image->store };
357 if ( $@ ) {
358 # Errors from here on are fatal only to the import of a particular image
359 #so don't bail, just note the error and keep going
360 warn "Database returned error: $@";
361 $filerrors{'DBERR'} = 1;
362 push my @filerrors, \%filerrors;
363 push @{ $count{filenames} },
365 filerrors => \@filerrors,
366 source => $filename,
367 cardnumber => $cardnumber
369 $template->param( ERRORS => 1 );
370 } else {
371 $count{count}++;
372 push @{ $count{filenames} },
373 { source => $filename, cardnumber => $cardnumber };
375 } else {
376 warn "Patron with the cardnumber '$cardnumber' does not exist";
377 $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1;
378 push my @filerrors, \%filerrors;
379 push @{ $count{filenames} },
381 filerrors => \@filerrors,
382 source => $filename,
383 cardnumber => $cardnumber
385 $template->param( ERRORS => 1 );
388 else {
389 warn "Unable to determine mime type of $filename. Please verify mimetype.";
390 $filerrors{'MIMERR'} = 1;
391 push my @filerrors, \%filerrors;
392 push @{ $count{filenames} },
394 filerrors => \@filerrors,
395 source => $filename,
396 cardnumber => $cardnumber
398 $template->param( ERRORS => 1 );
401 else {
402 warn "Contents of $filename corrupted!";
403 #$count{count}--;
404 $filerrors{'CORERR'} = 1;
405 push my @filerrors, \%filerrors;
406 push @{ $count{filenames} },
408 filerrors => \@filerrors,
409 source => $filename,
410 cardnumber => $cardnumber
412 $template->param( ERRORS => 1 );
415 else {
416 warn "Opening $source failed!";
417 $filerrors{'OPNERR'} = 1;
418 push my @filerrors, \%filerrors;
419 push @{ $count{filenames} },
421 filerrors => \@filerrors,
422 source => $filename,
423 cardnumber => $cardnumber
425 $template->param( ERRORS => 1 );
428 else {
429 # The need for this seems a bit unlikely, however, to maximize error trapping it is included
430 warn "Missing "
432 $cardnumber
433 ? "filename"
434 : ( $filename ? "cardnumber" : "cardnumber and filename" )
436 $filerrors{'CRDFIL'} = (
437 $cardnumber
438 ? "filename"
439 : ( $filename ? "cardnumber" : "cardnumber and filename" )
441 push my @filerrors, \%filerrors;
442 push @{ $count{filenames} },
444 filerrors => \@filerrors,
445 source => $filename,
446 cardnumber => $cardnumber
448 $template->param( ERRORS => 1 );
450 return (%count);
453 =head1 AUTHORS
455 Original contributor(s) undocumented
457 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
458 Image scaling/resizing contributed by the same.
460 =cut