Bug 17116: Fix CSRF in import_borrowers.pl
[koha.git] / tools / import_borrowers.pl
1 #!/usr/bin/perl
2
3 # Copyright 2007 Liblime
4 # Parts copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # Script to take some borrowers data in a known format and load it into Koha
22 #
23 # File format
24 #
25 # cardnumber,surname,firstname,title,othernames,initials,streetnumber,streettype,
26 # address line , address line 2, city, zipcode, contry, email, phone, mobile, fax, work email, work phone,
27 # alternate streetnumber, alternate streettype, alternate address line 1, alternate city,
28 # alternate zipcode, alternate country, alternate email, alternate phone, date of birth, branchcode,
29 # categorycode, enrollment date, expiry date, noaddress, lost, debarred, contact surname,
30 # contact firstname, contact title, borrower notes, contact relationship
31 # gender, username, opac note, contact note, password, sort one, sort two
32 #
33 # any fields except cardnumber can be blank but the number of fields must match
34 # dates should be in the format you have set up Koha to expect
35 # branchcode and categorycode need to be valid
36
37 use strict;
38 use warnings;
39
40 use C4::Auth;
41 use C4::Output;
42 use C4::Context;
43 use C4::Branch qw/GetBranchesLoop GetBranchName/;
44 use C4::Members;
45 use C4::Members::Attributes qw(:all);
46 use C4::Members::AttributeTypes;
47 use C4::Members::Messaging;
48 use C4::Reports::Guided;
49 use C4::Templates;
50 use Koha::Patron::Debarments;
51 use Koha::DateUtils;
52 use Koha::Token;
53
54 use Text::CSV;
55 # Text::CSV::Unicode, even in binary mode, fails to parse lines with these diacriticals:
56 # ė
57 # č
58
59 use CGI qw ( -utf8 );
60 # use encoding 'utf8';    # don't do this
61 use Digest::MD5 qw(md5_base64);
62
63 my (@errors, @feedback);
64 my $extended = C4::Context->preference('ExtendedPatronAttributes');
65 my $set_messaging_prefs = C4::Context->preference('EnhancedMessagingPreferences');
66 my @columnkeys = C4::Members::columns();
67 @columnkeys = map { $_ ne 'borrowernumber' ? $_ : () } @columnkeys;
68 if ($extended) {
69     push @columnkeys, 'patron_attributes';
70 }
71
72 my $input = CGI->new();
73 our $csv  = Text::CSV->new({binary => 1});  # binary needed for non-ASCII Unicode
74 #push @feedback, {feedback=>1, name=>'backend', value=>$csv->backend, backend=>$csv->backend}; #XXX
75
76 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
77         template_name   => "tools/import_borrowers.tt",
78         query           => $input,
79         type            => "intranet",
80         authnotrequired => 0,
81         flagsrequired   => { tools => 'import_patrons' },
82         debug           => 1,
83 });
84
85 # get the branches and pass them to the template
86 my $branches = GetBranchesLoop();
87 $template->param( branches => $branches ) if ( $branches );
88 # get the patron categories and pass them to the template
89 my $categories = GetBorrowercategoryList();
90 $template->param( categories => $categories ) if ( $categories );
91 my $columns = C4::Templates::GetColumnDefs( $input )->{borrowers};
92 $columns = [ grep { $_->{field} ne 'borrowernumber' ? $_ : () } @$columns ];
93 $template->param( borrower_fields => $columns );
94
95 if ($input->param('sample')) {
96     print $input->header(
97         -type       => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ?
98         -attachment => 'patron_import.csv',
99     );
100     $csv->combine(@columnkeys);
101     print $csv->string, "\n";
102     exit 0;
103 }
104 my $uploadborrowers = $input->param('uploadborrowers');
105 my $matchpoint      = $input->param('matchpoint');
106 if ($matchpoint) {
107     $matchpoint =~ s/^patron_attribute_//;
108 }
109 my $overwrite_cardnumber = $input->param('overwrite_cardnumber');
110
111 $template->param( SCRIPT_NAME => '/cgi-bin/koha/tools/import_borrowers.pl' );
112
113 if ( $uploadborrowers && length($uploadborrowers) > 0 ) {
114     die "Wrong CSRF token"
115         unless Koha::Token->new->check_csrf({
116             session_id => scalar $input->cookie('CGISESSID'),
117             token  => scalar $input->param('csrf_token'),
118         });
119
120     push @feedback, {feedback=>1, name=>'filename', value=>$uploadborrowers, filename=>$uploadborrowers};
121     my $handle = $input->upload('uploadborrowers');
122     my $uploadinfo = $input->uploadInfo($uploadborrowers);
123     foreach (keys %$uploadinfo) {
124         push @feedback, {feedback=>1, name=>$_, value=>$uploadinfo->{$_}, $_=>$uploadinfo->{$_}};
125     }
126     my $imported    = 0;
127     my $alreadyindb = 0;
128     my $overwritten = 0;
129     my $invalid     = 0;
130     my $matchpoint_attr_type; 
131     my %defaults = $input->Vars;
132
133     # use header line to construct key to column map
134     my $borrowerline = <$handle>;
135     my $status = $csv->parse($borrowerline);
136     ($status) or push @errors, {badheader=>1,line=>$., lineraw=>$borrowerline};
137     my @csvcolumns = $csv->fields();
138     my %csvkeycol;
139     my $col = 0;
140     foreach my $keycol (@csvcolumns) {
141         # columnkeys don't contain whitespace, but some stupid tools add it
142         $keycol =~ s/ +//g;
143         $csvkeycol{$keycol} = $col++;
144     }
145     #warn($borrowerline);
146     my $ext_preserve = $input->param('ext_preserve') || 0;
147     if ($extended) {
148         $matchpoint_attr_type = C4::Members::AttributeTypes->fetch($matchpoint);
149     }
150
151     push @feedback, {feedback=>1, name=>'headerrow', value=>join(', ', @csvcolumns)};
152     my $today_iso = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
153     my @criticals = qw(surname branchcode categorycode);    # there probably should be others
154     my @bad_dates;  # I've had a few.
155     LINE: while ( my $borrowerline = <$handle> ) {
156         my %borrower;
157         my @missing_criticals;
158         my $patron_attributes;
159         my $status  = $csv->parse($borrowerline);
160         my @columns = $csv->fields();
161         if (! $status) {
162             push @missing_criticals, {badparse=>1, line=>$., lineraw=>$borrowerline};
163         } elsif (@columns == @columnkeys) {
164             @borrower{@columnkeys} = @columns;
165             # MJR: try to fill blanks gracefully by using default values
166             foreach my $key (@columnkeys) {
167                 if ($borrower{$key} !~ /\S/) {
168                     $borrower{$key} = $defaults{$key};
169                 }
170             } 
171         } else {
172             # MJR: try to recover gracefully by using default values
173             foreach my $key (@columnkeys) {
174                 if (defined($csvkeycol{$key}) and $columns[$csvkeycol{$key}] =~ /\S/) { 
175                     $borrower{$key} = $columns[$csvkeycol{$key}];
176                 } elsif ( $defaults{$key} ) {
177                     $borrower{$key} = $defaults{$key};
178                 } elsif ( scalar grep {$key eq $_} @criticals ) {
179                     # a critical field is undefined
180                     push @missing_criticals, {key=>$key, line=>$., lineraw=>$borrowerline};
181                 } else {
182                         $borrower{$key} = '';
183                 }
184             }
185         }
186         #warn join(':',%borrower);
187         if ($borrower{categorycode}) {
188             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline, value=>$borrower{categorycode}, category_map=>1}
189                 unless GetBorrowercategory($borrower{categorycode});
190         } else {
191             push @missing_criticals, {key=>'categorycode', line=>$. , lineraw=>$borrowerline};
192         }
193         if ($borrower{branchcode}) {
194             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline, value=>$borrower{branchcode}, branch_map=>1}
195                 unless GetBranchName($borrower{branchcode});
196         } else {
197             push @missing_criticals, {key=>'branchcode', line=>$. , lineraw=>$borrowerline};
198         }
199         if (@missing_criticals) {
200             foreach (@missing_criticals) {
201                 $_->{borrowernumber} = $borrower{borrowernumber} || 'UNDEF';
202                 $_->{surname}        = $borrower{surname} || 'UNDEF';
203             }
204             $invalid++;
205             (25 > scalar @errors) and push @errors, {missing_criticals=>\@missing_criticals};
206             # The first 25 errors are enough.  Keeping track of 30,000+ would destroy performance.
207             next LINE;
208         }
209         if ($extended) {
210             my $attr_str = $borrower{patron_attributes};
211             $attr_str =~ s/\xe2\x80\x9c/"/g; # fixup double quotes in case we are passed smart quotes
212             $attr_str =~ s/\xe2\x80\x9d/"/g;
213             push @feedback, {feedback=>1, name=>'attribute string', value=>$attr_str, filename=>$uploadborrowers};
214             delete $borrower{patron_attributes};    # not really a field in borrowers, so we don't want to pass it to ModMember.
215             $patron_attributes = extended_attributes_code_value_arrayref($attr_str); 
216         }
217         # Popular spreadsheet applications make it difficult to force date outputs to be zero-padded, but we require it.
218         foreach (qw(dateofbirth dateenrolled dateexpiry)) {
219             my $tempdate = $borrower{$_} or next;
220             $tempdate = eval { output_pref( { dt => dt_from_string( $tempdate ), dateonly => 1, dateformat => 'iso' } ); };
221             if ($tempdate) {
222                 $borrower{$_} = $tempdate;
223             } else {
224                 $borrower{$_} = '';
225                 push @missing_criticals, {key=>$_, line=>$. , lineraw=>$borrowerline, bad_date=>1};
226             }
227         }
228         $borrower{dateenrolled} = $today_iso unless $borrower{dateenrolled};
229         $borrower{dateexpiry} = GetExpiryDate($borrower{categorycode},$borrower{dateenrolled}) unless $borrower{dateexpiry}; 
230         my $borrowernumber;
231         my $member;
232         if ( ($matchpoint eq 'cardnumber') && ($borrower{'cardnumber'}) ) {
233             $member = GetMember( 'cardnumber' => $borrower{'cardnumber'} );
234             if ($member) {
235                 $borrowernumber = $member->{'borrowernumber'};
236             }
237         } elsif ( ($matchpoint eq 'userid') && ($borrower{'userid'}) ) {
238             $member = GetMember( 'userid' => $borrower{'userid'} );
239             if ($member) {
240                 $borrowernumber = $member->{'borrowernumber'};
241             }
242         } elsif ($extended) {
243             if (defined($matchpoint_attr_type)) {
244                 foreach my $attr (@$patron_attributes) {
245                     if ($attr->{code} eq $matchpoint and $attr->{value} ne '') {
246                         my @borrowernumbers = $matchpoint_attr_type->get_patrons($attr->{value});
247                         $borrowernumber = $borrowernumbers[0] if scalar(@borrowernumbers) == 1;
248                         last;
249                     }
250                 }
251             }
252         }
253
254         if ( C4::Members::checkcardnumber( $borrower{cardnumber}, $borrowernumber ) ) {
255             push @errors, {
256                 invalid_cardnumber => 1,
257                 borrowernumber => $borrowernumber,
258                 cardnumber => $borrower{cardnumber}
259             };
260             $invalid++;
261             next;
262         }
263
264         if ($borrowernumber) {
265             # borrower exists
266             unless ($overwrite_cardnumber) {
267                 $alreadyindb++;
268                 $template->param('lastalreadyindb'=>$borrower{'surname'}.' / '.$borrowernumber);
269                 next LINE;
270             }
271             $borrower{'borrowernumber'} = $borrowernumber;
272             for my $col (keys %borrower) {
273                 # use values from extant patron unless our csv file includes this column or we provided a default.
274                 # FIXME : You cannot update a field with a  perl-evaluated false value using the defaults.
275
276                 # The password is always encrypted, skip it!
277                 next if $col eq 'password';
278
279                 unless(exists($csvkeycol{$col}) || $defaults{$col}) {
280                     $borrower{$col} = $member->{$col} if($member->{$col}) ;
281                 }
282             }
283
284             # Check if the userid provided does not exist yet
285             if (  exists $borrower{userid}
286                      and $borrower{userid}
287                  and not Check_Userid( $borrower{userid}, $borrower{borrowernumber} ) ) {
288                 push @errors, { duplicate_userid => 1, userid => $borrower{userid} };
289                 $invalid++;
290                 next LINE;
291             }
292
293             unless (ModMember(%borrower)) {
294                 $invalid++;
295                 # until we have better error trapping, we have no way of knowing why ModMember errored out...
296                 push @errors, {unknown_error => 1};
297                 $template->param('lastinvalid'=>$borrower{'surname'}.' / '.$borrowernumber);
298                 next LINE;
299             }
300
301             # Don't add a new restriction if the existing 'combined' restriction matches this one
302             if ( $borrower{debarred} && ( ( $borrower{debarred} ne $member->{debarred} ) || ( $borrower{debarredcomment} ne $member->{debarredcomment} ) ) ) {
303                 # Check to see if this debarment already exists
304                 my $debarrments = GetDebarments(
305                     {
306                         borrowernumber => $borrowernumber,
307                         expiration     => $borrower{debarred},
308                         comment        => $borrower{debarredcomment}
309                     }
310                 );
311                 # If it doesn't, then add it!
312                 unless (@$debarrments) {
313                     AddDebarment(
314                         {
315                             borrowernumber => $borrowernumber,
316                             expiration     => $borrower{debarred},
317                             comment        => $borrower{debarredcomment}
318                         }
319                     );
320                 }
321             }
322
323             if ($extended) {
324                 if ($ext_preserve) {
325                     my $old_attributes = GetBorrowerAttributes($borrowernumber);
326                     $patron_attributes = extended_attributes_merge($old_attributes, $patron_attributes);  #TODO: expose repeatable options in template
327                 }
328                 push @errors, {unknown_error => 1} unless SetBorrowerAttributes($borrower{'borrowernumber'}, $patron_attributes, 'no_branch_limit' );
329             }
330             $overwritten++;
331             $template->param('lastoverwritten'=>$borrower{'surname'}.' / '.$borrowernumber);
332         } else {
333             # FIXME: fixup_cardnumber says to lock table, but the web interface doesn't so this doesn't either.
334             # At least this is closer to AddMember than in members/memberentry.pl
335             if (!$borrower{'cardnumber'}) {
336                 $borrower{'cardnumber'} = fixup_cardnumber(undef);
337             }
338             if ($borrowernumber = AddMember(%borrower)) {
339
340                 if ( $borrower{debarred} ) {
341                     AddDebarment(
342                         {
343                             borrowernumber => $borrowernumber,
344                             expiration     => $borrower{debarred},
345                             comment        => $borrower{debarredcomment}
346                         }
347                     );
348                 }
349
350                 if ($extended) {
351                     SetBorrowerAttributes($borrowernumber, $patron_attributes);
352                 }
353
354                 if ($set_messaging_prefs) {
355                     C4::Members::Messaging::SetMessagingPreferencesFromDefaults({ borrowernumber => $borrowernumber,
356                                                                                   categorycode => $borrower{categorycode} });
357                 }
358
359                 $imported++;
360                 $template->param('lastimported'=>$borrower{'surname'}.' / '.$borrowernumber);
361             } else {
362                 $invalid++;
363                 push @errors, {unknown_error => 1};
364                 $template->param('lastinvalid'=>$borrower{'surname'}.' / AddMember');
365             }
366         }
367     }
368     (@errors  ) and $template->param(  ERRORS=>\@errors  );
369     (@feedback) and $template->param(FEEDBACK=>\@feedback);
370     $template->param(
371         'uploadborrowers' => 1,
372         'imported'        => $imported,
373         'overwritten'     => $overwritten,
374         'alreadyindb'     => $alreadyindb,
375         'invalid'         => $invalid,
376         'total'           => $imported + $alreadyindb + $invalid + $overwritten,
377     );
378
379 } else {
380     if ($extended) {
381         my @matchpoints = ();
382         my @attr_types = C4::Members::AttributeTypes::GetAttributeTypes(undef, 1);
383         foreach my $type (@attr_types) {
384             my $attr_type = C4::Members::AttributeTypes->fetch($type->{code});
385             if ($attr_type->unique_id()) {
386             push @matchpoints, { code =>  "patron_attribute_" . $attr_type->code(), description => $attr_type->description() };
387             }
388         }
389         $template->param(matchpoints => \@matchpoints);
390     }
391
392     $template->param(
393         csrf_token => Koha::Token->new->generate_csrf(
394             { session_id => scalar $input->cookie('CGISESSID'), }
395         ),
396     );
397
398 }
399
400 output_html_with_http_headers $input, $cookie, $template->output;
401