Bug 16847: Remove C4::Members::GetTitles
[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 WWW::CSRF qw(generate_csrf_token check_csrf_token CSRF_OK);
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::Modifications;
31 use C4::Branch qw(GetBranchesLoop);
32 use C4::Scrubber;
33 use Email::Valid;
34 use Koha::DateUtils;
35 use Koha::Patron::Images;
36
37 my $cgi = new CGI;
38 my $dbh = C4::Context->dbh;
39
40 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
41     {
42         template_name   => "opac-memberentry.tt",
43         type            => "opac",
44         query           => $cgi,
45         authnotrequired => 1,
46     }
47 );
48
49 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
50 {
51     print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
52     exit;
53 }
54
55 my $action = $cgi->param('action') || q{};
56 if ( $action eq q{} ) {
57     if ($borrowernumber) {
58         $action = 'edit';
59     }
60     else {
61         $action = 'new';
62     }
63 }
64
65 my $mandatory = GetMandatoryFields($action);
66
67 $template->param(
68     action            => $action,
69     hidden            => GetHiddenFields( $mandatory, 'registration' ),
70     mandatory         => $mandatory,
71     branches          => GetBranchesLoop(),
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             $borrower{'password'} = random_string("..........");
130
131             Koha::Patron::Modifications->new(
132                 verification_token => $verification_token )
133               ->AddModifications(\%borrower);
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     my $csrf_status = check_csrf_token($borrower->{userid}, md5_base64(C4::Context->config('pass')), scalar $cgi->param('csrf_token'));
185     die "Wrong CSRF token" unless ($csrf_status == CSRF_OK);
186
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     if (@empty_mandatory_fields || @$invalidformfields) {
195         $template->param(
196             empty_mandatory_fields => \@empty_mandatory_fields,
197             invalid_form_fields    => $invalidformfields,
198             borrower               => \%borrower,
199             csrf_token             => generate_csrf_token($borrower->{userid}, md5_base64(C4::Context->config('pass'))),
200         );
201
202         $template->param( action => 'edit' );
203     }
204     else {
205         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
206         if (%borrower_changes) {
207             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
208                 {
209                     template_name   => "opac-memberentry-update-submitted.tt",
210                     type            => "opac",
211                     query           => $cgi,
212                     authnotrequired => 1,
213                 }
214             );
215
216             my $m =
217               Koha::Patron::Modifications->new(
218                 borrowernumber => $borrowernumber );
219
220             $m->DelModifications;
221             $m->AddModifications(\%borrower_changes);
222             $template->param(
223                 borrower => GetMember( borrowernumber => $borrowernumber ),
224             );
225         }
226         else {
227             $template->param(
228                 action => 'edit',
229                 nochanges => 1,
230                 borrower => GetMember( borrowernumber => $borrowernumber ),
231                 csrf_token => generate_csrf_token($borrower->{userid}, md5_base64(C4::Context->config('pass')))
232             );
233         }
234     }
235 }
236 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
237     my $borrower = GetMember( borrowernumber => $borrowernumber );
238
239     if (C4::Context->preference('ExtendedPatronAttributes')) {
240         my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber, 'opac');
241         if (scalar(@$attributes) > 0) {
242             $borrower->{ExtendedPatronAttributes} = 1;
243             $borrower->{patron_attributes} = $attributes;
244         }
245     }
246
247     $template->param(
248         borrower  => $borrower,
249         guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
250         hidden => GetHiddenFields( $mandatory, 'modification' ),
251         csrf_token => generate_csrf_token($borrower->{userid}, md5_base64(C4::Context->config('pass')))
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( $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 }