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>.
21 use Digest::MD5 qw( md5_base64 md5_hex );
23 use List::MoreUtils qw( any each_array uniq );
24 use String::Random qw( random_string );
30 use C4::Form::MessagingPreferences;
33 use Koha::Patron::Consent;
34 use Koha::Patron::Modification;
35 use Koha::Patron::Modifications;
40 use Koha::Patron::Attribute::Types;
41 use Koha::Patron::Attributes;
42 use Koha::Patron::Images;
43 use Koha::Patron::Modification;
44 use Koha::Patron::Modifications;
45 use Koha::Patron::Categories;
49 my $dbh = C4::Context->dbh;
51 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
53 template_name => "opac-memberentry.tt",
60 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
62 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
66 my $action = $cgi->param('action') || q{};
67 if ( $action eq q{} ) {
68 if ($borrowernumber) {
76 my $mandatory = GetMandatoryFields($action);
79 if ( $action eq 'create' || $action eq 'new' ) {
80 my @PatronSelfRegistrationLibraryList = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList');
81 $params = { branchcode => { -in => \@PatronSelfRegistrationLibraryList } }
82 if @PatronSelfRegistrationLibraryList;
84 my @libraries = Koha::Libraries->search($params);
86 my ( $min, $max ) = C4::Members::get_cardnumber_length();
89 minlength_cardnumber => $min,
90 maxlength_cardnumber => $max
94 my $defaultCategory = Koha::Patron::Categories->find(C4::Context->preference('PatronSelfRegistrationDefaultCategory'));
98 hidden => GetHiddenFields( $mandatory, $action ),
99 mandatory => $mandatory,
100 libraries => \@libraries,
101 OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
102 defaultCategory => $defaultCategory,
105 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
106 my $conflicting_attribute = 0;
108 foreach my $attr (@$attributes) {
109 my $attribute = Koha::Patron::Attribute->new($attr);
110 eval {$attribute->check_unique_id};
112 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
114 extended_unique_id_failed_code => $attr->{code},
115 extended_unique_id_failed_value => $attr->{attribute},
116 extended_unique_id_failed_description => $attr_type->description,
118 $conflicting_attribute = 1;
122 if ( $action eq 'create' ) {
124 my %borrower = ParseCgiForBorrower($cgi);
126 %borrower = DelEmptyFields(%borrower);
127 $borrower{categorycode} ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
129 my @empty_mandatory_fields = (CheckMandatoryFields( \%borrower, $action ), CheckMandatoryAttributes( \%borrower, $attributes ) );
130 my $invalidformfields = CheckForInvalidFields(\%borrower);
131 delete $borrower{'password2'};
132 my $cardnumber_error_code;
133 if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
134 # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
135 # spurious length warning.
136 $cardnumber_error_code = checkcardnumber( $borrower{cardnumber}, $borrower{borrowernumber} );
139 if ( @empty_mandatory_fields || @$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
140 if ( $cardnumber_error_code == 1 ) {
141 $template->param( cardnumber_already_exists => 1 );
142 } elsif ( $cardnumber_error_code == 2 ) {
143 $template->param( cardnumber_wrong_length => 1 );
147 empty_mandatory_fields => \@empty_mandatory_fields,
148 invalid_form_fields => $invalidformfields,
149 borrower => \%borrower
151 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
154 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
158 borrower => \%borrower
160 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
161 } elsif ( ! grep { $borrower{branchcode} eq $_->branchcode } @libraries ) {
162 die "Branchcode not allowed"; # They hack the form
166 C4::Context->boolean_preference(
167 'PatronSelfRegistrationVerifyByEmail')
170 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
172 template_name => "opac-registration-email-sent.tt",
175 authnotrequired => 1,
178 $template->param( 'email' => $borrower{'email'} );
180 my $verification_token = md5_hex( time().{}.rand().{}.$$ );
181 while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
182 $verification_token = md5_hex( time().{}.rand().{}.$$ );
185 $borrower{password} = Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode})) unless $borrower{password};
186 $borrower{verification_token} = $verification_token;
188 Koha::Patron::Modification->new( \%borrower )->store();
190 #Send verification email
191 my $letter = C4::Letters::GetPreparedLetter(
193 letter_code => 'OPAC_REG_VERIFY',
194 lang => 'default', # Patron does not have a preferred language defined yet
196 borrower_modifications => $verification_token,
200 my $message_id = C4::Letters::EnqueueLetter(
203 message_transport_type => 'email',
204 to_address => $borrower{'email'},
206 C4::Context->preference('KohaAdminEmailAddress'),
209 C4::Letters::SendQueuedMessages({ message_id => $message_id });
212 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
214 template_name => "opac-registration-confirmation.tt",
217 authnotrequired => 1,
221 $borrower{password} ||= Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode}));
222 my $consent_dt = delete $borrower{gdpr_proc_consent};
223 my $patron = Koha::Patron->new( \%borrower )->store;
224 Koha::Patron::Consent->new({ borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt })->store if $consent_dt;
226 $patron->extended_attributes->filter_by_branch_limitations->delete;
227 $patron->extended_attributes($attributes);
228 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
229 C4::Form::MessagingPreferences::handle_form_action(
231 { borrowernumber => $patron->borrowernumber },
234 C4::Context->preference('PatronSelfRegistrationDefaultCategory')
238 $template->param( password_cleartext => $patron->plain_text_password );
239 $template->param( borrower => $patron->unblessed );
241 # FIXME Handle possible errors here
244 PatronSelfRegistrationAdditionalInstructions =>
245 C4::Context->preference(
246 'PatronSelfRegistrationAdditionalInstructions')
251 elsif ( $action eq 'update' ) {
253 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
254 die "Wrong CSRF token"
255 unless Koha::Token->new->check_csrf({
256 session_id => scalar $cgi->cookie('CGISESSID'),
257 token => scalar $cgi->param('csrf_token'),
260 my %borrower = ParseCgiForBorrower($cgi);
261 $borrower{borrowernumber} = $borrowernumber;
263 my @empty_mandatory_fields = grep { $_ ne 'password' } # password is not required when editing personal details
264 ( CheckMandatoryFields( \%borrower, $action ), CheckMandatoryAttributes( \%borrower, $attributes ) );
265 my $invalidformfields = CheckForInvalidFields(\%borrower);
267 # Send back the data to the template
268 %borrower = ( %$borrower, %borrower );
270 if (@empty_mandatory_fields || @$invalidformfields) {
272 empty_mandatory_fields => \@empty_mandatory_fields,
273 invalid_form_fields => $invalidformfields,
274 borrower => \%borrower,
275 csrf_token => Koha::Token->new->generate_csrf({
276 session_id => scalar $cgi->cookie('CGISESSID'),
279 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
281 $template->param( action => 'edit' );
284 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
285 $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
286 my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
288 if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
289 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
291 template_name => "opac-memberentry-update-submitted.tt",
294 authnotrequired => 1,
298 $borrower_changes{borrowernumber} = $borrowernumber;
299 $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
301 Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
303 my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
304 #Automatically approve patron profile changes if set in syspref
306 if (C4::Context->preference('AutoApprovePatronProfileSettings')) {
307 # Need to get the object from database, otherwise it is not complete enough to allow deletion
308 # when approval has been performed.
309 my $tmp_m = Koha::Patron::Modifications->find({borrowernumber => $borrowernumber});
310 $tmp_m->approve() if $tmp_m;
313 my $patron = Koha::Patrons->find( $borrowernumber );
314 $template->param( borrower => $patron->unblessed );
317 my $patron = Koha::Patrons->find( $borrowernumber );
321 borrower => $patron->unblessed,
322 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
323 csrf_token => Koha::Token->new->generate_csrf({
324 session_id => scalar $cgi->cookie('CGISESSID'),
330 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
331 my $patron = Koha::Patrons->find( $borrowernumber );
332 my $borrower = $patron->unblessed;
335 borrower => $borrower,
336 hidden => GetHiddenFields( $mandatory, 'edit' ),
337 csrf_token => Koha::Token->new->generate_csrf({
338 session_id => scalar $cgi->cookie('CGISESSID'),
342 if (C4::Context->preference('OPACpatronimages')) {
343 $template->param( display_patron_image => 1 ) if $patron->image;
346 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
348 # Render self-registration page
349 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
352 my $captcha = random_string("CCCCC");
353 my $patron_param = Koha::Patrons->find( $borrowernumber );
355 has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count
360 captcha_digest => md5_base64($captcha),
361 patron => $patron_param
364 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
366 sub GetHiddenFields {
367 my ( $mandatory, $action ) = @_;
370 my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
371 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
372 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
374 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
377 #Don't hide mandatory fields
378 next if $mandatory->{$_};
379 $hidden_fields{$_} = 1;
382 return \%hidden_fields;
385 sub GetMandatoryFields {
388 my %mandatory_fields;
390 my $BorrowerMandatoryField =
391 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
393 my @fields = split( /\|/, $BorrowerMandatoryField );
394 push @fields, 'gdpr_proc_consent' if C4::Context->preference('GDPR_Policy') && $action eq 'create';
397 $mandatory_fields{$_} = 1;
400 if ( $action eq 'create' || $action eq 'new' ) {
401 $mandatory_fields{'email'} = 1
402 if C4::Context->boolean_preference(
403 'PatronSelfRegistrationVerifyByEmail');
406 return \%mandatory_fields;
409 sub CheckMandatoryFields {
410 my ( $borrower, $action ) = @_;
412 my @empty_mandatory_fields;
414 my $mandatory_fields = GetMandatoryFields($action);
415 delete $mandatory_fields->{'cardnumber'};
417 foreach my $key ( keys %$mandatory_fields ) {
418 push( @empty_mandatory_fields, $key )
419 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
422 return @empty_mandatory_fields;
425 sub CheckMandatoryAttributes{
426 my ( $borrower, $attributes ) = @_;
428 my @empty_mandatory_fields;
430 for my $attribute (@$attributes ) {
431 my $attr = Koha::Patron::Attribute::Types->find($attribute->{code});
432 push @empty_mandatory_fields, $attribute->{code}
433 if $attr && $attr->mandatory && $attribute->{attribute} =~ m|^\s*$|;
436 return @empty_mandatory_fields;
439 sub CheckForInvalidFields {
440 my $borrower = shift;
442 if ($borrower->{'email'}) {
443 unless ( Email::Valid->address($borrower->{'email'}) ) {
444 push(@invalidFields, "email");
445 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
446 my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
448 email => $borrower->{email},
450 exists $borrower->{borrowernumber}
451 ? ( borrowernumber =>
452 { '!=' => $borrower->{borrowernumber} } )
457 if ( $patrons_with_same_email ) {
458 push @invalidFields, "duplicate_email";
460 } elsif ( C4::Context->preference("PatronSelfRegistrationConfirmEmail")
461 && $borrower->{'email'} ne $borrower->{'repeat_email'}
462 && !defined $borrower->{borrowernumber} ) {
463 push @invalidFields, "email_match";
465 # email passed all tests, so prevent attempting to store repeat_email
466 delete $borrower->{'repeat_email'};
468 if ($borrower->{'emailpro'}) {
469 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
471 if ($borrower->{'B_email'}) {
472 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
474 if ( defined $borrower->{'password'}
475 and $borrower->{'password'} ne $borrower->{'password2'} )
477 push( @invalidFields, "password_match" );
479 if ( $borrower->{'password'} ) {
480 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password}, Koha::Patron::Categories->find($borrower->{categorycode}||C4::Context->preference('PatronSelfRegistrationDefaultCategory')) );
481 unless ( $is_valid ) {
482 push @invalidFields, 'password_too_short' if $error eq 'too_short';
483 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
484 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
488 return \@invalidFields;
491 sub ParseCgiForBorrower {
494 my $scrubber = C4::Scrubber->new();
497 foreach my $field ( $cgi->param ) {
498 if ( $field =~ '^borrower_' ) {
499 my ($key) = substr( $field, 9 );
500 if ( $field !~ '^borrower_password' ) {
501 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
503 # Allow html characters for passwords
504 $borrower{$key} = $cgi->param($field);
509 if ( defined $borrower{'dateofbirth'} ) {
511 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
512 if ( $borrower{'dateofbirth'} );
515 $borrower{'dateofbirth'} = output_pref( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
519 $borrower{'dateofbirth'} = undef;
523 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
524 $borrower{gdpr_proc_consent} = dt_from_string if $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed';
529 sub DelUnchangedFields {
530 my ( $borrowernumber, %new_data ) = @_;
531 # get the mandatory fields so we can get the hidden fields
532 my $mandatory = GetMandatoryFields('edit');
533 my $patron = Koha::Patrons->find( $borrowernumber );
534 my $current_data = $patron->unblessed;
535 # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
536 my $hidden_fields = GetHiddenFields($mandatory, 'edit');
539 foreach my $key ( keys %new_data ) {
540 next if defined($new_data{$key}) xor defined($current_data->{$key});
541 if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
542 delete $new_data{$key};
552 foreach my $key ( keys %borrower ) {
553 delete $borrower{$key} unless $borrower{$key};
559 sub FilterUnchangedAttributes {
560 my ( $borrowernumber, $entered_attributes ) = @_;
562 my @patron_attributes = grep {$_->type->opac_editable ? $_ : ()} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
564 my $patron_attribute_types;
565 foreach my $attr (@patron_attributes) {
566 $patron_attribute_types->{ $attr->code } += 1;
569 my $passed_attribute_types;
570 foreach my $attr (@{ $entered_attributes }) {
571 $passed_attribute_types->{ $attr->{ code } } += 1;
574 my @changed_attributes;
576 # Loop through the current patron attributes
577 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
578 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
579 # count differs, overwrite all attributes for given type
580 foreach my $attr (@{ $entered_attributes }) {
581 push @changed_attributes, $attr
582 if $attr->{ code } eq $attribute_type;
585 # count matches, check values
587 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
589 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
594 foreach my $attr (@{ $entered_attributes }) {
595 push @changed_attributes, $attr
596 if $attr->{ code } eq $attribute_type;
602 # Loop through passed attributes, looking for new ones
603 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
604 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
606 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
607 push @changed_attributes, $attr;
612 return \@changed_attributes;
615 sub GeneratePatronAttributesForm {
616 my ( $borrowernumber, $entered_attributes ) = @_;
618 # Get all attribute types and the values for this patron (if applicable)
619 my @types = grep { $_->opac_editable() or $_->opac_display }
620 Koha::Patron::Attribute::Types->search()->as_list();
621 if ( scalar(@types) == 0 ) {
625 my @displayable_attributes = grep { $_->type->opac_display ? $_ : () }
626 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
628 my %attr_values = ();
630 # Build the attribute values list either from the passed values
631 # or taken from the patron itself
632 if ( defined $entered_attributes ) {
633 foreach my $attr (@$entered_attributes) {
634 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
637 elsif ( defined $borrowernumber ) {
638 my @editable_attributes = grep { $_->type->opac_editable ? $_ : () } @displayable_attributes;
639 foreach my $attr (@editable_attributes) {
640 push @{ $attr_values{ $attr->code } }, $attr->attribute;
644 # Add the non-editable attributes (that don't come from the form)
645 foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
646 push @{ $attr_values{ $attr->code } }, $attr->attribute;
649 # Find all existing classes
650 my @classes = sort( uniq( map { $_->class } @types ) );
653 foreach my $attr_type (@types) {
654 push @{ $items_by_class{ $attr_type->class() } }, {
656 # If editable, make sure there's at least one empty entry,
657 # to make the template's job easier
658 values => $attr_values{ $attr_type->code() } || ['']
660 unless !defined $attr_values{ $attr_type->code() }
661 and !$attr_type->opac_editable;
664 # Finally, build a list of containing classes
666 foreach my $class (@classes) {
667 next unless ( $items_by_class{$class} );
669 my $av = Koha::AuthorisedValues->search(
670 { category => 'PA_CLASS', authorised_value => $class } );
672 my $lib = $av->count ? $av->next->opac_description : $class;
677 items => $items_by_class{$class},
685 sub ParsePatronAttributes {
686 my ( $borrowernumber, $cgi ) = @_;
688 my @codes = $cgi->multi_param('patron_attribute_code');
689 my @values = $cgi->multi_param('patron_attribute_value');
691 my @editable_attribute_types
692 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
694 my $ea = each_array( @codes, @values );
697 my $delete_candidates = {};
699 while ( my ( $code, $value ) = $ea->() ) {
700 if ( any { $_ eq $code } @editable_attribute_types ) {
701 # It is an editable attribute
702 if ( !defined($value) or $value eq '' ) {
703 $delete_candidates->{$code} = 1
704 unless $delete_candidates->{$code};
708 push @attributes, { code => $code, attribute => $value };
710 # 'code' is no longer a delete candidate
711 delete $delete_candidates->{$code}
712 if defined $delete_candidates->{$code};
717 foreach my $code ( keys %{$delete_candidates} ) {
718 if ( not $borrowernumber # self-registration
719 || Koha::Patron::Attributes->search({
720 borrowernumber => $borrowernumber, code => $code })->count > 0 )
722 push @attributes, { code => $code, attribute => '' }
723 unless any { $_->{code} eq $code } @attributes;