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