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