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