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