Bug 6362: fixes display to re-embed items in OPAC MARC view
[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 under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
10 #
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along with
16 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
17 # Suite 330, Boston, MA  02111-1307 USA
18 #
19 #
20 #
21
22 #use strict;
23 #use warnings; FIXME - Bug 2505
24
25 use File::Temp;
26 use File::Copy;
27 use CGI;
28 use GD;
29 use C4::Context;
30 use C4::Auth;
31 use C4::Output;
32 use C4::Members;
33 use C4::Debug;
34
35 my $input = new CGI;
36
37 my ($template, $loggedinuser, $cookie)
38         = get_template_and_user({template_name => "tools/picture-upload.tmpl",
39                                         query => $input,
40                                         type => "intranet",
41                                         authnotrequired => 0,
42                                         flagsrequired => { tools => 'batch_upload_patron_images'},
43                                         debug => 0,
44                                         });
45
46 my $filetype            = $input->param('filetype');
47 my $cardnumber          = $input->param('cardnumber');
48 my $uploadfilename      = $input->param('uploadfile');
49 my $uploadfile          = $input->upload('uploadfile');
50 my $borrowernumber      = $input->param('borrowernumber');
51 my $op                  = $input->param('op');
52
53 #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.
54 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
55 #       coded. -fbcit
56
57 $debug and warn "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename";
58
59 =head1 NAME
60
61 picture-upload.pl - Script for handling uploading of both single and bulk patronimages and importing them into the database.
62
63 =head1 SYNOPSIS
64
65 picture-upload.pl
66
67 =head1 DESCRIPTION
68
69 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.
70 Files greater than 100K will be refused. Images should be 140x200 pixels. If they are larger they will be auto-resized to comply.
71
72 =cut
73
74 $debug and warn "Operation requested: $op";
75
76 my ( $total, $handled, @counts, $tempfile, $tfh );
77
78 if ( ($op eq 'Upload') && $uploadfile ) {       # Case is important in these operational values as the template must use case to be visually pleasing!
79     my $dirname = File::Temp::tempdir( CLEANUP => 1);
80     $debug and warn "dirname = $dirname";
81     my $filesuffix = $1 if $uploadfilename =~ m/(\..+)$/i;
82     ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
83     $debug and warn "tempfile = $tempfile";
84     my ( @directories, $errors );
85
86     $errors{'NOTZIP'} = 1 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
87     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
88     $errors{'EMPTYUPLOAD'} = 1 unless ( length( $uploadfile ) > 0 );
89
90     if ( %errors ) {
91         $template->param( ERRORS => [ \%errors ] );
92     } else {
93         while ( <$uploadfile> ) {
94             print $tfh $_;
95         }
96         close $tfh;
97         if ( $filetype eq 'zip' ) {
98             unless (system("unzip", $tempfile,  '-d', $dirname) == 0) {
99                 $errors{'UZIPFAIL'} = $uploadfilename;
100                 $template->param( ERRORS => [ \%errors ] );
101                 output_html_with_http_headers $input, $cookie, $template->output;   # This error is fatal to the import, so bail out here
102                 exit;
103             }
104             push @directories, "$dirname";
105             foreach $recursive_dir ( @directories ) {
106                 opendir $dir, $recursive_dir;
107                 while ( my $entry = readdir $dir ) {
108                 push @directories, "$recursive_dir/$entry" if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
109                 $debug and warn "$recursive_dir/$entry";
110                 }
111                 closedir $dir;
112             }
113             my $results;
114             foreach my $dir ( @directories ) {
115                 $results = handle_dir( $dir, $filesuffix );
116                 $handled++ if $results == 1;
117             }
118             $total = scalar @directories;
119         } else {       #if ($filetype eq 'zip' )
120             $results = handle_dir( $dirname, $filesuffix );
121             $handled = 1;
122             $total = 1;
123         }
124
125         if ( %$results || %errors ) {
126             $template->param( ERRORS => [ \%$results ] );
127         } else {
128                         my $filecount;
129                         map {$filecount += $_->{count}} @counts;
130             $debug and warn "Total directories processed: $total";
131             $debug and warn "Total files processed: $filecount";
132             $template->param(
133                         TOTAL => $total,
134                         HANDLED => $handled,
135                         COUNTS => \@counts,
136                         TCOUNTS => ($filecount > 0 ? $filecount : undef),
137             );
138                         $template->param( borrowernumber => $borrowernumber ) if $borrowernumber;
139         }
140     }
141 } elsif ( ($op eq 'Upload') && !$uploadfile ) {
142     warn "Problem uploading file or no file uploaded.";
143     $template->param(cardnumber => $cardnumber);
144     $template->param(filetype => $filetype);
145 } elsif ( $op eq 'Delete' ) {
146     my $dberror = RmPatronImage($cardnumber);
147         $debug and warn "Patron image deleted for $cardnumber";
148     warn "Database returned $dberror" if $dberror;
149 }
150 if ( $borrowernumber && !$errors && !$template->param('ERRORS') ) {
151     print $input->redirect ("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
152 } else {
153     output_html_with_http_headers $input, $cookie, $template->output;
154 }
155
156 sub handle_dir {
157     my ( $dir, $suffix ) = @_;
158     my $source;
159     $debug and warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix";
160     if ($suffix =~ m/zip/i) {     # If we were sent a zip file, process any included data/idlink.txt files
161         my ( $file, $filename, $cardnumber );
162         $debug and warn "Passed a zip file.";
163         opendir my $dirhandle, $dir;
164         while ( my $filename = readdir $dirhandle ) {
165             $file = "$dir/$filename" if ($filename =~ m/datalink\.txt/i || $filename =~ m/idlink\.txt/i);
166         }
167         unless (open (FILE, $file)) {
168                 warn "Opening $dir/$file failed!";
169                 $errors{'OPNLINK'} = $file;
170                 return $errors; # This error is fatal to the import of this directory contents, so bail and return the error to the caller
171         };
172
173         while (my $line = <FILE>) {
174             $debug and warn "Reading contents of $file";
175             chomp $line;
176             $debug and warn "Examining line: $line";
177             my $delim = ($line =~ /\t/) ? "\t" : ($line =~ /,/) ? "," : "";
178             $debug and warn "Delimeter is \'$delim\'";
179             unless ( $delim eq "," || $delim eq "\t" ) {
180                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
181                 $errors{'DELERR'} = 1;      # This error is fatal to the import of this directory contents, so bail and return the error to the caller
182                 return $errors;
183             }
184             ($cardnumber, $filename) = split $delim, $line;
185             $cardnumber =~ s/[\"\r\n]//g;  # remove offensive characters
186             $filename   =~ s/[\"\r\n\s]//g;
187             $debug and warn "Cardnumber: $cardnumber Filename: $filename";
188             $source = "$dir/$filename";
189             %counts = handle_file($cardnumber, $source, %counts);
190         }
191         close FILE;
192         closedir ($dirhandle);
193     } else {
194         $source = $tempfile;
195         %counts = handle_file($cardnumber, $source, %counts);
196     }
197 push @counts, \%counts;
198 return 1;
199 }
200
201 sub handle_file {
202     my ($cardnumber, $source, %count) = @_;
203     $debug and warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source";
204     $count{filenames} = () if !$count{filenames};
205     $count{source} = $source if !$count{source};
206     if ($cardnumber && $source) {     # Now process any imagefiles
207         my %filerrors;
208         my $filename;
209         if ($filetype eq 'image') {
210             $filename = $uploadfilename;
211         } else {
212             $filename = $1 if ($source =~ /\/([^\/]+)$/);
213         }
214         $debug and warn "Source: $source";
215         my $size = (stat($source))[7];
216             if ($size > 550000) {    # This check is necessary even with image resizing to avoid possible security/performance issues...
217                 $filerrors{'OVRSIZ'} = 1;
218                 push my @filerrors, \%filerrors;
219                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
220                 $template->param( ERRORS => 1 );
221                 return %count;    # this one is fatal so bail here...
222             }
223         my ($srcimage, $image);
224         if (open (IMG, "$source")) {
225             $srcimage = GD::Image->new(*IMG);
226             close (IMG);
227                         if (defined $srcimage) {
228                                 my $mimetype = 'image/png';     # GD autodetects three basic image formats: PNG, JPEG, XPM; we will convert all to PNG which is lossless...
229                                 # Check the pixel size of the image we are about to import...
230                                 my ($width, $height) = $srcimage->getBounds();
231                                 $debug and warn "$filename is $width pix X $height pix.";
232                                 if ($width > 200 || $height > 300) {    # MAX pixel dims are 200 X 300...
233                                         $debug and warn "$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing...";
234                                         my $percent_reduce;    # Percent we will reduce the image dimensions by...
235                                         if ($width > 200) {
236                                                 $percent_reduce = sprintf("%.5f",(140/$width));    # If the width is oversize, scale based on width overage...
237                                         } else {
238                                                 $percent_reduce = sprintf("%.5f",(200/$height));    # otherwise scale based on height overage.
239                                         }
240                                         my $width_reduce = sprintf("%.0f", ($width * $percent_reduce));
241                                         my $height_reduce = sprintf("%.0f", ($height * $percent_reduce));
242                                         $debug and warn "Reducing $filename by " . ($percent_reduce * 100) . "\% or to $width_reduce pix X $height_reduce pix";
243                                         $image = GD::Image->new($width_reduce, $height_reduce, 1); #'1' creates true color image...
244                                         $image->copyResampled($srcimage,0,0,0,0,$width_reduce,$height_reduce,$width,$height);
245                                         $imgfile = $image->png();
246                                         $debug and warn "$filename is " . length($imgfile) . " bytes after resizing.";
247                                         undef $image;
248                                         undef $srcimage;    # This object can get big...
249                                 } else {
250                                         $image = $srcimage;
251                                         $imgfile = $image->png();
252                                         $debug and warn "$filename is " . length($imgfile) . " bytes.";
253                                         undef $image;
254                                         undef $srcimage;    # This object can get big...
255                                 }
256                                 $debug and warn "Image is of mimetype $mimetype";
257                                 my $dberror = PutPatronImage($cardnumber,$mimetype, $imgfile) if $mimetype;
258                                 if ( !$dberror && $mimetype ) { # Errors from here on are fatal only to the import of a particular image, so don't bail, just note the error and keep going
259                                         $count{count}++;
260                                         push @{ $count{filenames} }, { source => $filename, cardnumber => $cardnumber };
261                                 } elsif ( $dberror ) {
262                                                 warn "Database returned error: $dberror";
263                                                 ($dberror =~ /patronimage_fk1/) ? $filerrors{'IMGEXISTS'} = 1 : $filerrors{'DBERR'} = 1;
264                                                 push my @filerrors, \%filerrors;
265                                                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
266                                                 $template->param( ERRORS => 1 );
267                                 } elsif ( !$mimetype ) {
268                                         warn "Unable to determine mime type of $filename. Please verify mimetype.";
269                                         $filerrors{'MIMERR'} = 1;
270                                         push my @filerrors, \%filerrors;
271                                         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
272                                         $template->param( ERRORS => 1 );
273                                 }
274                         } else {
275                                 warn "Contents of $filename corrupted!";
276                         #       $count{count}--;
277                                 $filerrors{'CORERR'} = 1;
278                                 push my @filerrors, \%filerrors;
279                                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
280                                 $template->param( ERRORS => 1 );
281                         }
282                 } else {
283                         warn "Opening $dir/$filename failed!";
284                         $filerrors{'OPNERR'} = 1;
285                         push my @filerrors, \%filerrors;
286                         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
287                         $template->param( ERRORS => 1 );
288                 }
289     } else {    # The need for this seems a bit unlikely, however, to maximize error trapping it is included
290         warn "Missing " . ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
291         $filerrors{'CRDFIL'} = ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
292         push my @filerrors, \%filerrors;
293                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
294         $template->param( ERRORS => 1 );
295     }
296     return (%count);
297 }
298
299 =head1 AUTHORS
300
301 Original contributor(s) undocumented
302
303 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
304 Image scaling/resizing contributed by the same.
305
306 =cut