NOTE: REQUIRES INSTALLATION OF Image::Magick; Adding image scaling/resizing capabilit...
[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 File::Temp;
23 use File::Copy;
24 use CGI;
25 use Image::Magick;
26 use C4::Context;
27 use C4::Auth;
28 use C4::Output;
29 use C4::Members;
30 #use Data::Dumper;
31
32 my $DEBUG = ($ENV{DEBUG}) ? 1 : 0;
33
34 my $input = new CGI;
35
36 my ($template, $loggedinuser, $cookie)
37         = get_template_and_user({template_name => "tools/picture-upload.tmpl",
38                                         query => $input,
39                                         type => "intranet",
40                                         authnotrequired => 0,
41                                         flagsrequired => {management => 1, tools => 1},
42                                         debug => 0,
43                                         });
44
45 my $filetype            = $input->param('filetype');
46 my $cardnumber          = $input->param('cardnumber');
47 my $uploadfilename      = $input->param('uploadfile');
48 my $uploadfile          = $input->upload('uploadfile');
49 my $borrowernumber      = $input->param('borrowernumber');
50 my $op                  = $input->param('op');
51
52 #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.
53 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
54 #       coded. -fbcit
55
56 warn "Params are: filetype=$filetype, cardnumber=$cardnumber, uploadfile=$uploadfilename" if $DEBUG;
57
58 =head1 NAME
59
60 picture-upload.p. - Script for handling uploading of both single and bulk patronimages and importing them into the database.
61
62 =head1 SYNOPSIS
63
64 picture-upload.pl
65
66 =head1 DESCRIPTION
67
68 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.
69
70 =cut
71
72 warn "Operation requested: $op" if $DEBUG;
73
74 my ( $total, $handled, @counts, $tempfile, $tfh );
75
76 if ( ($op eq 'Upload') && $uploadfile ) {       # Case is important in these operational values as the template must use case to be visually pleasing!
77     my $dirname = File::Temp::tempdir( CLEANUP => 1);
78     warn "dirname = $dirname" if $DEBUG;
79     my $filesuffix = $1 if $uploadfilename =~ m/(\..+)$/i;
80     ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
81     warn "tempfile = $tempfile" if $DEBUG;
82     my ( @directories, $errors );
83
84     $errors{'NOTZIP'} = 1 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
85     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
86     $errors{'EMPTYUPLOAD'} = 1 unless ( length( $uploadfile ) > 0 );
87
88     if ( %errors ) {
89         $template->param( ERRORS => [ \%errors ] );
90     } else {
91         while ( <$uploadfile> ) {
92             print $tfh $_;
93         }
94
95         close $tfh;
96         if ( $filetype eq 'zip' ) {
97             unless (system("unzip $tempfile -d $dirname") == 0) {
98                 $errors{'UZIPFAIL'} = $uploadfilename;
99                 $template->param( ERRORS => [ \%errors ] );
100                 output_html_with_http_headers $input, $cookie, $template->output;   # This error is fatal to the import, so bail out here
101                 exit;
102             }
103             push @directories, "$dirname";
104             foreach $recursive_dir ( @directories ) {
105                 opendir $dir, $recursive_dir;
106                 while ( my $entry = readdir $dir ) {
107                 push @directories, "$recursive_dir/$entry" if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
108                 warn "$recursive_dir/$entry" if $DEBUG;
109                 }   
110                 closedir $dir;
111             }       
112             my $results;
113             foreach my $dir ( @directories ) {
114                 $results = handle_dir( $dir, $filesuffix );
115                 $handled++ if $results == 1;
116             }
117             $total = scalar @directories;
118         } else {       #if ($filetype eq 'zip' )
119             $result = handle_dir( $dirname, $filesuffix );
120             $handled = 1;
121             $total = 1;
122         }
123
124         if ( %$results || %errors ) {
125             $template->param( ERRORS => [ \%$results ] );
126         } else {
127             warn "Total files processed: $total" if $DEBUG;
128             warn "Errors in \$errors." if $errors;
129             $template->param(
130                  TOTAL => $total,
131                  HANDLED => $handled,
132                  COUNTS => \@counts,
133                  TCOUNTS => scalar(@counts),
134             );
135         }   
136     }
137 } elsif ( ($op eq 'Upload') && !$uploadfile ) {
138     warn "Problem uploading file or no file uploaded.";
139     $template->param(cardnumber => $cardnumber);
140     $template->param(filetype => $filetype);
141 } elsif ( $op eq 'Delete' ) {
142     my $dberror = RmPatronImage($cardnumber);
143     warn "Database returned $dberror" if $dberror;
144 } elsif ( $op eq 'Cancel' ) {
145     print $input->redirect ("/cgi-bin/koha/tools/picture-upload.pl");
146 }
147
148 if ( $borrowernumber && !$errors && !$template->param('ERRORS') ) {
149     print $input->redirect ("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
150 } else {
151     output_html_with_http_headers $input, $cookie, $template->output;
152 }
153
154 sub handle_dir {
155     my ( $dir, $suffix ) = @_;
156     my $source;
157     warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix" if $DEBUG;
158     if ($suffix =~ m/zip/i) {     # If we were sent a zip file, process any included data/idlink.txt files 
159         my ( $file, $filename, $cardnumber );
160         warn "Passed a zip file." if $DEBUG;
161         opendir my $dirhandle, $dir;
162         while ( my $filename = readdir $dirhandle ) {
163             $file = "$dir/$filename" if ($filename =~ m/datalink\.txt/i || $filename =~ m/idlink\.txt/i);
164         }
165         unless (open (FILE, $file)) { 
166                 warn "Opening $dir/$file failed!";
167                 $errors{'OPNLINK'} = $file;
168                 return $errors; # This error is fatal to the import of this directory contents, so bail and return the error to the caller
169         };
170
171         while (my $line = <FILE>) {
172             warn "Reading contents of $file" if $DEBUG;
173             chomp $line;
174             warn "Examining line: $line" if $DEBUG;
175             my $delim = ($line =~ /\t/) ? "\t" : ($line =~ /,/) ? "," : "";
176             warn "Delimeter is \'$delim\'" if $DEBUG;
177             unless ( $delim eq "," || $delim eq "\t" ) {
178                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
179                 $errors{'DELERR'} = 1;      # This error is fatal to the import of this directory contents, so bail and return the error to the caller
180                 return $errors;
181             }
182             ($cardnumber, $filename) = split $delim, $line;
183             $cardnumber =~ s/[\"\r\n]//g;  # remove offensive characters
184             $filename   =~ s/[\"\r\n\s]//g;
185             warn "Cardnumber: $cardnumber Filename: $filename" if $DEBUG;
186             $source = "$dir/$filename";
187             %counts = handle_file($cardnumber, $source, %counts);
188         }
189         close FILE;
190         closedir ($dirhandle);
191     } else {
192         $source = $tempfile;
193         %counts = handle_file($cardnumber, $source, %counts);
194     }
195 push @counts, \%counts;
196 return 1;
197 }
198
199 sub handle_file {
200     my ($cardnumber, $source, %count) = @_;
201     warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source" if $DEBUG;
202     $count{filenames} = () if !$count{filenames};
203     $count{source} = $source if !$count{source};
204     if ($cardnumber && $source) {     # Now process any imagefiles
205         my %filerrors;
206         my $filename;
207         if ($filetype eq 'image') {
208             $filename = $uploadfilename;
209         } else {
210             $filename = $1 if ($source =~ /\/([^\/]+)$/);
211         }
212         warn "Source: $source" if $DEBUG;
213         my $size = (stat($source))[7];
214             if ($size > 100000) {    # This check is necessary even with image resizing to avoid possible security/performance issues...
215                 warn "$filename is TOO BIG!!! I refuse to beleagur my database with that much data. Try reducing the pixel dimensions and I\'ll reconsider.";
216                 $filerrors{'OVRSIZ'} = 1;
217                 push my @filerrors, \%filerrors;
218                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
219                 $template->param( ERRORS => 1 );
220                 return %count;    # this one is fatal so bail here...
221             }
222         my $image = Image::Magick->new;
223         if (open (IMG, "$source")) {
224             $image->Read(file=>\*IMG);
225             close (IMG);
226             my $mimetype = $image->Get('mime');
227             # Check the pixel size of the image we are about to import...
228             my ($height, $width) = $image->Get('height', 'width');
229             warn "$filename is $width pix X $height pix." if $DEBUG;
230             if ($width > 140 || $height > 200) {    # MAX pixel dims are 140 X 200...
231                 warn "$filename exceeds the maximum pixel dimensions of 140 X 200. Resizing...";
232                 my $percent_reduce;    # Percent we will reduce the image dimensions by...
233                 if ($width > 140) {
234                     $percent_reduce = sprintf("%.5f",(140/$width));    # If the width is oversize, scale based on width overage...
235                 } else {
236                     $percent_reduce = sprintf("%.5f",(200/$height));    # otherwise scale based on height overage.
237                 }
238                 my $width_reduce = sprintf("%.0f", ($width * $percent_reduce));
239                 my $height_reduce = sprintf("%.0f", ($height * $percent_reduce));
240                 warn "Reducing $filename by " . ($percent_reduce * 100) . "\% or to $width_reduce pix X $height_reduce pix";
241                 $image->Resize(width=>$width_reduce, height=>$height_reduce);
242                 my @img = $image->ImageToBlob();
243                 $imgfile = $img[0];
244                 warn "$filename is " . length($imgfile) . " bytes after resizing.";
245                 undef $image;    # This object can get big...
246             }
247             warn "Image is of mimetype $mimetype" if $DEBUG;
248             my $dberror = PutPatronImage($cardnumber,$mimetype, $imgfile) if $mimetype;
249             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
250                 $count{count}++;
251                 push @{ $count{filenames} }, { source => $filename, cardnumber => $cardnumber };
252             } elsif ( $dberror ) {
253                 warn "Database returned error: $dberror";
254                 ($dberror =~ /patronimage_fk1/) ? $filerrors{'IMGEXISTS'} = 1 : $filerrors{'DBERR'} = 1;
255                 push my @filerrors, \%filerrors;
256                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
257                 $template->param( ERRORS => 1 );
258             } elsif ( !$mimetype ) {
259                 warn "Unable to determine mime type of $filename. Please verify mimetype and add to \%mimemap if necessary.";
260                 $filerrors{'MIMERR'} = 1;
261                 push my @filerrors, \%filerrors;
262                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
263                 $template->param( ERRORS => 1 );
264             }
265         } else {
266             warn "Opening $dir/$filename failed!";
267             $filerrors{'OPNERR'} = 1;
268             push my @filerrors, \%filerrors;
269             push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
270             $template->param( ERRORS => 1 );
271         }
272     } else {    # The need for this seems a bit unlikely, however, to maximize error trapping it is included
273         warn "Missing " . ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
274         $filerrors{'CRDFIL'} = ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename")); 
275         push my @filerrors, \%filerrors;
276         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
277         $template->param( ERRORS => 1 );
278     }
279     return %count;
280 }
281
282 =back
283
284 =head1 AUTHORS
285
286 Original contributor(s) undocumented
287
288 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
289 Image scaling/resizing contributed by the same.
290
291 =cut