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