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