Revert "Bug 14598: Fix warning from effective_itemtype"
[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( time().{}.rand().{}.$$ );
127
128             while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
129                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
130             }
131
132             $borrower{'password'} = random_string("..........");
133
134             Koha::Patron::Modifications->new(
135                 verification_token => $verification_token )
136               ->AddModifications(\%borrower);
137
138             #Send verification email
139             my $letter = C4::Letters::GetPreparedLetter(
140                 module      => 'members',
141                 letter_code => 'OPAC_REG_VERIFY',
142                 tables      => {
143                     borrower_modifications => $verification_token,
144                 },
145             );
146
147             C4::Letters::EnqueueLetter(
148                 {
149                     letter                 => $letter,
150                     message_transport_type => 'email',
151                     to_address             => $borrower{'email'},
152                     from_address =>
153                       C4::Context->preference('KohaAdminEmailAddress'),
154                 }
155             );
156         }
157         else {
158             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
159                 {
160                     template_name   => "opac-registration-confirmation.tt",
161                     type            => "opac",
162                     query           => $cgi,
163                     authnotrequired => 1,
164                 }
165             );
166
167             $template->param( OpacPasswordChange =>
168                   C4::Context->preference('OpacPasswordChange') );
169
170             my ( $borrowernumber, $password ) = AddMember_Opac(%borrower);
171             C4::Form::MessagingPreferences::handle_form_action($cgi, { borrowernumber => $borrowernumber }, $template, 1, C4::Context->preference('PatronSelfRegistrationDefaultCategory') ) if $borrowernumber && C4::Context->preference('EnhancedMessagingPreferences');
172
173             $template->param( password_cleartext => $password );
174             $template->param(
175                 borrower => GetMember( borrowernumber => $borrowernumber ) );
176             $template->param(
177                 PatronSelfRegistrationAdditionalInstructions =>
178                   C4::Context->preference(
179                     'PatronSelfRegistrationAdditionalInstructions')
180             );
181         }
182     }
183 }
184 elsif ( $action eq 'update' ) {
185
186     my $borrower = GetMember( borrowernumber => $borrowernumber );
187     my %borrower = ParseCgiForBorrower($cgi);
188
189     my %borrower_changes = DelEmptyFields(%borrower);
190     my @empty_mandatory_fields =
191       CheckMandatoryFields( \%borrower_changes, $action );
192     my $invalidformfields = CheckForInvalidFields(\%borrower);
193
194     # Send back the data to the template
195     %borrower = ( %$borrower, %borrower );
196
197     if (@empty_mandatory_fields || @$invalidformfields) {
198         $template->param(
199             empty_mandatory_fields => \@empty_mandatory_fields,
200             invalid_form_fields    => $invalidformfields,
201             borrower               => \%borrower
202         );
203
204         $template->param( action => 'edit' );
205     }
206     else {
207         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
208         if (%borrower_changes) {
209             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
210                 {
211                     template_name   => "opac-memberentry-update-submitted.tt",
212                     type            => "opac",
213                     query           => $cgi,
214                     authnotrequired => 1,
215                 }
216             );
217
218             my $m =
219               Koha::Patron::Modifications->new(
220                 borrowernumber => $borrowernumber );
221
222             $m->DelModifications;
223             $m->AddModifications(\%borrower_changes);
224             $template->param(
225                 borrower => GetMember( borrowernumber => $borrowernumber ),
226             );
227         }
228         else {
229             $template->param(
230                 action => 'edit',
231                 nochanges => 1,
232                 borrower => GetMember( borrowernumber => $borrowernumber ),
233             );
234         }
235     }
236 }
237 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
238     my $borrower = GetMember( borrowernumber => $borrowernumber );
239
240     if (C4::Context->preference('ExtendedPatronAttributes')) {
241         my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber, 'opac');
242         if (scalar(@$attributes) > 0) {
243             $borrower->{ExtendedPatronAttributes} = 1;
244             $borrower->{patron_attributes} = $attributes;
245         }
246     }
247
248     $template->param(
249         borrower  => $borrower,
250         guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
251         hidden => GetHiddenFields( $mandatory, 'modification' ),
252     );
253
254     if (C4::Context->preference('OPACpatronimages')) {
255         my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
256         $template->param( display_patron_image => 1 ) if $patron_image;
257     }
258
259 }
260
261 my $captcha = random_string("CCCCC");
262
263 $template->param(
264     captcha        => $captcha,
265     captcha_digest => md5_base64($captcha)
266 );
267
268 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
269
270 sub GetHiddenFields {
271     my ( $mandatory, $action ) = @_;
272     my %hidden_fields;
273
274     my $BorrowerUnwantedField = $action eq 'modification' ?
275       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
276       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
277
278     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
279     foreach (@fields) {
280         next unless m/\w/o;
281         #Don't hide mandatory fields
282         next if $mandatory->{$_};
283         $hidden_fields{$_} = 1;
284     }
285
286     return \%hidden_fields;
287 }
288
289 sub GetMandatoryFields {
290     my ($action) = @_;
291
292     my %mandatory_fields;
293
294     my $BorrowerMandatoryField =
295       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
296
297     my @fields = split( /\|/, $BorrowerMandatoryField );
298
299     foreach (@fields) {
300         $mandatory_fields{$_} = 1;
301     }
302
303     if ( $action eq 'create' || $action eq 'new' ) {
304         $mandatory_fields{'email'} = 1
305           if C4::Context->boolean_preference(
306             'PatronSelfRegistrationVerifyByEmail');
307     }
308
309     return \%mandatory_fields;
310 }
311
312 sub CheckMandatoryFields {
313     my ( $borrower, $action ) = @_;
314
315     my @empty_mandatory_fields;
316
317     my $mandatory_fields = GetMandatoryFields($action);
318     delete $mandatory_fields->{'cardnumber'};
319
320     foreach my $key ( keys %$mandatory_fields ) {
321         push( @empty_mandatory_fields, $key )
322           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
323     }
324
325     return @empty_mandatory_fields;
326 }
327
328 sub CheckForInvalidFields {
329     my $minpw = C4::Context->preference('minPasswordLength');
330     my $borrower = shift;
331     my @invalidFields;
332     if ($borrower->{'email'}) {
333         push(@invalidFields, "email") if (!Email::Valid->address($borrower->{'email'}));
334     }
335     if ($borrower->{'emailpro'}) {
336         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
337     }
338     if ($borrower->{'B_email'}) {
339         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
340     }
341     if ( $borrower->{'password'} ne $borrower->{'password2'} ){
342         push(@invalidFields, "password_match");
343     }
344     if ( $borrower->{'password'}  && $minpw && (length($borrower->{'password'}) < $minpw) ) {
345        push(@invalidFields, "password_invalid");
346     }
347     if ( $borrower->{'password'} ) {
348        push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
349     }
350
351     return \@invalidFields;
352 }
353
354 sub ParseCgiForBorrower {
355     my ($cgi) = @_;
356
357     my $scrubber = C4::Scrubber->new();
358     my %borrower;
359
360     foreach ( $cgi->param ) {
361         if ( $_ =~ '^borrower_' ) {
362             my ($key) = substr( $_, 9 );
363             $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
364         }
365     }
366
367     my $dob_dt;
368     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
369         if ( $borrower{'dateofbirth'} );
370
371     if ( $dob_dt ) {
372         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
373     }
374     else {
375         # Trigger validation
376         $borrower{'dateofbirth'} = undef;
377     }
378
379     return %borrower;
380 }
381
382 sub DelUnchangedFields {
383     my ( $borrowernumber, %new_data ) = @_;
384
385     my $current_data = GetMember( borrowernumber => $borrowernumber );
386
387     foreach my $key ( keys %new_data ) {
388         if ( $current_data->{$key} eq $new_data{$key} ) {
389             delete $new_data{$key};
390         }
391     }
392
393     return %new_data;
394 }
395
396 sub DelEmptyFields {
397     my (%borrower) = @_;
398
399     foreach my $key ( keys %borrower ) {
400         delete $borrower{$key} unless $borrower{$key};
401     }
402
403     return %borrower;
404 }