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);
78 my @libraries = Koha
::Libraries
->search;
80 && ( my @libraries_to_display = split '\|', C4
::Context
->preference('PatronSelfRegistrationLibraryList') )
84 my $branchcode = $_->branchcode;
85 ( grep { $_ eq $branchcode } @libraries_to_display ) ?
$b : ()
88 my ( $min, $max ) = C4
::Members
::get_cardnumber_length
();
91 minlength_cardnumber
=> $min,
92 maxlength_cardnumber
=> $max
98 hidden
=> GetHiddenFields
( $mandatory, $action ),
99 mandatory
=> $mandatory,
100 libraries
=> \
@libraries,
101 OPACPatronDetails
=> C4
::Context
->preference('OPACPatronDetails'),
104 my $attributes = ParsePatronAttributes
($borrowernumber,$cgi);
105 my $conflicting_attribute = 0;
107 foreach my $attr (@
$attributes) {
108 my $attribute = Koha
::Patron
::Attribute
->new($attr);
109 eval {$attribute->check_unique_id};
111 my $attr_type = Koha
::Patron
::Attribute
::Types
->find($attr->{code
});
113 extended_unique_id_failed_code
=> $attr->{code
},
114 extended_unique_id_failed_value
=> $attr->{attribute
},
115 extended_unique_id_failed_description
=> $attr_type->description,
117 $conflicting_attribute = 1;
121 if ( $action eq 'create' ) {
123 my %borrower = ParseCgiForBorrower
($cgi);
125 %borrower = DelEmptyFields
(%borrower);
127 my @empty_mandatory_fields = (CheckMandatoryFields
( \
%borrower, $action ), CheckMandatoryAttributes
( \
%borrower, $attributes ) );
128 my $invalidformfields = CheckForInvalidFields
(\
%borrower);
129 delete $borrower{'password2'};
130 my $cardnumber_error_code;
131 if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
132 # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
133 # spurious length warning.
134 $cardnumber_error_code = checkcardnumber
( $borrower{cardnumber
}, $borrower{borrowernumber
} );
137 if ( @empty_mandatory_fields || @
$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
138 if ( $cardnumber_error_code == 1 ) {
139 $template->param( cardnumber_already_exists
=> 1 );
140 } elsif ( $cardnumber_error_code == 2 ) {
141 $template->param( cardnumber_wrong_length
=> 1 );
145 empty_mandatory_fields
=> \
@empty_mandatory_fields,
146 invalid_form_fields
=> $invalidformfields,
147 borrower
=> \
%borrower
149 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
152 md5_base64
( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
156 borrower
=> \
%borrower
158 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
162 C4
::Context
->boolean_preference(
163 'PatronSelfRegistrationVerifyByEmail')
166 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
168 template_name
=> "opac-registration-email-sent.tt",
171 authnotrequired
=> 1,
174 $template->param( 'email' => $borrower{'email'} );
176 my $verification_token = md5_hex
( time().{}.rand().{}.$$ );
177 while ( Koha
::Patron
::Modifications
->search( { verification_token
=> $verification_token } )->count() ) {
178 $verification_token = md5_hex
( time().{}.rand().{}.$$ );
181 $borrower{password
} = Koha
::AuthUtils
::generate_password
(Koha
::Patron
::Categories
->find($borrower{categorycode
})) unless $borrower{password
};
182 $borrower{verification_token
} = $verification_token;
184 Koha
::Patron
::Modification
->new( \
%borrower )->store();
186 #Send verification email
187 my $letter = C4
::Letters
::GetPreparedLetter
(
189 letter_code
=> 'OPAC_REG_VERIFY',
190 lang
=> 'default', # Patron does not have a preferred language defined yet
192 borrower_modifications
=> $verification_token,
196 C4
::Letters
::EnqueueLetter
(
199 message_transport_type
=> 'email',
200 to_address
=> $borrower{'email'},
202 C4
::Context
->preference('KohaAdminEmailAddress'),
205 my $num_letters_attempted = C4
::Letters
::SendQueuedMessages
( {
206 letter_code
=> 'OPAC_REG_VERIFY'
210 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
212 template_name
=> "opac-registration-confirmation.tt",
215 authnotrequired
=> 1,
219 $borrower{categorycode
} ||= C4
::Context
->preference('PatronSelfRegistrationDefaultCategory');
220 $borrower{password
} ||= Koha
::AuthUtils
::generate_password
(Koha
::Patron
::Categories
->find($borrower{categorycode
}));
221 my $consent_dt = delete $borrower{gdpr_proc_consent
};
222 my $patron = Koha
::Patron
->new( \
%borrower )->store;
223 Koha
::Patron
::Consent
->new({ borrowernumber
=> $patron->borrowernumber, type
=> 'GDPR_PROCESSING', given_on
=> $consent_dt })->store if $consent_dt;
225 $patron->extended_attributes->filter_by_branch_limitations->delete;
226 $patron->extended_attributes($attributes);
227 if ( C4
::Context
->preference('EnhancedMessagingPreferences') ) {
228 C4
::Form
::MessagingPreferences
::handle_form_action
(
230 { borrowernumber
=> $patron->borrowernumber },
233 C4
::Context
->preference('PatronSelfRegistrationDefaultCategory')
237 $template->param( password_cleartext
=> $patron->plain_text_password );
238 $template->param( borrower
=> $patron->unblessed );
240 # FIXME Handle possible errors here
243 PatronSelfRegistrationAdditionalInstructions
=>
244 C4
::Context
->preference(
245 'PatronSelfRegistrationAdditionalInstructions')
250 elsif ( $action eq 'update' ) {
252 my $borrower = Koha
::Patrons
->find( $borrowernumber )->unblessed;
253 die "Wrong CSRF token"
254 unless Koha
::Token
->new->check_csrf({
255 session_id
=> scalar $cgi->cookie('CGISESSID'),
256 token
=> scalar $cgi->param('csrf_token'),
259 my %borrower = ParseCgiForBorrower
($cgi);
260 $borrower{borrowernumber
} = $borrowernumber;
262 my @empty_mandatory_fields =
263 ( CheckMandatoryFields
( \
%borrower, $action ), CheckMandatoryAttributes
( \
%borrower, $attributes ) );
264 my $invalidformfields = CheckForInvalidFields
(\
%borrower);
266 # Send back the data to the template
267 %borrower = ( %$borrower, %borrower );
269 if (@empty_mandatory_fields || @
$invalidformfields) {
271 empty_mandatory_fields
=> \
@empty_mandatory_fields,
272 invalid_form_fields
=> $invalidformfields,
273 borrower
=> \
%borrower,
274 csrf_token
=> Koha
::Token
->new->generate_csrf({
275 session_id
=> scalar $cgi->cookie('CGISESSID'),
278 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber, $attributes ) );
280 $template->param( action
=> 'edit' );
283 my %borrower_changes = DelUnchangedFields
( $borrowernumber, %borrower );
284 $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
285 my $extended_attributes_changes = FilterUnchangedAttributes
( $borrowernumber, $attributes );
287 if ( %borrower_changes || scalar @
{$extended_attributes_changes} > 0 ) {
288 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
290 template_name
=> "opac-memberentry-update-submitted.tt",
293 authnotrequired
=> 1,
297 $borrower_changes{borrowernumber
} = $borrowernumber;
298 $borrower_changes{extended_attributes
} = to_json
($extended_attributes_changes);
300 Koha
::Patron
::Modifications
->search({ borrowernumber
=> $borrowernumber })->delete;
302 my $m = Koha
::Patron
::Modification
->new( \
%borrower_changes )->store();
303 #Automatically approve patron profile changes if set in syspref
305 if (C4
::Context
->preference('AutoApprovePatronProfileSettings')) {
306 # Need to get the object from database, otherwise it is not complete enough to allow deletion
307 # when approval has been performed.
308 my $tmp_m = Koha
::Patron
::Modifications
->find({borrowernumber
=> $borrowernumber});
309 $tmp_m->approve() if $tmp_m;
312 my $patron = Koha
::Patrons
->find( $borrowernumber );
313 $template->param( borrower
=> $patron->unblessed );
316 my $patron = Koha
::Patrons
->find( $borrowernumber );
320 borrower
=> $patron->unblessed,
321 patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber, $attributes ),
322 csrf_token
=> Koha
::Token
->new->generate_csrf({
323 session_id
=> scalar $cgi->cookie('CGISESSID'),
329 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
330 my $patron = Koha
::Patrons
->find( $borrowernumber );
331 my $borrower = $patron->unblessed;
334 borrower
=> $borrower,
335 hidden
=> GetHiddenFields
( $mandatory, 'edit' ),
336 csrf_token
=> Koha
::Token
->new->generate_csrf({
337 session_id
=> scalar $cgi->cookie('CGISESSID'),
341 if (C4
::Context
->preference('OPACpatronimages')) {
342 $template->param( display_patron_image
=> 1 ) if $patron->image;
345 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber ) );
347 # Render self-registration page
348 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
() );
351 my $captcha = random_string
("CCCCC");
352 my $patron_param = Koha
::Patrons
->find( $borrowernumber );
354 has_guarantor_flag
=> $patron_param->guarantor_relationships->guarantors->_resultset->count
359 captcha_digest
=> md5_base64
($captcha),
360 patron
=> $patron_param
363 output_html_with_http_headers
$cgi, $cookie, $template->output, undef, { force_no_caching
=> 1 };
365 sub GetHiddenFields
{
366 my ( $mandatory, $action ) = @_;
369 my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
370 C4
::Context
->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
371 C4
::Context
->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
373 my @fields = split( /\|/, $BorrowerUnwantedField || q
|| );
376 #Don't hide mandatory fields
377 next if $mandatory->{$_};
378 $hidden_fields{$_} = 1;
381 return \
%hidden_fields;
384 sub GetMandatoryFields
{
387 my %mandatory_fields;
389 my $BorrowerMandatoryField =
390 C4
::Context
->preference("PatronSelfRegistrationBorrowerMandatoryField");
392 my @fields = split( /\|/, $BorrowerMandatoryField );
393 push @fields, 'gdpr_proc_consent' if C4
::Context
->preference('GDPR_Policy') && $action eq 'create';
396 $mandatory_fields{$_} = 1;
399 if ( $action eq 'create' || $action eq 'new' ) {
400 $mandatory_fields{'email'} = 1
401 if C4
::Context
->boolean_preference(
402 'PatronSelfRegistrationVerifyByEmail');
405 return \
%mandatory_fields;
408 sub CheckMandatoryFields
{
409 my ( $borrower, $action ) = @_;
411 my @empty_mandatory_fields;
413 my $mandatory_fields = GetMandatoryFields
($action);
414 delete $mandatory_fields->{'cardnumber'};
416 foreach my $key ( keys %$mandatory_fields ) {
417 push( @empty_mandatory_fields, $key )
418 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
421 return @empty_mandatory_fields;
424 sub CheckMandatoryAttributes
{
425 my ( $borrower, $attributes ) = @_;
427 my @empty_mandatory_fields;
429 for my $attribute (@
$attributes ) {
430 my $attr = Koha
::Patron
::Attribute
::Types
->find($attribute->{code
});
431 push @empty_mandatory_fields, $attribute->{code
}
432 if $attr && $attr->mandatory && $attribute->{attribute
} =~ m
|^\s
*$|;
435 return @empty_mandatory_fields;
438 sub CheckForInvalidFields
{
439 my $borrower = shift;
441 if ($borrower->{'email'}) {
442 unless ( Email
::Valid
->address($borrower->{'email'}) ) {
443 push(@invalidFields, "email");
444 } elsif ( C4
::Context
->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
445 my $patrons_with_same_email = Koha
::Patrons
->search( # FIXME Should be search_limited?
447 email
=> $borrower->{email
},
449 exists $borrower->{borrowernumber
}
450 ?
( borrowernumber
=>
451 { '!=' => $borrower->{borrowernumber
} } )
456 if ( $patrons_with_same_email ) {
457 push @invalidFields, "duplicate_email";
459 } elsif ( C4
::Context
->preference("PatronSelfRegistrationConfirmEmail")
460 && $borrower->{'email'} ne $borrower->{'repeat_email'}
461 && !defined $borrower->{borrowernumber
} ) {
462 push @invalidFields, "email_match";
464 # email passed all tests, so prevent attempting to store repeat_email
465 delete $borrower->{'repeat_email'};
467 if ($borrower->{'emailpro'}) {
468 push(@invalidFields, "emailpro") if (!Email
::Valid
->address($borrower->{'emailpro'}));
470 if ($borrower->{'B_email'}) {
471 push(@invalidFields, "B_email") if (!Email
::Valid
->address($borrower->{'B_email'}));
473 if ( defined $borrower->{'password'}
474 and $borrower->{'password'} ne $borrower->{'password2'} )
476 push( @invalidFields, "password_match" );
478 if ( $borrower->{'password'} ) {
479 my ( $is_valid, $error ) = Koha
::AuthUtils
::is_password_valid
( $borrower->{password
}, Koha
::Patron
::Categories
->find($borrower->{categorycode
}) );
480 unless ( $is_valid ) {
481 push @invalidFields, 'password_too_short' if $error eq 'too_short';
482 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
483 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
487 return \
@invalidFields;
490 sub ParseCgiForBorrower
{
493 my $scrubber = C4
::Scrubber
->new();
496 foreach my $field ( $cgi->param ) {
497 if ( $field =~ '^borrower_' ) {
498 my ($key) = substr( $field, 9 );
499 if ( $field !~ '^borrower_password' ) {
500 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
502 # Allow html characters for passwords
503 $borrower{$key} = $cgi->param($field);
508 if ( defined $borrower{'dateofbirth'} ) {
510 $dob_dt = eval { dt_from_string
( $borrower{'dateofbirth'} ); }
511 if ( $borrower{'dateofbirth'} );
514 $borrower{'dateofbirth'} = output_pref
( { dt
=> $dob_dt, dateonly
=> 1, dateformat
=> 'iso' } );
518 $borrower{'dateofbirth'} = undef;
522 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
523 $borrower{gdpr_proc_consent
} = dt_from_string
if $borrower{gdpr_proc_consent
} && $borrower{gdpr_proc_consent
} eq 'agreed';
528 sub DelUnchangedFields
{
529 my ( $borrowernumber, %new_data ) = @_;
530 # get the mandatory fields so we can get the hidden fields
531 my $mandatory = GetMandatoryFields
('edit');
532 my $patron = Koha
::Patrons
->find( $borrowernumber );
533 my $current_data = $patron->unblessed;
534 # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
535 my $hidden_fields = GetHiddenFields
($mandatory, 'edit');
538 foreach my $key ( keys %new_data ) {
539 next if defined($new_data{$key}) xor defined($current_data->{$key});
540 if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
541 delete $new_data{$key};
551 foreach my $key ( keys %borrower ) {
552 delete $borrower{$key} unless $borrower{$key};
558 sub FilterUnchangedAttributes
{
559 my ( $borrowernumber, $entered_attributes ) = @_;
561 my @patron_attributes = grep {$_->type->opac_editable ?
$_ : ()} Koha
::Patron
::Attributes
->search({ borrowernumber
=> $borrowernumber })->as_list;
563 my $patron_attribute_types;
564 foreach my $attr (@patron_attributes) {
565 $patron_attribute_types->{ $attr->code } += 1;
568 my $passed_attribute_types;
569 foreach my $attr (@
{ $entered_attributes }) {
570 $passed_attribute_types->{ $attr->{ code
} } += 1;
573 my @changed_attributes;
575 # Loop through the current patron attributes
576 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
577 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
578 # count differs, overwrite all attributes for given type
579 foreach my $attr (@
{ $entered_attributes }) {
580 push @changed_attributes, $attr
581 if $attr->{ code
} eq $attribute_type;
584 # count matches, check values
586 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
588 unless any
{ $_->{ value
} eq $attr->attribute } @
{ $entered_attributes };
593 foreach my $attr (@
{ $entered_attributes }) {
594 push @changed_attributes, $attr
595 if $attr->{ code
} eq $attribute_type;
601 # Loop through passed attributes, looking for new ones
602 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
603 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
605 foreach my $attr (grep { $_->{code
} eq $attribute_type } @
{ $entered_attributes }) {
606 push @changed_attributes, $attr;
611 return \
@changed_attributes;
614 sub GeneratePatronAttributesForm
{
615 my ( $borrowernumber, $entered_attributes ) = @_;
617 # Get all attribute types and the values for this patron (if applicable)
618 my @types = grep { $_->opac_editable() or $_->opac_display }
619 Koha
::Patron
::Attribute
::Types
->search()->as_list();
620 if ( scalar(@types) == 0 ) {
624 my @displayable_attributes = grep { $_->type->opac_display ?
$_ : () }
625 Koha
::Patron
::Attributes
->search({ borrowernumber
=> $borrowernumber })->as_list;
627 my %attr_values = ();
629 # Build the attribute values list either from the passed values
630 # or taken from the patron itself
631 if ( defined $entered_attributes ) {
632 foreach my $attr (@
$entered_attributes) {
633 push @
{ $attr_values{ $attr->{code
} } }, $attr->{value
};
636 elsif ( defined $borrowernumber ) {
637 my @editable_attributes = grep { $_->type->opac_editable ?
$_ : () } @displayable_attributes;
638 foreach my $attr (@editable_attributes) {
639 push @
{ $attr_values{ $attr->code } }, $attr->attribute;
643 # Add the non-editable attributes (that don't come from the form)
644 foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
645 push @
{ $attr_values{ $attr->code } }, $attr->attribute;
648 # Find all existing classes
649 my @classes = sort( uniq
( map { $_->class } @types ) );
652 foreach my $attr_type (@types) {
653 push @
{ $items_by_class{ $attr_type->class() } }, {
655 # If editable, make sure there's at least one empty entry,
656 # to make the template's job easier
657 values => $attr_values{ $attr_type->code() } || ['']
659 unless !defined $attr_values{ $attr_type->code() }
660 and !$attr_type->opac_editable;
663 # Finally, build a list of containing classes
665 foreach my $class (@classes) {
666 next unless ( $items_by_class{$class} );
668 my $av = Koha
::AuthorisedValues
->search(
669 { category
=> 'PA_CLASS', authorised_value
=> $class } );
671 my $lib = $av->count ?
$av->next->opac_description : $class;
676 items
=> $items_by_class{$class},
684 sub ParsePatronAttributes
{
685 my ( $borrowernumber, $cgi ) = @_;
687 my @codes = $cgi->multi_param('patron_attribute_code');
688 my @values = $cgi->multi_param('patron_attribute_value');
690 my @editable_attribute_types
691 = map { $_->code } Koha
::Patron
::Attribute
::Types
->search({ opac_editable
=> 1 });
693 my $ea = each_array
( @codes, @values );
696 my $delete_candidates = {};
698 while ( my ( $code, $value ) = $ea->() ) {
699 if ( any
{ $_ eq $code } @editable_attribute_types ) {
700 # It is an editable attribute
701 if ( !defined($value) or $value eq '' ) {
702 $delete_candidates->{$code} = 1
703 unless $delete_candidates->{$code};
707 push @attributes, { code
=> $code, attribute
=> $value };
709 # 'code' is no longer a delete candidate
710 delete $delete_candidates->{$code}
711 if defined $delete_candidates->{$code};
716 foreach my $code ( keys %{$delete_candidates} ) {
717 if ( not $borrowernumber # self-registration
718 || Koha
::Patron
::Attributes
->search({
719 borrowernumber
=> $borrowernumber, code
=> $code })->count > 0 )
721 push @attributes, { code
=> $code, attribute
=> '' }
722 unless any
{ $_->{code
} eq $code } @attributes;