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