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 );
22 use JSON qw( to_json );
23 use List::MoreUtils qw( any each_array uniq );
24 use String::Random qw( random_string );
26 use C4::Auth qw( get_template_and_user );
27 use C4::Output qw( output_html_with_http_headers );
29 use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages );
30 use C4::Members qw( checkcardnumber );
31 use C4::Form::MessagingPreferences;
34 use Koha::Patron::Consent;
35 use Koha::Patron::Modification;
36 use Koha::Patron::Modifications;
38 use Koha::DateUtils qw( dt_from_string );
41 use Koha::Patron::Attribute::Types;
42 use Koha::Patron::Attributes;
43 use Koha::Patron::Images;
44 use Koha::Patron::Categories;
46 use Koha::AuthorisedValues;
48 my $dbh = C4::Context->dbh;
50 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
52 template_name => "opac-memberentry.tt",
59 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
61 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
65 my $action = $cgi->param('action') || q{};
66 if ( $borrowernumber && ( $action eq 'create' || $action eq 'new' ) ) {
67 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
71 if ( $action eq q{} ) {
72 if ($borrowernumber) {
80 my $mandatory = GetMandatoryFields($action);
83 if ( $action eq 'create' || $action eq 'new' ) {
84 my @PatronSelfRegistrationLibraryList = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList');
85 $params = { branchcode => { -in => \@PatronSelfRegistrationLibraryList } }
86 if @PatronSelfRegistrationLibraryList;
88 my $libraries = Koha::Libraries->search($params);
90 my ( $min, $max ) = C4::Members::get_cardnumber_length();
93 minlength_cardnumber => $min,
94 maxlength_cardnumber => $max
98 my $defaultCategory = Koha::Patron::Categories->find(C4::Context->preference('PatronSelfRegistrationDefaultCategory'));
102 hidden => GetHiddenFields( $mandatory, $action ),
103 mandatory => $mandatory,
104 libraries => $libraries,
105 OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
106 defaultCategory => $defaultCategory,
109 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
110 my $conflicting_attribute = 0;
112 foreach my $attr (@$attributes) {
113 my $attribute = Koha::Patron::Attribute->new($attr);
114 if ( !$attribute->unique_ok ) {
115 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
117 extended_unique_id_failed_code => $attr->{code},
118 extended_unique_id_failed_value => $attr->{attribute},
119 extended_unique_id_failed_description => $attr_type->description,
121 $conflicting_attribute = 1;
125 if ( $action eq 'create' ) {
127 my %borrower = ParseCgiForBorrower($cgi);
129 %borrower = DelEmptyFields(%borrower);
130 $borrower{categorycode} ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
132 my @empty_mandatory_fields = (CheckMandatoryFields( \%borrower, $action ), CheckMandatoryAttributes( \%borrower, $attributes ) );
133 my $invalidformfields = CheckForInvalidFields(\%borrower);
134 delete $borrower{'password2'};
135 my $cardnumber_error_code;
136 if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
137 # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
138 # spurious length warning.
139 $cardnumber_error_code = checkcardnumber( $borrower{cardnumber}, $borrower{borrowernumber} );
142 if ( @empty_mandatory_fields || @$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
143 if ( $cardnumber_error_code == 1 ) {
144 $template->param( cardnumber_already_exists => 1 );
145 } elsif ( $cardnumber_error_code == 2 ) {
146 $template->param( cardnumber_wrong_length => 1 );
150 empty_mandatory_fields => \@empty_mandatory_fields,
151 invalid_form_fields => $invalidformfields,
152 borrower => \%borrower
154 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
157 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
161 borrower => \%borrower
163 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
164 } elsif ( !$libraries->find($borrower{branchcode}) ) {
165 die "Branchcode not allowed"; # They hack the form
169 C4::Context->preference(
170 'PatronSelfRegistrationVerifyByEmail')
173 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
175 template_name => "opac-registration-email-sent.tt",
178 authnotrequired => 1,
181 $template->param( 'email' => $borrower{'email'} );
183 my $verification_token = md5_hex( time().{}.rand().{}.$$ );
184 while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
185 $verification_token = md5_hex( time().{}.rand().{}.$$ );
188 $borrower{password} = Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode})) unless $borrower{password};
189 $borrower{verification_token} = $verification_token;
191 $borrower{extended_attributes} = to_json($attributes);
192 Koha::Patron::Modification->new( \%borrower )->store();
194 #Send verification email
195 my $letter = C4::Letters::GetPreparedLetter(
197 letter_code => 'OPAC_REG_VERIFY',
198 lang => 'default', # Patron does not have a preferred language defined yet
200 borrower_modifications => $verification_token,
204 my $message_id = C4::Letters::EnqueueLetter(
207 message_transport_type => 'email',
208 to_address => $borrower{'email'},
210 C4::Context->preference('KohaAdminEmailAddress'),
213 C4::Letters::SendQueuedMessages({ message_id => $message_id });
216 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
218 template_name => "opac-registration-confirmation.tt",
221 authnotrequired => 1,
225 $borrower{password} ||= Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode}));
226 my $consent_dt = delete $borrower{gdpr_proc_consent};
227 my $patron = Koha::Patron->new( \%borrower )->store;
228 Koha::Patron::Consent->new({ borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt })->store if $consent_dt;
230 $patron->extended_attributes->filter_by_branch_limitations->delete;
231 $patron->extended_attributes($attributes);
232 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
233 C4::Form::MessagingPreferences::handle_form_action(
235 { borrowernumber => $patron->borrowernumber },
238 C4::Context->preference('PatronSelfRegistrationDefaultCategory')
242 $template->param( password_cleartext => $patron->plain_text_password );
243 $template->param( borrower => $patron->unblessed );
245 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
246 if ( C4::Context->preference("AutoEmailNewUser") ) {
247 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
248 my $emailaddr = $patron->notice_email_address;
249 # if we manage to find a valid email address, send notice
252 my $letter = GetPreparedLetter(
254 letter_code => 'WELCOME',
255 branchcode => $patron->branchcode,,
256 lang => $patron->lang || 'default',
258 'branches' => $patron->branchcode,
259 'borrowers' => $patron->borrowernumber,
264 my $message_id = EnqueueLetter(
267 borrowernumber => $patron->id,
268 to_address => $emailaddr,
269 message_transport_type => 'email'
272 SendQueuedMessages({ message_id => $message_id });
277 # FIXME Handle possible errors here
280 PatronSelfRegistrationAdditionalInstructions =>
281 C4::Context->preference(
282 'PatronSelfRegistrationAdditionalInstructions')
287 elsif ( $action eq 'update' ) {
289 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
290 die "Wrong CSRF token"
291 unless Koha::Token->new->check_csrf({
292 session_id => scalar $cgi->cookie('CGISESSID'),
293 token => scalar $cgi->param('csrf_token'),
296 my %borrower = ParseCgiForBorrower($cgi);
297 $borrower{borrowernumber} = $borrowernumber;
299 my @empty_mandatory_fields = grep { $_ ne 'password' } # password is not required when editing personal details
300 ( CheckMandatoryFields( \%borrower, $action ), CheckMandatoryAttributes( \%borrower, $attributes ) );
301 my $invalidformfields = CheckForInvalidFields(\%borrower);
303 # Send back the data to the template
304 %borrower = ( %$borrower, %borrower );
306 if (@empty_mandatory_fields || @$invalidformfields) {
308 empty_mandatory_fields => \@empty_mandatory_fields,
309 invalid_form_fields => $invalidformfields,
310 borrower => \%borrower,
311 csrf_token => Koha::Token->new->generate_csrf({
312 session_id => scalar $cgi->cookie('CGISESSID'),
315 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
317 $template->param( action => 'edit' );
320 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
321 $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
322 my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
324 if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
325 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
327 template_name => "opac-memberentry-update-submitted.tt",
330 authnotrequired => 1,
334 $borrower_changes{borrowernumber} = $borrowernumber;
335 $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
337 Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
339 my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
340 #Automatically approve patron profile changes if set in syspref
342 if (C4::Context->preference('AutoApprovePatronProfileSettings')) {
343 # Need to get the object from database, otherwise it is not complete enough to allow deletion
344 # when approval has been performed.
345 my $tmp_m = Koha::Patron::Modifications->find({borrowernumber => $borrowernumber});
346 $tmp_m->approve() if $tmp_m;
349 my $patron = Koha::Patrons->find( $borrowernumber );
350 $template->param( borrower => $patron->unblessed );
353 my $patron = Koha::Patrons->find( $borrowernumber );
357 borrower => $patron->unblessed,
358 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
359 csrf_token => Koha::Token->new->generate_csrf({
360 session_id => scalar $cgi->cookie('CGISESSID'),
366 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
367 my $patron = Koha::Patrons->find( $borrowernumber );
368 my $borrower = $patron->unblessed;
371 borrower => $borrower,
372 hidden => GetHiddenFields( $mandatory, 'edit' ),
373 csrf_token => Koha::Token->new->generate_csrf({
374 session_id => scalar $cgi->cookie('CGISESSID'),
378 if (C4::Context->preference('OPACpatronimages')) {
379 $template->param( display_patron_image => 1 ) if $patron->image;
382 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
384 # Render self-registration page
385 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
388 my $captcha = random_string("CCCCC");
389 my $patron_param = Koha::Patrons->find( $borrowernumber );
391 has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count
396 captcha_digest => md5_base64($captcha),
397 patron => $patron_param
400 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
402 sub GetHiddenFields {
403 my ( $mandatory, $action ) = @_;
406 my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
407 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
408 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
410 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
413 #Don't hide mandatory fields
414 next if $mandatory->{$_};
415 $hidden_fields{$_} = 1;
418 return \%hidden_fields;
421 sub GetMandatoryFields {
424 my %mandatory_fields;
426 my $BorrowerMandatoryField = $action eq 'edit' || $action eq 'update' ?
427 C4::Context->preference("PatronSelfModificationMandatoryField") :
428 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
430 my @fields = split( /\|/, $BorrowerMandatoryField );
431 push @fields, 'gdpr_proc_consent' if C4::Context->preference('GDPR_Policy') && $action eq 'create';
434 $mandatory_fields{$_} = 1;
437 if ( $action eq 'create' || $action eq 'new' ) {
438 $mandatory_fields{'email'} = 1
439 if C4::Context->preference(
440 'PatronSelfRegistrationVerifyByEmail');
443 return \%mandatory_fields;
446 sub CheckMandatoryFields {
447 my ( $borrower, $action ) = @_;
449 my @empty_mandatory_fields;
451 my $mandatory_fields = GetMandatoryFields($action);
452 delete $mandatory_fields->{'cardnumber'};
454 foreach my $key ( keys %$mandatory_fields ) {
455 push( @empty_mandatory_fields, $key )
456 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
459 return @empty_mandatory_fields;
462 sub CheckMandatoryAttributes{
463 my ( $borrower, $attributes ) = @_;
465 my @empty_mandatory_fields;
467 for my $attribute (@$attributes ) {
468 my $attr = Koha::Patron::Attribute::Types->find($attribute->{code});
469 push @empty_mandatory_fields, $attribute->{code}
470 if $attr && $attr->mandatory && $attribute->{attribute} =~ m|^\s*$|;
473 return @empty_mandatory_fields;
476 sub CheckForInvalidFields {
477 my $borrower = shift;
479 if ($borrower->{'email'}) {
480 unless ( Koha::Email->is_valid($borrower->{email}) ) {
481 push(@invalidFields, "email");
482 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
483 my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
485 email => $borrower->{email},
487 exists $borrower->{borrowernumber}
488 ? ( borrowernumber =>
489 { '!=' => $borrower->{borrowernumber} } )
494 if ( $patrons_with_same_email ) {
495 push @invalidFields, "duplicate_email";
497 } elsif ( C4::Context->preference("PatronSelfRegistrationConfirmEmail")
498 && $borrower->{'email'} ne $borrower->{'repeat_email'}
499 && !defined $borrower->{borrowernumber} ) {
500 push @invalidFields, "email_match";
502 # email passed all tests, so prevent attempting to store repeat_email
503 delete $borrower->{'repeat_email'};
505 if ($borrower->{'emailpro'}) {
506 push(@invalidFields, "emailpro") unless Koha::Email->is_valid($borrower->{'emailpro'});
508 if ($borrower->{'B_email'}) {
509 push(@invalidFields, "B_email") unless Koha::Email->is_valid($borrower->{'B_email'});
511 if ( defined $borrower->{'password'}
512 and $borrower->{'password'} ne $borrower->{'password2'} )
514 push( @invalidFields, "password_match" );
516 if ( $borrower->{'password'} ) {
517 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password}, Koha::Patron::Categories->find($borrower->{categorycode}||C4::Context->preference('PatronSelfRegistrationDefaultCategory')) );
518 unless ( $is_valid ) {
519 push @invalidFields, 'password_too_short' if $error eq 'too_short';
520 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
521 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
525 return \@invalidFields;
528 sub ParseCgiForBorrower {
531 my $scrubber = C4::Scrubber->new();
534 foreach my $field ( $cgi->param ) {
535 if ( $field =~ '^borrower_' ) {
536 my ($key) = substr( $field, 9 );
537 if ( $field !~ '^borrower_password' ) {
538 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
540 # Allow html characters for passwords
541 $borrower{$key} = $cgi->param($field);
546 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
547 $borrower{gdpr_proc_consent} = dt_from_string if $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed';
549 delete $borrower{$_} for qw/borrowernumber date_renewed debarred debarredcomment flags privacy privacy_guarantor_fines privacy_guarantor_checkouts checkprevcheckout updated_on lastseen lang login_attempts overdrive_auth_token anonymized/; # See also members/memberentry.pl
550 delete $borrower{$_} for qw/dateenrolled dateexpiry borrowernotes opacnote sort1 sort2 sms_provider_id autorenew_checkouts gonenoaddress lost relationship/; # On OPAC only
551 delete $borrower{$_} for split( /\s*\|\s*/, C4::Context->preference('PatronSelfRegistrationBorrowerUnwantedField') || q{} );
556 sub DelUnchangedFields {
557 my ( $borrowernumber, %new_data ) = @_;
558 # get the mandatory fields so we can get the hidden fields
559 my $mandatory = GetMandatoryFields('edit');
560 my $patron = Koha::Patrons->find( $borrowernumber );
561 my $current_data = $patron->unblessed;
562 # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
563 my $hidden_fields = GetHiddenFields($mandatory, 'edit');
566 foreach my $key ( keys %new_data ) {
567 next if defined($new_data{$key}) xor defined($current_data->{$key});
568 if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
569 delete $new_data{$key};
579 foreach my $key ( keys %borrower ) {
580 delete $borrower{$key} unless $borrower{$key};
586 sub FilterUnchangedAttributes {
587 my ( $borrowernumber, $entered_attributes ) = @_;
589 my @patron_attributes = grep {$_->type->opac_editable ? $_ : ()} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
591 my $patron_attribute_types;
592 foreach my $attr (@patron_attributes) {
593 $patron_attribute_types->{ $attr->code } += 1;
596 my $passed_attribute_types;
597 foreach my $attr (@{ $entered_attributes }) {
598 $passed_attribute_types->{ $attr->{ code } } += 1;
601 my @changed_attributes;
603 # Loop through the current patron attributes
604 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
605 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
606 # count differs, overwrite all attributes for given type
607 foreach my $attr (@{ $entered_attributes }) {
608 push @changed_attributes, $attr
609 if $attr->{ code } eq $attribute_type;
612 # count matches, check values
614 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
616 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
621 foreach my $attr (@{ $entered_attributes }) {
622 push @changed_attributes, $attr
623 if $attr->{ code } eq $attribute_type;
629 # Loop through passed attributes, looking for new ones
630 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
631 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
633 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
634 push @changed_attributes, $attr;
639 return \@changed_attributes;
642 sub GeneratePatronAttributesForm {
643 my ( $borrowernumber, $entered_attributes ) = @_;
645 # Get all attribute types and the values for this patron (if applicable)
646 my @types = grep { $_->opac_editable() or $_->opac_display } # FIXME filter using DBIC
647 Koha::Patron::Attribute::Types->search()->as_list();
648 if ( scalar(@types) == 0 ) {
652 my @displayable_attributes = grep { $_->type->opac_display ? $_ : () }
653 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
655 my %attr_values = ();
657 # Build the attribute values list either from the passed values
658 # or taken from the patron itself
659 if ( defined $entered_attributes ) {
660 foreach my $attr (@$entered_attributes) {
661 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
664 elsif ( defined $borrowernumber ) {
665 my @editable_attributes = grep { $_->type->opac_editable ? $_ : () } @displayable_attributes;
666 foreach my $attr (@editable_attributes) {
667 push @{ $attr_values{ $attr->code } }, $attr->attribute;
671 # Add the non-editable attributes (that don't come from the form)
672 foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
673 push @{ $attr_values{ $attr->code } }, $attr->attribute;
676 # Find all existing classes
677 my @classes = sort( uniq( map { $_->class } @types ) );
680 foreach my $attr_type (@types) {
681 push @{ $items_by_class{ $attr_type->class() } }, {
683 # If editable, make sure there's at least one empty entry,
684 # to make the template's job easier
685 values => $attr_values{ $attr_type->code() } || ['']
687 unless !defined $attr_values{ $attr_type->code() }
688 and !$attr_type->opac_editable;
691 # Finally, build a list of containing classes
693 foreach my $class (@classes) {
694 next unless ( $items_by_class{$class} );
696 my $av = Koha::AuthorisedValues->search(
697 { category => 'PA_CLASS', authorised_value => $class } );
699 my $lib = $av->count ? $av->next->opac_description : $class;
704 items => $items_by_class{$class},
712 sub ParsePatronAttributes {
713 my ( $borrowernumber, $cgi ) = @_;
715 my @codes = $cgi->multi_param('patron_attribute_code');
716 my @values = $cgi->multi_param('patron_attribute_value');
718 my @editable_attribute_types
719 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 })->as_list;
721 my $ea = each_array( @codes, @values );
724 my $delete_candidates = {};
726 while ( my ( $code, $value ) = $ea->() ) {
727 if ( any { $_ eq $code } @editable_attribute_types ) {
728 # It is an editable attribute
729 if ( !defined($value) or $value eq '' ) {
730 $delete_candidates->{$code} = 1
731 unless $delete_candidates->{$code};
735 push @attributes, { code => $code, attribute => $value };
737 # 'code' is no longer a delete candidate
738 delete $delete_candidates->{$code}
739 if defined $delete_candidates->{$code};
744 foreach my $code ( keys %{$delete_candidates} ) {
745 if ( not $borrowernumber # self-registration
746 || Koha::Patron::Attributes->search({
747 borrowernumber => $borrowernumber, code => $code })->count > 0 )
749 push @attributes, { code => $code, attribute => '' }
750 unless any { $_->{code} eq $code } @attributes;