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