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