Third installment on moving patronimages into the database.
[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 C4::Context;
26 use C4::Auth;
27 use C4::Output;
28 use C4::Members;
29 #use Data::Dumper;
30
31 my $DEBUG = ($ENV{DEBUG}) ? 1 : 0;
32
33 my $input = new CGI;
34
35 my ($template, $loggedinuser, $cookie)
36         = get_template_and_user({template_name => "tools/picture-upload.tmpl",
37                                         query => $input,
38                                         type => "intranet",
39                                         authnotrequired => 0,
40                                         flagsrequired => {management => 1, tools => 1},
41                                         debug => 0,
42                                         });
43
44 my $filetype            = $input->param('filetype');
45 my $cardnumber          = $input->param('cardnumber');
46 my $uploadfilename      = $input->param('uploadfile');
47 my $uploadfile          = $input->upload('uploadfile');
48
49 #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.
50 #       Other parts of this code could be optimized as well, I think. Perhaps the file upload could be done with YUI's upload
51 #       coded. -fbcit
52
53 warn "Params are: filetype=$filetype, cardnumber=$cardnumber, uploadfile=$uploadfilename" if $DEBUG;
54
55 =head1 NAME
56
57 picture-upload.p. - Script for handling uploading of both single and bulk patronimages and importing them into the database.
58
59 =head1 SYNOPSIS
60
61 picture-upload.pl
62
63 =head1 DESCRIPTION
64
65 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.
66
67 =cut
68
69
70
71 my ( $total, $handled, @counts, $tempfile, $tfh );
72
73 if ( $uploadfile ) {
74     my $dirname = File::Temp::tempdir( CLEANUP => 1);
75     warn "dirname = $dirname" if $DEBUG;
76     my $filesuffix = $1 if $uploadfilename =~ m/(\..+)$/i;
77     ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 );
78     warn "tempfile = $tempfile" if $DEBUG;
79     my ( @directories, $errors );
80
81     $errors{'NOTZIP'} = 1 if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i );
82     $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname );
83     $errors{'EMPTYUPLOAD'} = 1 unless ( length( $uploadfile ) > 0 );
84
85     if ( %errors ) {
86         $template->param( ERRORS => [ \%errors ] );
87     } else {
88         while ( <$uploadfile> ) {
89             print $tfh $_;
90         }
91
92         close $tfh;
93         if ( $filetype eq 'zip' ) {
94             unless (system("unzip $tempfile -d $dirname") == 0) {
95                 $errors{'UZIPFAIL'} = $uploadfilename;
96                 $template->param( ERRORS => [ \%errors ] );
97                 output_html_with_http_headers $input, $cookie, $template->output;   # This error is fatal to the import, so bail out here
98                 exit;
99             }
100             push @directories, "$dirname";
101             foreach $recursive_dir ( @directories ) {
102                 opendir $dir, $recursive_dir;
103                 while ( my $entry = readdir $dir ) {
104                 push @directories, "$recursive_dir/$entry" if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ );
105                 warn "$recursive_dir/$entry" if $DEBUG;
106                 }   
107                 closedir $dir;
108             }       
109             my $results;
110             foreach my $dir ( @directories ) {
111                 $results = handle_dir( $dir, $filesuffix );
112                 $handled++ if $results == 1;
113             }
114             $total = scalar @directories;
115         } else {       #if ($filetype eq 'zip' )
116             $result = handle_dir( $dirname, $filesuffix );
117             $handled = 1;
118             $total = 1;
119         }
120
121         if ( %$results || %errors ) {
122             $template->param( ERRORS => [ \%$results ] );
123         } else {
124             warn "Total files processed: $total" if $DEBUG;
125             warn "Errors in \$errors." if $errors;
126             $template->param(
127                  TOTAL => $total,
128                  HANDLED => $handled,
129                  COUNTS => \@counts,
130                  TCOUNTS => scalar(@counts),
131             );
132         }   
133     }
134 }
135
136 output_html_with_http_headers $input, $cookie, $template->output;
137
138 sub handle_dir {
139     my ( $dir, $suffix ) = @_;
140     my $source;
141     warn "Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix" if $DEBUG;
142     if ($suffix =~ m/zip/i) {     # If we were sent a zip file, process any included data/idlink.txt files 
143         my ( $file, $filename, $cardnumber );
144         warn "Passed a zip file." if $DEBUG;
145         opendir my $dirhandle, $dir;
146         while ( my $filename = readdir $dirhandle ) {
147             $file = "$dir/$filename" if ($filename =~ m/datalink\.txt/i || $filename =~ m/idlink\.txt/i);
148         }
149         unless (open (FILE, $file)) { 
150                 warn "Opening $dir/$file failed!";
151                 $errors{'OPNLINK'} = $file;
152                 return $errors; # This error is fatal to the import of this directory contents, so bail and return the error to the caller
153         };
154
155         while (my $line = <FILE>) {
156             warn "Reading contents of $file" if $DEBUG;
157             chomp $line;
158             warn "Examining line: $line" if $DEBUG;
159             my $delim = ($line =~ /\t/) ? "\t" : ($line =~ /,/) ? "," : "";
160             warn "Delimeter is \'$delim\'" if $DEBUG;
161             unless ( $delim eq "," || $delim eq "\t" ) {
162                 warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'";
163                 $errors{'DELERR'} = 1;      # This error is fatal to the import of this directory contents, so bail and return the error to the caller
164                 return $errors;
165             }
166             ($cardnumber, $filename) = split $delim, $line;
167             $cardnumber =~ s/[\"\r\n]//g;  # remove offensive characters
168             $filename   =~ s/[\"\r\n\s]//g;
169             warn "Cardnumber: $cardnumber Filename: $filename" if $DEBUG;
170             $source = "$dir/$filename";
171             %counts = handle_file($cardnumber, $source, %counts);
172         }
173         close FILE;
174         closedir ($dirhandle);
175     } else {
176         $source = $tempfile;
177         %counts = handle_file($cardnumber, $source, %counts);
178     }
179 push @counts, \%counts;
180 warn Dumper(@counts);
181 return 1;
182 }
183
184 sub handle_file {
185     my ($cardnumber, $source, %count) = @_;
186     warn "Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source" if $DEBUG;
187     my $mimemap = {
188         "gif"   => "image/gif",
189         "jpg"   => "image/jpeg",
190         "jpeg"  => "image/jpeg",
191         "png"   => "image/png"
192     };
193     $count{filenames} = () if !$count{filenames};
194     $count{source} = $source if !$count{source};
195     if ($cardnumber && $source) {     # Now process any imagefiles
196         my %filerrors;
197         warn "Source: $source" if $DEBUG;
198         if (open (IMG, "$source")) {
199             #binmode (IMG); # Not sure if we need this or not -fbcit
200             my $imgfile;
201             while (<IMG>) {
202                 $imgfile .= $_;
203             }
204             if ($filetype eq 'image') {
205                 $filename = $uploadfilename;
206             } else {
207                 $filename = $1 if ($source =~ /\/([^\/]+)$/);
208             }
209             warn "\$filename=$filename";
210             my $mimetype = $mimemap->{lc ($1)} if $filename =~ m/\.([^.]+)$/i;
211             warn "$filename is mimetype \"$mimetype\"" if $DEBUG;
212             my $dberror = PutPatronImage($cardnumber,$mimetype, $imgfile) if $mimetype;
213             close (IMG);
214             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
215                 $count{count}++;
216                 push @{ $count{filenames} }, { source => $filename, cardnumber => $cardnumber };
217             } elsif ( $dberror ) {
218                 warn "Database returned error: $dberror";
219                 ($dberror =~ /patronimage_fk1/) ? $filerrors{'IMGEXISTS'} = 1 : $filerrors{'DBERR'} = 1;
220                 push my @filerrors, \%filerrors;
221                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
222                 $template->param( ERRORS => 1 );
223             } elsif ( !$mimetype ) {
224                 warn "Unable to determine mime type of $filename. Please verify mimetype and add to \%mimemap if necessary.";
225                 $filerrors{'MIMERR'} = 1;
226                 push my @filerrors, \%filerrors;
227                 push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
228                 $template->param( ERRORS => 1 );
229             }
230         } else {
231             warn "Opening $dir/$filename failed!";
232             $filerrors{'OPNERR'} = 1;
233             push my @filerrors, \%filerrors;
234             push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
235             $template->param( ERRORS => 1 );
236         }
237     } else {    # The need for this seems a bit unlikely, however, to maximize error trapping it is included
238         warn "Missing " . ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename"));
239         $filerrors{'CRDFIL'} = ($cardnumber ? "filename" : ($filename ? "cardnumber" : "cardnumber and filename")); 
240         push my @filerrors, \%filerrors;
241         push @{ $count{filenames} }, { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber };
242         $template->param( ERRORS => 1 );
243     }
244     return %count;
245 }
246
247 =back
248
249 =head1 AUTHORS
250
251 Original contributor(s) undocumented
252
253 Database storage, single patronimage upload option, and extensive error trapping contributed by Chris Nighswonger cnighswonger <at> foundations <dot> edu
254
255 =cut