Bug 24759: DBRev 19.12.00.051
[koha.git] / opac / opac-memberentry.pl
blob3f6d8a8735e2acd493b5e32700bed6a8a6e6fc10
1 #!/usr/bin/perl
3 # This file is part of Koha.
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.
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.
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>.
18 use Modern::Perl;
20 use CGI qw ( -utf8 );
21 use Digest::MD5 qw( md5_base64 md5_hex );
22 use JSON;
23 use List::MoreUtils qw( any each_array uniq );
24 use String::Random qw( random_string );
26 use C4::Auth;
27 use C4::Output;
28 use C4::Members;
29 use C4::Form::MessagingPreferences;
30 use Koha::AuthUtils;
31 use Koha::Patrons;
32 use Koha::Patron::Consent;
33 use Koha::Patron::Modification;
34 use Koha::Patron::Modifications;
35 use C4::Scrubber;
36 use Email::Valid;
37 use Koha::DateUtils;
38 use Koha::Libraries;
39 use Koha::Patron::Attribute::Types;
40 use Koha::Patron::Attributes;
41 use Koha::Patron::Images;
42 use Koha::Patron::Modification;
43 use Koha::Patron::Modifications;
44 use Koha::Patrons;
45 use Koha::Token;
47 my $cgi = new CGI;
48 my $dbh = C4::Context->dbh;
50 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
52 template_name => "opac-memberentry.tt",
53 type => "opac",
54 query => $cgi,
55 authnotrequired => 1,
59 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
61 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
62 exit;
65 my $action = $cgi->param('action') || q{};
66 if ( $action eq q{} ) {
67 if ($borrowernumber) {
68 $action = 'edit';
70 else {
71 $action = 'new';
75 my $mandatory = GetMandatoryFields($action);
77 my @libraries = Koha::Libraries->search;
78 if ( my @libraries_to_display = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList') ) {
79 @libraries = map { my $b = $_; my $branchcode = $_->branchcode; grep { $_ eq $branchcode } @libraries_to_display ? $b : () } @libraries;
81 my ( $min, $max ) = C4::Members::get_cardnumber_length();
82 if ( defined $min ) {
83 $template->param(
84 minlength_cardnumber => $min,
85 maxlength_cardnumber => $max
89 $template->param(
90 action => $action,
91 hidden => GetHiddenFields( $mandatory, $action ),
92 mandatory => $mandatory,
93 libraries => \@libraries,
94 OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
97 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
98 my $conflicting_attribute = 0;
100 foreach my $attr (@$attributes) {
101 my $attribute = Koha::Patron::Attribute->new($attr);
102 eval {$attribute->check_unique_id};
103 if ( $@ ) {
104 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
105 $template->param(
106 extended_unique_id_failed_code => $attr->{code},
107 extended_unique_id_failed_value => $attr->{attribute},
108 extended_unique_id_failed_description => $attr_type->description,
110 $conflicting_attribute = 1;
114 if ( $action eq 'create' ) {
116 my %borrower = ParseCgiForBorrower($cgi);
118 %borrower = DelEmptyFields(%borrower);
120 my @empty_mandatory_fields = CheckMandatoryFields( \%borrower, $action );
121 my $invalidformfields = CheckForInvalidFields(\%borrower);
122 delete $borrower{'password2'};
123 my $cardnumber_error_code;
124 if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
125 # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
126 # spurious length warning.
127 $cardnumber_error_code = checkcardnumber( $borrower{cardnumber}, $borrower{borrowernumber} );
130 if ( @empty_mandatory_fields || @$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
131 if ( $cardnumber_error_code == 1 ) {
132 $template->param( cardnumber_already_exists => 1 );
133 } elsif ( $cardnumber_error_code == 2 ) {
134 $template->param( cardnumber_wrong_length => 1 );
137 $template->param(
138 empty_mandatory_fields => \@empty_mandatory_fields,
139 invalid_form_fields => $invalidformfields,
140 borrower => \%borrower
142 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
144 elsif (
145 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
147 $template->param(
148 failed_captcha => 1,
149 borrower => \%borrower
151 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
153 else {
154 if (
155 C4::Context->boolean_preference(
156 'PatronSelfRegistrationVerifyByEmail')
159 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
161 template_name => "opac-registration-email-sent.tt",
162 type => "opac",
163 query => $cgi,
164 authnotrequired => 1,
167 $template->param( 'email' => $borrower{'email'} );
169 my $verification_token = md5_hex( time().{}.rand().{}.$$ );
170 while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
171 $verification_token = md5_hex( time().{}.rand().{}.$$ );
174 $borrower{password} = Koha::AuthUtils::generate_password unless $borrower{password};
175 $borrower{verification_token} = $verification_token;
177 Koha::Patron::Modification->new( \%borrower )->store();
179 #Send verification email
180 my $letter = C4::Letters::GetPreparedLetter(
181 module => 'members',
182 letter_code => 'OPAC_REG_VERIFY',
183 lang => 'default', # Patron does not have a preferred language defined yet
184 tables => {
185 borrower_modifications => $verification_token,
189 C4::Letters::EnqueueLetter(
191 letter => $letter,
192 message_transport_type => 'email',
193 to_address => $borrower{'email'},
194 from_address =>
195 C4::Context->preference('KohaAdminEmailAddress'),
198 my $num_letters_attempted = C4::Letters::SendQueuedMessages( {
199 letter_code => 'OPAC_REG_VERIFY'
200 } );
202 else {
203 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
205 template_name => "opac-registration-confirmation.tt",
206 type => "opac",
207 query => $cgi,
208 authnotrequired => 1,
212 $borrower{categorycode} ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
213 $borrower{password} ||= Koha::AuthUtils::generate_password;
214 my $consent_dt = delete $borrower{gdpr_proc_consent};
215 my $patron = Koha::Patron->new( \%borrower )->store;
216 Koha::Patron::Consent->new({ borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt })->store if $consent_dt;
217 if ( $patron ) {
218 $patron->extended_attributes->filter_by_branch_limitations->delete;
219 $patron->extended_attributes($attributes);
220 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
221 C4::Form::MessagingPreferences::handle_form_action(
222 $cgi,
223 { borrowernumber => $patron->borrowernumber },
224 $template,
226 C4::Context->preference('PatronSelfRegistrationDefaultCategory')
230 $template->param( password_cleartext => $patron->plain_text_password );
231 $template->param( borrower => $patron->unblessed );
232 } else {
233 # FIXME Handle possible errors here
235 $template->param(
236 PatronSelfRegistrationAdditionalInstructions =>
237 C4::Context->preference(
238 'PatronSelfRegistrationAdditionalInstructions')
243 elsif ( $action eq 'update' ) {
245 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
246 die "Wrong CSRF token"
247 unless Koha::Token->new->check_csrf({
248 session_id => scalar $cgi->cookie('CGISESSID'),
249 token => scalar $cgi->param('csrf_token'),
252 my %borrower = ParseCgiForBorrower($cgi);
253 $borrower{borrowernumber} = $borrowernumber;
255 my @empty_mandatory_fields =
256 CheckMandatoryFields( \%borrower, $action );
257 my $invalidformfields = CheckForInvalidFields(\%borrower);
259 # Send back the data to the template
260 %borrower = ( %$borrower, %borrower );
262 if (@empty_mandatory_fields || @$invalidformfields) {
263 $template->param(
264 empty_mandatory_fields => \@empty_mandatory_fields,
265 invalid_form_fields => $invalidformfields,
266 borrower => \%borrower,
267 csrf_token => Koha::Token->new->generate_csrf({
268 session_id => scalar $cgi->cookie('CGISESSID'),
271 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
273 $template->param( action => 'edit' );
275 else {
276 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
277 $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
278 my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
280 if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
281 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
283 template_name => "opac-memberentry-update-submitted.tt",
284 type => "opac",
285 query => $cgi,
286 authnotrequired => 1,
290 $borrower_changes{borrowernumber} = $borrowernumber;
291 $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
293 Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
295 my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
297 my $patron = Koha::Patrons->find( $borrowernumber );
298 $template->param( borrower => $patron->unblessed );
300 else {
301 my $patron = Koha::Patrons->find( $borrowernumber );
302 $template->param(
303 action => 'edit',
304 nochanges => 1,
305 borrower => $patron->unblessed,
306 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
307 csrf_token => Koha::Token->new->generate_csrf({
308 session_id => scalar $cgi->cookie('CGISESSID'),
314 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
315 my $patron = Koha::Patrons->find( $borrowernumber );
316 my $borrower = $patron->unblessed;
318 $template->param(
319 borrower => $borrower,
320 hidden => GetHiddenFields( $mandatory, 'edit' ),
321 csrf_token => Koha::Token->new->generate_csrf({
322 session_id => scalar $cgi->cookie('CGISESSID'),
326 if (C4::Context->preference('OPACpatronimages')) {
327 $template->param( display_patron_image => 1 ) if $patron->image;
330 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
331 } else {
332 # Render self-registration page
333 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
336 my $captcha = random_string("CCCCC");
337 my $patron_param = Koha::Patrons->find( $borrowernumber );
338 $template->param(
339 has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count
340 ) if $patron_param;
342 $template->param(
343 captcha => $captcha,
344 captcha_digest => md5_base64($captcha),
345 patron => $patron_param
348 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
350 sub GetHiddenFields {
351 my ( $mandatory, $action ) = @_;
352 my %hidden_fields;
354 my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
355 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
356 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
358 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
359 foreach (@fields) {
360 next unless m/\w/o;
361 #Don't hide mandatory fields
362 next if $mandatory->{$_};
363 $hidden_fields{$_} = 1;
366 return \%hidden_fields;
369 sub GetMandatoryFields {
370 my ($action) = @_;
372 my %mandatory_fields;
374 my $BorrowerMandatoryField =
375 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
377 my @fields = split( /\|/, $BorrowerMandatoryField );
378 push @fields, 'gdpr_proc_consent' if C4::Context->preference('GDPR_Policy') && $action eq 'create';
380 foreach (@fields) {
381 $mandatory_fields{$_} = 1;
384 if ( $action eq 'create' || $action eq 'new' ) {
385 $mandatory_fields{'email'} = 1
386 if C4::Context->boolean_preference(
387 'PatronSelfRegistrationVerifyByEmail');
390 return \%mandatory_fields;
393 sub CheckMandatoryFields {
394 my ( $borrower, $action ) = @_;
396 my @empty_mandatory_fields;
398 my $mandatory_fields = GetMandatoryFields($action);
399 delete $mandatory_fields->{'cardnumber'};
401 foreach my $key ( keys %$mandatory_fields ) {
402 push( @empty_mandatory_fields, $key )
403 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
406 return @empty_mandatory_fields;
409 sub CheckForInvalidFields {
410 my $borrower = shift;
411 my @invalidFields;
412 if ($borrower->{'email'}) {
413 unless ( Email::Valid->address($borrower->{'email'}) ) {
414 push(@invalidFields, "email");
415 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
416 my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
418 email => $borrower->{email},
420 exists $borrower->{borrowernumber}
421 ? ( borrowernumber =>
422 { '!=' => $borrower->{borrowernumber} } )
423 : ()
426 )->count;
427 if ( $patrons_with_same_email ) {
428 push @invalidFields, "duplicate_email";
432 if ($borrower->{'emailpro'}) {
433 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
435 if ($borrower->{'B_email'}) {
436 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
438 if ( defined $borrower->{'password'}
439 and $borrower->{'password'} ne $borrower->{'password2'} )
441 push( @invalidFields, "password_match" );
443 if ( $borrower->{'password'} ) {
444 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
445 unless ( $is_valid ) {
446 push @invalidFields, 'password_too_short' if $error eq 'too_short';
447 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
448 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
452 return \@invalidFields;
455 sub ParseCgiForBorrower {
456 my ($cgi) = @_;
458 my $scrubber = C4::Scrubber->new();
459 my %borrower;
461 foreach my $field ( $cgi->param ) {
462 if ( $field =~ '^borrower_' ) {
463 my ($key) = substr( $field, 9 );
464 if ( $field !~ '^borrower_password' ) {
465 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
466 } else {
467 # Allow html characters for passwords
468 $borrower{$key} = $cgi->param($field);
473 my $dob_dt;
474 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
475 if ( $borrower{'dateofbirth'} );
477 if ( $dob_dt ) {
478 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
480 else {
481 # Trigger validation
482 $borrower{'dateofbirth'} = undef;
485 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
486 $borrower{gdpr_proc_consent} = dt_from_string if $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed';
488 return %borrower;
491 sub DelUnchangedFields {
492 my ( $borrowernumber, %new_data ) = @_;
493 # get the mandatory fields so we can get the hidden fields
494 my $mandatory = GetMandatoryFields('edit');
495 my $patron = Koha::Patrons->find( $borrowernumber );
496 my $current_data = $patron->unblessed;
497 # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
498 my $hidden_fields = GetHiddenFields($mandatory, 'edit');
501 foreach my $key ( keys %new_data ) {
502 next if defined($new_data{$key}) xor defined($current_data->{$key});
503 if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
504 delete $new_data{$key};
508 return %new_data;
511 sub DelEmptyFields {
512 my (%borrower) = @_;
514 foreach my $key ( keys %borrower ) {
515 delete $borrower{$key} unless $borrower{$key};
518 return %borrower;
521 sub FilterUnchangedAttributes {
522 my ( $borrowernumber, $entered_attributes ) = @_;
524 my @patron_attributes = grep {$_->type->opac_editable ? $_ : ()} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
526 my $patron_attribute_types;
527 foreach my $attr (@patron_attributes) {
528 $patron_attribute_types->{ $attr->code } += 1;
531 my $passed_attribute_types;
532 foreach my $attr (@{ $entered_attributes }) {
533 $passed_attribute_types->{ $attr->{ code } } += 1;
536 my @changed_attributes;
538 # Loop through the current patron attributes
539 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
540 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
541 # count differs, overwrite all attributes for given type
542 foreach my $attr (@{ $entered_attributes }) {
543 push @changed_attributes, $attr
544 if $attr->{ code } eq $attribute_type;
546 } else {
547 # count matches, check values
548 my $changes = 0;
549 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
550 $changes = 1
551 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
552 last if $changes;
555 if ( $changes ) {
556 foreach my $attr (@{ $entered_attributes }) {
557 push @changed_attributes, $attr
558 if $attr->{ code } eq $attribute_type;
564 # Loop through passed attributes, looking for new ones
565 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
566 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
567 # YAY, new stuff
568 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
569 push @changed_attributes, $attr;
574 return \@changed_attributes;
577 sub GeneratePatronAttributesForm {
578 my ( $borrowernumber, $entered_attributes ) = @_;
580 # Get all attribute types and the values for this patron (if applicable)
581 my @types = grep { $_->opac_editable() or $_->opac_display }
582 Koha::Patron::Attribute::Types->search()->as_list();
583 if ( scalar(@types) == 0 ) {
584 return [];
587 my @displayable_attributes = grep { $_->type->opac_display ? $_ : () }
588 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
590 my %attr_values = ();
592 # Build the attribute values list either from the passed values
593 # or taken from the patron itself
594 if ( defined $entered_attributes ) {
595 foreach my $attr (@$entered_attributes) {
596 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
599 elsif ( defined $borrowernumber ) {
600 my @editable_attributes = grep { $_->type->opac_editable ? $_ : () } @displayable_attributes;
601 foreach my $attr (@editable_attributes) {
602 push @{ $attr_values{ $attr->code } }, $attr->attribute;
606 # Add the non-editable attributes (that don't come from the form)
607 foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
608 push @{ $attr_values{ $attr->code } }, $attr->attribute;
611 # Find all existing classes
612 my @classes = sort( uniq( map { $_->class } @types ) );
613 my %items_by_class;
615 foreach my $attr_type (@types) {
616 push @{ $items_by_class{ $attr_type->class() } }, {
617 type => $attr_type,
618 # If editable, make sure there's at least one empty entry,
619 # to make the template's job easier
620 values => $attr_values{ $attr_type->code() } || ['']
622 unless !defined $attr_values{ $attr_type->code() }
623 and !$attr_type->opac_editable;
626 # Finally, build a list of containing classes
627 my @class_loop;
628 foreach my $class (@classes) {
629 next unless ( $items_by_class{$class} );
631 my $av = Koha::AuthorisedValues->search(
632 { category => 'PA_CLASS', authorised_value => $class } );
634 my $lib = $av->count ? $av->next->opac_description : $class;
636 push @class_loop,
638 class => $class,
639 items => $items_by_class{$class},
640 lib => $lib,
644 return \@class_loop;
647 sub ParsePatronAttributes {
648 my ( $borrowernumber, $cgi ) = @_;
650 my @codes = $cgi->multi_param('patron_attribute_code');
651 my @values = $cgi->multi_param('patron_attribute_value');
653 my @editable_attribute_types
654 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
656 my $ea = each_array( @codes, @values );
657 my @attributes;
659 my $delete_candidates = {};
661 while ( my ( $code, $value ) = $ea->() ) {
662 if ( any { $_ eq $code } @editable_attribute_types ) {
663 # It is an editable attribute
664 if ( !defined($value) or $value eq '' ) {
665 $delete_candidates->{$code} = 1
666 unless $delete_candidates->{$code};
668 else {
669 # we've got a value
670 push @attributes, { code => $code, attribute => $value };
672 # 'code' is no longer a delete candidate
673 delete $delete_candidates->{$code}
674 if defined $delete_candidates->{$code};
679 foreach my $code ( keys %{$delete_candidates} ) {
680 if ( Koha::Patron::Attributes->search({
681 borrowernumber => $borrowernumber, code => $code })->count > 0 )
683 push @attributes, { code => $code, attribute => '' }
684 unless any { $_->{code} eq $code } @attributes;
688 return \@attributes;