Bug 5260: Follow-up - Reindenting POD of SendAlerts
[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( \%borrower );
142
143             $borrower{password}           = random_string("..........");
144             $borrower{verification_token} = $verification_token;
145
146             Koha::Patron::Modification->new( \%borrower )->store();
147
148             #Send verification email
149             my $letter = C4::Letters::GetPreparedLetter(
150                 module      => 'members',
151                 letter_code => 'OPAC_REG_VERIFY',
152                 tables      => {
153                     borrower_modifications => $verification_token,
154                 },
155             );
156
157             C4::Letters::EnqueueLetter(
158                 {
159                     letter                 => $letter,
160                     message_transport_type => 'email',
161                     to_address             => $borrower{'email'},
162                     from_address =>
163                       C4::Context->preference('KohaAdminEmailAddress'),
164                 }
165             );
166         }
167         else {
168             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
169                 {
170                     template_name   => "opac-registration-confirmation.tt",
171                     type            => "opac",
172                     query           => $cgi,
173                     authnotrequired => 1,
174                 }
175             );
176
177             $template->param( OpacPasswordChange =>
178                   C4::Context->preference('OpacPasswordChange') );
179
180             my ( $borrowernumber, $password ) = AddMember_Opac(%borrower);
181             C4::Form::MessagingPreferences::handle_form_action($cgi, { borrowernumber => $borrowernumber }, $template, 1, C4::Context->preference('PatronSelfRegistrationDefaultCategory') ) if $borrowernumber && C4::Context->preference('EnhancedMessagingPreferences');
182
183             $template->param( password_cleartext => $password );
184             $template->param(
185                 borrower => GetMember( borrowernumber => $borrowernumber ) );
186             $template->param(
187                 PatronSelfRegistrationAdditionalInstructions =>
188                   C4::Context->preference(
189                     'PatronSelfRegistrationAdditionalInstructions')
190             );
191         }
192     }
193 }
194 elsif ( $action eq 'update' ) {
195
196     my $borrower = GetMember( borrowernumber => $borrowernumber );
197     die "Wrong CSRF token"
198         unless Koha::Token->new->check_csrf({
199             id     => $borrower->{userid},
200             secret => md5_base64( C4::Context->config('pass') ),
201             token  => scalar $cgi->param('csrf_token'),
202         });
203
204     my %borrower = ParseCgiForBorrower($cgi);
205
206     my %borrower_changes = DelEmptyFields(%borrower);
207     my @empty_mandatory_fields =
208       CheckMandatoryFields( \%borrower_changes, $action );
209     my $invalidformfields = CheckForInvalidFields(\%borrower);
210
211     # Send back the data to the template
212     %borrower = ( %$borrower, %borrower );
213
214     if (@empty_mandatory_fields || @$invalidformfields) {
215         $template->param(
216             empty_mandatory_fields => \@empty_mandatory_fields,
217             invalid_form_fields    => $invalidformfields,
218             borrower               => \%borrower,
219             csrf_token             => Koha::Token->new->generate_csrf({
220                 id     => $borrower->{userid},
221                 secret => md5_base64( C4::Context->config('pass') ),
222             }),
223         );
224
225         $template->param( action => 'edit' );
226     }
227     else {
228         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
229         if (%borrower_changes) {
230             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
231                 {
232                     template_name   => "opac-memberentry-update-submitted.tt",
233                     type            => "opac",
234                     query           => $cgi,
235                     authnotrequired => 1,
236                 }
237             );
238
239             $borrower_changes{borrowernumber} = $borrowernumber;
240
241             # FIXME update the following with
242             # Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
243             # when bug 17091 will be pushed
244             my $patron_modifications = Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber });
245             while ( my $patron_modification = $patron_modifications->next ) {
246                 $patron_modification->delete;
247             }
248
249             my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
250
251             $template->param(
252                 borrower => GetMember( borrowernumber => $borrowernumber ),
253             );
254         }
255         else {
256             $template->param(
257                 action => 'edit',
258                 nochanges => 1,
259                 borrower => GetMember( borrowernumber => $borrowernumber ),
260                 csrf_token => Koha::Token->new->generate_csrf({
261                     id     => $borrower->{userid},
262                     secret => md5_base64( C4::Context->config('pass') ),
263                 }),
264             );
265         }
266     }
267 }
268 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
269     my $borrower = GetMember( borrowernumber => $borrowernumber );
270
271     if (C4::Context->preference('ExtendedPatronAttributes')) {
272         my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber, 'opac');
273         if (scalar(@$attributes) > 0) {
274             $borrower->{ExtendedPatronAttributes} = 1;
275             $borrower->{patron_attributes} = $attributes;
276         }
277     }
278
279     $template->param(
280         borrower  => $borrower,
281         guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
282         hidden => GetHiddenFields( $mandatory, 'modification' ),
283         csrf_token => Koha::Token->new->generate_csrf({
284             id     => $borrower->{userid},
285             secret => md5_base64( C4::Context->config('pass') ),
286         }),
287     );
288
289     if (C4::Context->preference('OPACpatronimages')) {
290         my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
291         $template->param( display_patron_image => 1 ) if $patron_image;
292     }
293
294 }
295
296 my $captcha = random_string("CCCCC");
297
298 $template->param(
299     captcha        => $captcha,
300     captcha_digest => md5_base64($captcha)
301 );
302
303 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
304
305 sub GetHiddenFields {
306     my ( $mandatory, $action ) = @_;
307     my %hidden_fields;
308
309     my $BorrowerUnwantedField = $action eq 'modification' ?
310       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
311       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
312
313     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
314     foreach (@fields) {
315         next unless m/\w/o;
316         #Don't hide mandatory fields
317         next if $mandatory->{$_};
318         $hidden_fields{$_} = 1;
319     }
320
321     return \%hidden_fields;
322 }
323
324 sub GetMandatoryFields {
325     my ($action) = @_;
326
327     my %mandatory_fields;
328
329     my $BorrowerMandatoryField =
330       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
331
332     my @fields = split( /\|/, $BorrowerMandatoryField );
333
334     foreach (@fields) {
335         $mandatory_fields{$_} = 1;
336     }
337
338     if ( $action eq 'create' || $action eq 'new' ) {
339         $mandatory_fields{'email'} = 1
340           if C4::Context->boolean_preference(
341             'PatronSelfRegistrationVerifyByEmail');
342     }
343
344     return \%mandatory_fields;
345 }
346
347 sub CheckMandatoryFields {
348     my ( $borrower, $action ) = @_;
349
350     my @empty_mandatory_fields;
351
352     my $mandatory_fields = GetMandatoryFields($action);
353     delete $mandatory_fields->{'cardnumber'};
354
355     foreach my $key ( keys %$mandatory_fields ) {
356         push( @empty_mandatory_fields, $key )
357           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
358     }
359
360     return @empty_mandatory_fields;
361 }
362
363 sub CheckForInvalidFields {
364     my $minpw = C4::Context->preference('minPasswordLength');
365     my $borrower = shift;
366     my @invalidFields;
367     if ($borrower->{'email'}) {
368         unless ( Email::Valid->address($borrower->{'email'}) ) {
369             push(@invalidFields, "email");
370         } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
371             my $patrons_with_same_email = Koha::Patrons->search( { email => $borrower->{email} })->count;
372             if ( $patrons_with_same_email ) {
373                 push @invalidFields, "duplicate_email";
374             }
375         }
376     }
377     if ($borrower->{'emailpro'}) {
378         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
379     }
380     if ($borrower->{'B_email'}) {
381         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
382     }
383     if ( $borrower->{'password'} ne $borrower->{'password2'} ){
384         push(@invalidFields, "password_match");
385     }
386     if ( $borrower->{'password'}  && $minpw && (length($borrower->{'password'}) < $minpw) ) {
387        push(@invalidFields, "password_invalid");
388     }
389     if ( $borrower->{'password'} ) {
390        push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
391     }
392
393     return \@invalidFields;
394 }
395
396 sub ParseCgiForBorrower {
397     my ($cgi) = @_;
398
399     my $scrubber = C4::Scrubber->new();
400     my %borrower;
401
402     foreach ( $cgi->param ) {
403         if ( $_ =~ '^borrower_' ) {
404             my ($key) = substr( $_, 9 );
405             $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
406         }
407     }
408
409     my $dob_dt;
410     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
411         if ( $borrower{'dateofbirth'} );
412
413     if ( $dob_dt ) {
414         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
415     }
416     else {
417         # Trigger validation
418         $borrower{'dateofbirth'} = undef;
419     }
420
421     return %borrower;
422 }
423
424 sub DelUnchangedFields {
425     my ( $borrowernumber, %new_data ) = @_;
426
427     my $current_data = GetMember( borrowernumber => $borrowernumber );
428
429     foreach my $key ( keys %new_data ) {
430         if ( $current_data->{$key} eq $new_data{$key} ) {
431             delete $new_data{$key};
432         }
433     }
434
435     return %new_data;
436 }
437
438 sub DelEmptyFields {
439     my (%borrower) = @_;
440
441     foreach my $key ( keys %borrower ) {
442         delete $borrower{$key} unless $borrower{$key};
443     }
444
445     return %borrower;
446 }