Bug 17830: CSRF - Handle unicode characters in userid
[koha.git] / opac / opac-memberentry.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use CGI qw ( -utf8 );
21 use Digest::MD5 qw( md5_base64 md5_hex );
22 use Encode qw( encode );
23 use String::Random qw( random_string );
24
25 use C4::Auth;
26 use C4::Output;
27 use C4::Members;
28 use C4::Form::MessagingPreferences;
29 use Koha::Patrons;
30 use Koha::Patron::Modification;
31 use Koha::Patron::Modifications;
32 use C4::Scrubber;
33 use Email::Valid;
34 use Koha::DateUtils;
35 use Koha::Libraries;
36 use Koha::Patron::Images;
37 use Koha::Token;
38
39 my $cgi = new CGI;
40 my $dbh = C4::Context->dbh;
41
42 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
43     {
44         template_name   => "opac-memberentry.tt",
45         type            => "opac",
46         query           => $cgi,
47         authnotrequired => 1,
48     }
49 );
50
51 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
52 {
53     print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
54     exit;
55 }
56
57 my $action = $cgi->param('action') || q{};
58 if ( $action eq q{} ) {
59     if ($borrowernumber) {
60         $action = 'edit';
61     }
62     else {
63         $action = 'new';
64     }
65 }
66
67 my $mandatory = GetMandatoryFields($action);
68
69 my @libraries = Koha::Libraries->search;
70 if ( my @libraries_to_display = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList') ) {
71     @libraries = map { my $b = $_; my $branchcode = $_->branchcode; grep( /^$branchcode$/, @libraries_to_display ) ? $b : () } @libraries;
72 }
73 my ( $min, $max ) = C4::Members::get_cardnumber_length();
74 if ( defined $min ) {
75      $template->param(
76          minlength_cardnumber => $min,
77          maxlength_cardnumber => $max
78      );
79  }
80
81 $template->param(
82     action            => $action,
83     hidden            => GetHiddenFields( $mandatory, 'registration' ),
84     mandatory         => $mandatory,
85     libraries         => \@libraries,
86     OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
87 );
88
89 if ( $action eq 'create' ) {
90
91     my %borrower = ParseCgiForBorrower($cgi);
92
93     %borrower = DelEmptyFields(%borrower);
94
95     my @empty_mandatory_fields = CheckMandatoryFields( \%borrower, $action );
96     my $invalidformfields = CheckForInvalidFields(\%borrower);
97     delete $borrower{'password2'};
98     my $cardnumber_error_code;
99     if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
100         # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
101         # spurious length warning.
102         $cardnumber_error_code = checkcardnumber( $borrower{cardnumber}, $borrower{borrowernumber} );
103     }
104
105     if ( @empty_mandatory_fields || @$invalidformfields || $cardnumber_error_code ) {
106         if ( $cardnumber_error_code == 1 ) {
107             $template->param( cardnumber_already_exists => 1 );
108         } elsif ( $cardnumber_error_code == 2 ) {
109             $template->param( cardnumber_wrong_length => 1 );
110         }
111
112         $template->param(
113             empty_mandatory_fields => \@empty_mandatory_fields,
114             invalid_form_fields    => $invalidformfields,
115             borrower               => \%borrower
116         );
117     }
118     elsif (
119         md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
120     {
121         $template->param(
122             failed_captcha => 1,
123             borrower       => \%borrower
124         );
125     }
126     else {
127         if (
128             C4::Context->boolean_preference(
129                 'PatronSelfRegistrationVerifyByEmail')
130           )
131         {
132             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
133                 {
134                     template_name   => "opac-registration-email-sent.tt",
135                     type            => "opac",
136                     query           => $cgi,
137                     authnotrequired => 1,
138                 }
139             );
140             $template->param( 'email' => $borrower{'email'} );
141
142             my $verification_token = md5_hex( time().{}.rand().{}.$$ );
143             while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
144                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
145             }
146
147             $borrower{password}           = random_string("..........");
148             $borrower{verification_token} = $verification_token;
149
150             Koha::Patron::Modification->new( \%borrower )->store();
151
152             #Send verification email
153             my $letter = C4::Letters::GetPreparedLetter(
154                 module      => 'members',
155                 letter_code => 'OPAC_REG_VERIFY',
156                 tables      => {
157                     borrower_modifications => $verification_token,
158                 },
159             );
160
161             C4::Letters::EnqueueLetter(
162                 {
163                     letter                 => $letter,
164                     message_transport_type => 'email',
165                     to_address             => $borrower{'email'},
166                     from_address =>
167                       C4::Context->preference('KohaAdminEmailAddress'),
168                 }
169             );
170         }
171         else {
172             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
173                 {
174                     template_name   => "opac-registration-confirmation.tt",
175                     type            => "opac",
176                     query           => $cgi,
177                     authnotrequired => 1,
178                 }
179             );
180
181             $template->param( OpacPasswordChange =>
182                   C4::Context->preference('OpacPasswordChange') );
183
184             my ( $borrowernumber, $password ) = AddMember_Opac(%borrower);
185             C4::Form::MessagingPreferences::handle_form_action($cgi, { borrowernumber => $borrowernumber }, $template, 1, C4::Context->preference('PatronSelfRegistrationDefaultCategory') ) if $borrowernumber && C4::Context->preference('EnhancedMessagingPreferences');
186
187             $template->param( password_cleartext => $password );
188             $template->param(
189                 borrower => GetMember( borrowernumber => $borrowernumber ) );
190             $template->param(
191                 PatronSelfRegistrationAdditionalInstructions =>
192                   C4::Context->preference(
193                     'PatronSelfRegistrationAdditionalInstructions')
194             );
195         }
196     }
197 }
198 elsif ( $action eq 'update' ) {
199
200     my $borrower = GetMember( borrowernumber => $borrowernumber );
201     die "Wrong CSRF token"
202         unless Koha::Token->new->check_csrf({
203             id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
204             secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
205             token  => scalar $cgi->param('csrf_token'),
206         });
207
208     my %borrower = ParseCgiForBorrower($cgi);
209
210     my %borrower_changes = DelEmptyFields(%borrower);
211     my @empty_mandatory_fields =
212       CheckMandatoryFields( \%borrower_changes, $action );
213     my $invalidformfields = CheckForInvalidFields(\%borrower);
214
215     # Send back the data to the template
216     %borrower = ( %$borrower, %borrower );
217
218     if (@empty_mandatory_fields || @$invalidformfields) {
219         $template->param(
220             empty_mandatory_fields => \@empty_mandatory_fields,
221             invalid_form_fields    => $invalidformfields,
222             borrower               => \%borrower,
223             csrf_token             => Koha::Token->new->generate_csrf({
224                 id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
225                 secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
226             }),
227         );
228
229         $template->param( action => 'edit' );
230     }
231     else {
232         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
233         if (%borrower_changes) {
234             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
235                 {
236                     template_name   => "opac-memberentry-update-submitted.tt",
237                     type            => "opac",
238                     query           => $cgi,
239                     authnotrequired => 1,
240                 }
241             );
242
243             $borrower_changes{borrowernumber} = $borrowernumber;
244
245             # FIXME update the following with
246             # Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
247             # when bug 17091 will be pushed
248             my $patron_modifications = Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber });
249             while ( my $patron_modification = $patron_modifications->next ) {
250                 $patron_modification->delete;
251             }
252
253             my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
254
255             $template->param(
256                 borrower => GetMember( borrowernumber => $borrowernumber ),
257             );
258         }
259         else {
260             $template->param(
261                 action => 'edit',
262                 nochanges => 1,
263                 borrower => GetMember( borrowernumber => $borrowernumber ),
264                 csrf_token => Koha::Token->new->generate_csrf({
265                     id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
266                     secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
267                 }),
268             );
269         }
270     }
271 }
272 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
273     my $borrower = GetMember( borrowernumber => $borrowernumber );
274
275     if (C4::Context->preference('ExtendedPatronAttributes')) {
276         my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber, 'opac');
277         if (scalar(@$attributes) > 0) {
278             $borrower->{ExtendedPatronAttributes} = 1;
279             $borrower->{patron_attributes} = $attributes;
280         }
281     }
282
283     $template->param(
284         borrower  => $borrower,
285         guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
286         hidden => GetHiddenFields( $mandatory, 'modification' ),
287         csrf_token => Koha::Token->new->generate_csrf({
288             id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
289             secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
290         }),
291     );
292
293     if (C4::Context->preference('OPACpatronimages')) {
294         my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
295         $template->param( display_patron_image => 1 ) if $patron_image;
296     }
297
298 }
299
300 my $captcha = random_string("CCCCC");
301
302 $template->param(
303     captcha        => $captcha,
304     captcha_digest => md5_base64($captcha)
305 );
306
307 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
308
309 sub GetHiddenFields {
310     my ( $mandatory, $action ) = @_;
311     my %hidden_fields;
312
313     my $BorrowerUnwantedField = $action eq 'modification' ?
314       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
315       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
316
317     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
318     foreach (@fields) {
319         next unless m/\w/o;
320         #Don't hide mandatory fields
321         next if $mandatory->{$_};
322         $hidden_fields{$_} = 1;
323     }
324
325     return \%hidden_fields;
326 }
327
328 sub GetMandatoryFields {
329     my ($action) = @_;
330
331     my %mandatory_fields;
332
333     my $BorrowerMandatoryField =
334       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
335
336     my @fields = split( /\|/, $BorrowerMandatoryField );
337
338     foreach (@fields) {
339         $mandatory_fields{$_} = 1;
340     }
341
342     if ( $action eq 'create' || $action eq 'new' ) {
343         $mandatory_fields{'email'} = 1
344           if C4::Context->boolean_preference(
345             'PatronSelfRegistrationVerifyByEmail');
346     }
347
348     return \%mandatory_fields;
349 }
350
351 sub CheckMandatoryFields {
352     my ( $borrower, $action ) = @_;
353
354     my @empty_mandatory_fields;
355
356     my $mandatory_fields = GetMandatoryFields($action);
357     delete $mandatory_fields->{'cardnumber'};
358
359     foreach my $key ( keys %$mandatory_fields ) {
360         push( @empty_mandatory_fields, $key )
361           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
362     }
363
364     return @empty_mandatory_fields;
365 }
366
367 sub CheckForInvalidFields {
368     my $minpw = C4::Context->preference('minPasswordLength');
369     my $borrower = shift;
370     my @invalidFields;
371     if ($borrower->{'email'}) {
372         unless ( Email::Valid->address($borrower->{'email'}) ) {
373             push(@invalidFields, "email");
374         } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
375             my $patrons_with_same_email = Koha::Patrons->search( { email => $borrower->{email} })->count;
376             if ( $patrons_with_same_email ) {
377                 push @invalidFields, "duplicate_email";
378             }
379         }
380     }
381     if ($borrower->{'emailpro'}) {
382         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
383     }
384     if ($borrower->{'B_email'}) {
385         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
386     }
387     if ( $borrower->{'password'} ne $borrower->{'password2'} ){
388         push(@invalidFields, "password_match");
389     }
390     if ( $borrower->{'password'}  && $minpw && (length($borrower->{'password'}) < $minpw) ) {
391        push(@invalidFields, "password_invalid");
392     }
393     if ( $borrower->{'password'} ) {
394        push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
395     }
396
397     return \@invalidFields;
398 }
399
400 sub ParseCgiForBorrower {
401     my ($cgi) = @_;
402
403     my $scrubber = C4::Scrubber->new();
404     my %borrower;
405
406     foreach ( $cgi->param ) {
407         if ( $_ =~ '^borrower_' ) {
408             my ($key) = substr( $_, 9 );
409             $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
410         }
411     }
412
413     my $dob_dt;
414     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
415         if ( $borrower{'dateofbirth'} );
416
417     if ( $dob_dt ) {
418         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
419     }
420     else {
421         # Trigger validation
422         $borrower{'dateofbirth'} = undef;
423     }
424
425     return %borrower;
426 }
427
428 sub DelUnchangedFields {
429     my ( $borrowernumber, %new_data ) = @_;
430
431     my $current_data = GetMember( borrowernumber => $borrowernumber );
432
433     foreach my $key ( keys %new_data ) {
434         if ( $current_data->{$key} eq $new_data{$key} ) {
435             delete $new_data{$key};
436         }
437     }
438
439     return %new_data;
440 }
441
442 sub DelEmptyFields {
443     my (%borrower) = @_;
444
445     foreach my $key ( keys %borrower ) {
446         delete $borrower{$key} unless $borrower{$key};
447     }
448
449     return %borrower;
450 }