Bug 16330: Add routes to add, update and delete patrons
[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 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;
33
34 use Koha::Patrons;
35 use Koha::Patron::Images;
36 use Koha::Token;
37
38 my $input = new CGI;
39
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                                         });
48
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') || '';
55
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
59
60 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
61
62 =head1 NAME
63
64 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
65
66 =head1 SYNOPSIS
67
68 picture-upload.pl
69
70 =head1 DESCRIPTION
71
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.
74
75 =cut
76
77 $debug and warn "Operation requested: $op";
78
79 my ( $total, $handled, $tempfile, $tfh );
80 our @counts = ();
81 our %errors = ();
82
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
86     die "Wrong CSRF token"
87         unless Koha::Token->new->check_csrf({
88             session_id => scalar $input->cookie('CGISESSID'),
89             token  => scalar $input->param('csrf_token'),
90         });
91
92     my $dirname = File::Temp::tempdir( CLEANUP => 1 );
93     $debug and warn "dirname = $dirname";
94     my $filesuffix;
95     if ( $uploadfilename =~ m/(\..+)$/i ) {
96         $filesuffix = $1;
97     }
98     ( $tfh, $tempfile ) =
99       File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
100     $debug and warn "tempfile = $tempfile";
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         unless ( system( "unzip", $tempfile, '-d', $dirname ) == 0 ) {
119             $errors{'UZIPFAIL'} = $uploadfilename;
120             $template->param( ERRORS => [ \%errors ] );
121             # This error is fatal to the import, so bail out here
122             output_html_with_http_headers $input, $cookie, $template->output;
123             exit;
124         }
125         push @directories, "$dirname";
126         foreach my $recursive_dir (@directories) {
127             opendir RECDIR, $recursive_dir;
128             while ( my $entry = readdir RECDIR ) {
129                 push @directories, "$recursive_dir/$entry"
130                   if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
131                 $debug and warn "$recursive_dir/$entry";
132             }
133             closedir RECDIR;
134         }
135         foreach my $dir (@directories) {
136             $results = handle_dir( $dir, $filesuffix, $template );
137             $handled++ if $results == 1;
138         }
139         $total = scalar @directories;
140     }
141     else {
142         #if ($filetype eq 'zip' )
143         $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber,
144             $tempfile );
145         $handled++ if $results == 1;
146         $total   = 1;
147     }
148
149     if ( $results!=1 || %errors ) {
150         $template->param( ERRORS => [$results] );
151     }
152     else {
153         my $filecount;
154         map { $filecount += $_->{count} } @counts;
155         $debug and warn "Total directories processed: $total";
156         $debug and warn "Total files processed: $filecount";
157         $template->param(
158             TOTAL   => $total,
159             HANDLED => $handled,
160             COUNTS  => \@counts,
161             TCOUNTS => ( $filecount > 0 ? $filecount : undef ),
162         );
163         $template->param( borrowernumber => $borrowernumber )
164           if $borrowernumber;
165     }
166 }
167 elsif ( ( $op eq 'Upload' ) && !$uploadfile ) {
168     warn "Problem uploading file or no file uploaded.";
169     $template->param( cardnumber => $cardnumber );
170     $template->param( filetype   => $filetype );
171 }
172 elsif ( $op eq 'Delete' ) {
173     die "Wrong CSRF token"
174         unless Koha::Token->new->check_csrf({
175             session_id => scalar $input->cookie('CGISESSID'),
176             token  => scalar $input->param('csrf_token'),
177         });
178
179     my $deleted = eval {
180         Koha::Patron::Images->find( $borrowernumber )->delete;
181     };
182     if ( $@ or not $deleted ) {
183         warn "Image for patron '$borrowernumber' has not been deleted";
184     }
185 }
186 if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) {
187     print $input->redirect(
188         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
189 }
190 else {
191     $template->param(
192         csrf_token => Koha::Token->new->generate_csrf({
193             session_id => scalar $input->cookie('CGISESSID'),
194         }),
195     );
196     output_html_with_http_headers $input, $cookie, $template->output;
197 }
198
199 sub handle_dir {
200     my ( $dir, $suffix, $template, $cardnumber, $source ) = @_;
201     my ( %counts, %direrrors );
202     $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
203     if ( $suffix =~ m/zip/i ) {
204         # If we were sent a zip file, process any included data/idlink.txt files
205         my ( $file, $filename );
206         undef $cardnumber;
207         $debug and warn "Passed a zip file.";
208         opendir DIR, $dir;
209         while ( my $filename = readdir DIR ) {
210             $file = "$dir/$filename"
211               if ( $filename =~ m/datalink\.txt/i
212                 || $filename =~ m/idlink\.txt/i );
213         }
214         unless ( open( FILE, $file ) ) {
215             warn "Opening $dir/$file failed!";
216             $direrrors{'OPNLINK'} = $file;
217             # This error is fatal to the import of this directory contents
218             # so bail and return the error to the caller
219             return \%direrrors;
220         }
221
222         while ( my $line = <FILE> ) {
223             $debug and warn "Reading contents of $file";
224             chomp $line;
225             $debug and warn "Examining line: $line";
226             my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : "";
227             $debug and warn "Delimeter is \'$delim\'";
228             unless ( $delim eq "," || $delim eq "\t" ) {
229                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
230                 $direrrors{'DELERR'} = 1;
231                 # This error is fatal to the import of this directory contents
232                 # so bail and return the error to the caller
233                 return \%direrrors;
234             }
235             ( $cardnumber, $filename ) = split $delim, $line;
236             $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters
237             $filename   =~ s/[\"\r\n\s]//g;
238             $debug and warn "Cardnumber: $cardnumber Filename: $filename";
239             $source = "$dir/$filename";
240             %counts = handle_file( $cardnumber, $source, $template, %counts );
241         }
242         close FILE;
243         closedir DIR;
244     }
245     else {
246         %counts = handle_file( $cardnumber, $source, $template, %counts );
247     }
248     push @counts, \%counts;
249     return 1;
250 }
251
252 sub handle_file {
253     my ( $cardnumber, $source, $template, %count ) = @_;
254     $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
255     $count{filenames} = ()      if !$count{filenames};
256     $count{source}    = $source if !$count{source};
257     $count{count}     = 0       unless exists $count{count};
258     my %filerrors;
259     my $filename;
260     if ( $filetype eq 'image' ) {
261         $filename = $uploadfilename;
262     }
263     else {
264         $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ );
265     }
266     if ( $cardnumber && $source ) {
267         # Now process any imagefiles
268         $debug and warn "Source: $source";
269         my $size = ( stat($source) )[7];
270         if ( $size > 550000 ) {
271             # This check is necessary even with image resizing to avoid possible security/performance issues...
272             $filerrors{'OVRSIZ'} = 1;
273             push my @filerrors, \%filerrors;
274             push @{ $count{filenames} },
275               {
276                 filerrors  => \@filerrors,
277                 source     => $filename,
278                 cardnumber => $cardnumber
279               };
280             $template->param( ERRORS => 1 );
281             # this one is fatal so bail here...
282             return %count;
283         }
284         my ( $srcimage, $image );
285         if ( open( IMG, "$source" ) ) {
286             $srcimage = GD::Image->new(*IMG);
287             close(IMG);
288             if ( defined $srcimage ) {
289                 my $imgfile;
290                 my $mimetype = 'image/png';
291                 # GD autodetects three basic image formats: PNG, JPEG, XPM
292                 # we will convert all to PNG which is lossless...
293                 # Check the pixel size of the image we are about to import...
294                 my ( $width, $height ) = $srcimage->getBounds();
295                 $debug and warn "$filename is $width pix X $height pix.";
296                 if ( $width > 200 || $height > 300 ) {
297                     # MAX pixel dims are 200 X 300...
298                     $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
299                     # Percent we will reduce the image dimensions by...
300                     my $percent_reduce;
301                     if ( $width > 200 ) {
302                         # If the width is oversize, scale based on width overage...
303                         $percent_reduce = sprintf( "%.5f", ( 140 / $width ) );
304                     }
305                     else {
306                         # otherwise scale based on height overage.
307                         $percent_reduce = sprintf( "%.5f", ( 200 / $height ) );
308                     }
309                     my $width_reduce =
310                       sprintf( "%.0f", ( $width * $percent_reduce ) );
311                     my $height_reduce =
312                       sprintf( "%.0f", ( $height * $percent_reduce ) );
313                     $debug
314                       and warn "Reducing $filename by "
315                       . ( $percent_reduce * 100 )
316                       . "\% or to $width_reduce pix X $height_reduce pix";
317                     #'1' creates true color image...
318                     $image = GD::Image->new( $width_reduce, $height_reduce, 1 );
319                     $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce,
320                         $height_reduce, $width, $height );
321                     $imgfile = $image->png();
322                     $debug
323                       and warn "$filename is "
324                       . length($imgfile)
325                       . " bytes after resizing.";
326                     undef $image;
327                     undef $srcimage; # This object can get big...
328                 }
329                 else {
330                     $image   = $srcimage;
331                     $imgfile = $image->png();
332                     $debug
333                       and warn "$filename is " . length($imgfile) . " bytes.";
334                     undef $image;
335                     undef $srcimage; # This object can get big...
336                 }
337                 $debug and warn "Image is of mimetype $mimetype";
338                 my $dberror;
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