Bug 19911: Do not escape html characters when saving passwords
[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
26 use C4::Auth;
27 use C4::Output;
28 use C4::Members;
29 use C4::Form::MessagingPreferences;
30 use Koha::Patrons;
31 use Koha::Patron::Modification;
32 use Koha::Patron::Modifications;
33 use C4::Scrubber;
34 use Email::Valid;
35 use Koha::DateUtils;
36 use Koha::Libraries;
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 my @libraries = Koha::Libraries->search;
71 if ( my @libraries_to_display = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList') ) {
72     @libraries = map { my $b = $_; my $branchcode = $_->branchcode; grep( /^$branchcode$/, @libraries_to_display ) ? $b : () } @libraries;
73 }
74 my ( $min, $max ) = C4::Members::get_cardnumber_length();
75 if ( defined $min ) {
76      $template->param(
77          minlength_cardnumber => $min,
78          maxlength_cardnumber => $max
79      );
80  }
81
82 $template->param(
83     action            => $action,
84     hidden            => GetHiddenFields( $mandatory, 'registration' ),
85     mandatory         => $mandatory,
86     libraries         => \@libraries,
87     OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
88 );
89
90 if ( $action eq 'create' ) {
91
92     my %borrower = ParseCgiForBorrower($cgi);
93
94     %borrower = DelEmptyFields(%borrower);
95
96     my @empty_mandatory_fields = CheckMandatoryFields( \%borrower, $action );
97     my $invalidformfields = CheckForInvalidFields(\%borrower);
98     delete $borrower{'password2'};
99     my $cardnumber_error_code;
100     if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
101         # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
102         # spurious length warning.
103         $cardnumber_error_code = checkcardnumber( $borrower{cardnumber}, $borrower{borrowernumber} );
104     }
105
106     if ( @empty_mandatory_fields || @$invalidformfields || $cardnumber_error_code ) {
107         if ( $cardnumber_error_code == 1 ) {
108             $template->param( cardnumber_already_exists => 1 );
109         } elsif ( $cardnumber_error_code == 2 ) {
110             $template->param( cardnumber_wrong_length => 1 );
111         }
112
113         $template->param(
114             empty_mandatory_fields => \@empty_mandatory_fields,
115             invalid_form_fields    => $invalidformfields,
116             borrower               => \%borrower
117         );
118     }
119     elsif (
120         md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
121     {
122         $template->param(
123             failed_captcha => 1,
124             borrower       => \%borrower
125         );
126     }
127     else {
128         if (
129             C4::Context->boolean_preference(
130                 'PatronSelfRegistrationVerifyByEmail')
131           )
132         {
133             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
134                 {
135                     template_name   => "opac-registration-email-sent.tt",
136                     type            => "opac",
137                     query           => $cgi,
138                     authnotrequired => 1,
139                 }
140             );
141             $template->param( 'email' => $borrower{'email'} );
142
143             my $verification_token = md5_hex( time().{}.rand().{}.$$ );
144             while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
145                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
146             }
147
148             $borrower{password}           = random_string("..........");
149             $borrower{verification_token} = $verification_token;
150
151             Koha::Patron::Modification->new( \%borrower )->store();
152
153             #Send verification email
154             my $letter = C4::Letters::GetPreparedLetter(
155                 module      => 'members',
156                 letter_code => 'OPAC_REG_VERIFY',
157                 tables      => {
158                     borrower_modifications => $verification_token,
159                 },
160             );
161
162             C4::Letters::EnqueueLetter(
163                 {
164                     letter                 => $letter,
165                     message_transport_type => 'email',
166                     to_address             => $borrower{'email'},
167                     from_address =>
168                       C4::Context->preference('KohaAdminEmailAddress'),
169                 }
170             );
171         }
172         else {
173             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
174                 {
175                     template_name   => "opac-registration-confirmation.tt",
176                     type            => "opac",
177                     query           => $cgi,
178                     authnotrequired => 1,
179                 }
180             );
181
182             $template->param( OpacPasswordChange =>
183                   C4::Context->preference('OpacPasswordChange') );
184
185             my ( $borrowernumber, $password ) = AddMember_Opac(%borrower);
186             C4::Form::MessagingPreferences::handle_form_action($cgi, { borrowernumber => $borrowernumber }, $template, 1, C4::Context->preference('PatronSelfRegistrationDefaultCategory') ) if $borrowernumber && C4::Context->preference('EnhancedMessagingPreferences');
187
188             $template->param( password_cleartext => $password );
189             $template->param(
190                 borrower => GetMember( borrowernumber => $borrowernumber ) );
191             $template->param(
192                 PatronSelfRegistrationAdditionalInstructions =>
193                   C4::Context->preference(
194                     'PatronSelfRegistrationAdditionalInstructions')
195             );
196         }
197     }
198 }
199 elsif ( $action eq 'update' ) {
200
201     my $borrower = GetMember( borrowernumber => $borrowernumber );
202     die "Wrong CSRF token"
203         unless Koha::Token->new->check_csrf({
204             session_id => scalar $cgi->cookie('CGISESSID'),
205             token  => scalar $cgi->param('csrf_token'),
206         });
207
208     my %borrower = ParseCgiForBorrower($cgi);
209     $borrower{borrowernumber} = $borrowernumber;
210
211     my %borrower_changes = DelEmptyFields(%borrower);
212     my @empty_mandatory_fields =
213       CheckMandatoryFields( \%borrower_changes, $action );
214     my $invalidformfields = CheckForInvalidFields(\%borrower);
215
216     # Send back the data to the template
217     %borrower = ( %$borrower, %borrower );
218
219     if (@empty_mandatory_fields || @$invalidformfields) {
220         $template->param(
221             empty_mandatory_fields => \@empty_mandatory_fields,
222             invalid_form_fields    => $invalidformfields,
223             borrower               => \%borrower,
224             csrf_token             => Koha::Token->new->generate_csrf({
225                 session_id => scalar $cgi->cookie('CGISESSID'),
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                     session_id => scalar $cgi->cookie('CGISESSID'),
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             session_id => scalar $cgi->cookie('CGISESSID'),
288         }),
289     );
290
291     if (C4::Context->preference('OPACpatronimages')) {
292         my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
293         $template->param( display_patron_image => 1 ) if $patron_image;
294     }
295
296 }
297
298 my $captcha = random_string("CCCCC");
299
300 $template->param(
301     captcha        => $captcha,
302     captcha_digest => md5_base64($captcha)
303 );
304
305 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
306
307 sub GetHiddenFields {
308     my ( $mandatory, $action ) = @_;
309     my %hidden_fields;
310
311     my $BorrowerUnwantedField = $action eq 'modification' ?
312       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
313       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
314
315     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
316     foreach (@fields) {
317         next unless m/\w/o;
318         #Don't hide mandatory fields
319         next if $mandatory->{$_};
320         $hidden_fields{$_} = 1;
321     }
322
323     return \%hidden_fields;
324 }
325
326 sub GetMandatoryFields {
327     my ($action) = @_;
328
329     my %mandatory_fields;
330
331     my $BorrowerMandatoryField =
332       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
333
334     my @fields = split( /\|/, $BorrowerMandatoryField );
335
336     foreach (@fields) {
337         $mandatory_fields{$_} = 1;
338     }
339
340     if ( $action eq 'create' || $action eq 'new' ) {
341         $mandatory_fields{'email'} = 1
342           if C4::Context->boolean_preference(
343             'PatronSelfRegistrationVerifyByEmail');
344     }
345
346     return \%mandatory_fields;
347 }
348
349 sub CheckMandatoryFields {
350     my ( $borrower, $action ) = @_;
351
352     my @empty_mandatory_fields;
353
354     my $mandatory_fields = GetMandatoryFields($action);
355     delete $mandatory_fields->{'cardnumber'};
356
357     foreach my $key ( keys %$mandatory_fields ) {
358         push( @empty_mandatory_fields, $key )
359           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
360     }
361
362     return @empty_mandatory_fields;
363 }
364
365 sub CheckForInvalidFields {
366     my $minpw = C4::Context->preference('minPasswordLength');
367     my $borrower = shift;
368     my @invalidFields;
369     if ($borrower->{'email'}) {
370         unless ( Email::Valid->address($borrower->{'email'}) ) {
371             push(@invalidFields, "email");
372         } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
373             my $patrons_with_same_email = Koha::Patrons->search(
374                 {
375                     email => $borrower->{email},
376                     (
377                         exists $borrower->{borrowernumber}
378                         ? ( borrowernumber =>
379                               { '!=' => $borrower->{borrowernumber} } )
380                         : ()
381                     )
382                 }
383             )->count;
384             if ( $patrons_with_same_email ) {
385                 push @invalidFields, "duplicate_email";
386             }
387         }
388     }
389     if ($borrower->{'emailpro'}) {
390         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
391     }
392     if ($borrower->{'B_email'}) {
393         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
394     }
395     if ( $borrower->{'password'} ne $borrower->{'password2'} ){
396         push(@invalidFields, "password_match");
397     }
398     if ( $borrower->{'password'}  && $minpw && (length($borrower->{'password'}) < $minpw) ) {
399        push(@invalidFields, "password_invalid");
400     }
401     if ( $borrower->{'password'} ) {
402        push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
403     }
404
405     return \@invalidFields;
406 }
407
408 sub ParseCgiForBorrower {
409     my ($cgi) = @_;
410
411     my $scrubber = C4::Scrubber->new();
412     my %borrower;
413
414     foreach my $field ( $cgi->param ) {
415         if ( $field =~ '^borrower_' ) {
416             my ($key) = substr( $field, 9 );
417             if ( $field !~ '^borrower_password' ) {
418                 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
419             } else {
420                 # Allow html characters for passwords
421                 $borrower{$key} = $cgi->param($field);
422             }
423         }
424     }
425
426     my $dob_dt;
427     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
428         if ( $borrower{'dateofbirth'} );
429
430     if ( $dob_dt ) {
431         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
432     }
433     else {
434         # Trigger validation
435         $borrower{'dateofbirth'} = undef;
436     }
437
438     return %borrower;
439 }
440
441 sub DelUnchangedFields {
442     my ( $borrowernumber, %new_data ) = @_;
443
444     my $current_data = GetMember( borrowernumber => $borrowernumber );
445
446     foreach my $key ( keys %new_data ) {
447         if ( $current_data->{$key} eq $new_data{$key} ) {
448             delete $new_data{$key};
449         }
450     }
451
452     return %new_data;
453 }
454
455 sub DelEmptyFields {
456     my (%borrower) = @_;
457
458     foreach my $key ( keys %borrower ) {
459         delete $borrower{$key} unless $borrower{$key};
460     }
461
462     return %borrower;
463 }