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 );
29 use C4
::Form
::MessagingPreferences
;
32 use Koha
::Patron
::Consent
;
33 use Koha
::Patron
::Modification
;
34 use Koha
::Patron
::Modifications
;
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
;
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 ( $action eq q{} ) {
67 if ($borrowernumber) {
75 my $mandatory = GetMandatoryFields
($action);
77 my @libraries = Koha
::Libraries
->search;
79 && ( my @libraries_to_display = split '\|', C4
::Context
->preference('PatronSelfRegistrationLibraryList') )
83 my $branchcode = $_->branchcode;
84 ( grep { $_ eq $branchcode } @libraries_to_display ) ?
$b : ()
87 my ( $min, $max ) = C4
::Members
::get_cardnumber_length
();
90 minlength_cardnumber
=> $min,
91 maxlength_cardnumber
=> $max
97 hidden
=> GetHiddenFields
( $mandatory, $action ),
98 mandatory
=> $mandatory,
99 libraries
=> \
@libraries,
100 OPACPatronDetails
=> C4
::Context
->preference('OPACPatronDetails'),
103 my $attributes = ParsePatronAttributes
($borrowernumber,$cgi);
104 my $conflicting_attribute = 0;
106 foreach my $attr (@
$attributes) {
107 my $attribute = Koha
::Patron
::Attribute
->new($attr);
108 eval {$attribute->check_unique_id};
110 my $attr_type = Koha
::Patron
::Attribute
::Types
->find($attr->{code
});
112 extended_unique_id_failed_code
=> $attr->{code
},
113 extended_unique_id_failed_value
=> $attr->{attribute
},
114 extended_unique_id_failed_description
=> $attr_type->description,
116 $conflicting_attribute = 1;
120 if ( $action eq 'create' ) {
122 my %borrower = ParseCgiForBorrower
($cgi);
124 %borrower = DelEmptyFields
(%borrower);
126 my @empty_mandatory_fields = (CheckMandatoryFields
( \
%borrower, $action ), CheckMandatoryAttributes
( \
%borrower, $attributes ) );
127 my $invalidformfields = CheckForInvalidFields
(\
%borrower);
128 delete $borrower{'password2'};
129 my $cardnumber_error_code;
130 if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
131 # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
132 # spurious length warning.
133 $cardnumber_error_code = checkcardnumber
( $borrower{cardnumber
}, $borrower{borrowernumber
} );
136 if ( @empty_mandatory_fields || @
$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
137 if ( $cardnumber_error_code == 1 ) {
138 $template->param( cardnumber_already_exists
=> 1 );
139 } elsif ( $cardnumber_error_code == 2 ) {
140 $template->param( cardnumber_wrong_length
=> 1 );
144 empty_mandatory_fields
=> \
@empty_mandatory_fields,
145 invalid_form_fields
=> $invalidformfields,
146 borrower
=> \
%borrower
148 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
151 md5_base64
( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
155 borrower
=> \
%borrower
157 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
161 C4
::Context
->boolean_preference(
162 'PatronSelfRegistrationVerifyByEmail')
165 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
167 template_name
=> "opac-registration-email-sent.tt",
170 authnotrequired
=> 1,
173 $template->param( 'email' => $borrower{'email'} );
175 my $verification_token = md5_hex
( time().{}.rand().{}.$$ );
176 while ( Koha
::Patron
::Modifications
->search( { verification_token
=> $verification_token } )->count() ) {
177 $verification_token = md5_hex
( time().{}.rand().{}.$$ );
180 $borrower{password
} = Koha
::AuthUtils
::generate_password
unless $borrower{password
};
181 $borrower{verification_token
} = $verification_token;
183 Koha
::Patron
::Modification
->new( \
%borrower )->store();
185 #Send verification email
186 my $letter = C4
::Letters
::GetPreparedLetter
(
188 letter_code
=> 'OPAC_REG_VERIFY',
189 lang
=> 'default', # Patron does not have a preferred language defined yet
191 borrower_modifications
=> $verification_token,
195 C4
::Letters
::EnqueueLetter
(
198 message_transport_type
=> 'email',
199 to_address
=> $borrower{'email'},
201 C4
::Context
->preference('KohaAdminEmailAddress'),
204 my $num_letters_attempted = C4
::Letters
::SendQueuedMessages
( {
205 letter_code
=> 'OPAC_REG_VERIFY'
209 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
211 template_name
=> "opac-registration-confirmation.tt",
214 authnotrequired
=> 1,
218 $borrower{categorycode
} ||= C4
::Context
->preference('PatronSelfRegistrationDefaultCategory');
219 $borrower{password
} ||= Koha
::AuthUtils
::generate_password
;
220 my $consent_dt = delete $borrower{gdpr_proc_consent
};
221 my $patron = Koha
::Patron
->new( \
%borrower )->store;
222 Koha
::Patron
::Consent
->new({ borrowernumber
=> $patron->borrowernumber, type
=> 'GDPR_PROCESSING', given_on
=> $consent_dt })->store if $consent_dt;
224 $patron->extended_attributes->filter_by_branch_limitations->delete;
225 $patron->extended_attributes($attributes);
226 if ( C4
::Context
->preference('EnhancedMessagingPreferences') ) {
227 C4
::Form
::MessagingPreferences
::handle_form_action
(
229 { borrowernumber
=> $patron->borrowernumber },
232 C4
::Context
->preference('PatronSelfRegistrationDefaultCategory')
236 $template->param( password_cleartext
=> $patron->plain_text_password );
237 $template->param( borrower
=> $patron->unblessed );
239 # FIXME Handle possible errors here
242 PatronSelfRegistrationAdditionalInstructions
=>
243 C4
::Context
->preference(
244 'PatronSelfRegistrationAdditionalInstructions')
249 elsif ( $action eq 'update' ) {
251 my $borrower = Koha
::Patrons
->find( $borrowernumber )->unblessed;
252 die "Wrong CSRF token"
253 unless Koha
::Token
->new->check_csrf({
254 session_id
=> scalar $cgi->cookie('CGISESSID'),
255 token
=> scalar $cgi->param('csrf_token'),
258 my %borrower = ParseCgiForBorrower
($cgi);
259 $borrower{borrowernumber
} = $borrowernumber;
261 my @empty_mandatory_fields =
262 ( CheckMandatoryFields
( \
%borrower, $action ), CheckMandatoryAttributes
( \
%borrower, $attributes ) );
263 my $invalidformfields = CheckForInvalidFields
(\
%borrower);
265 # Send back the data to the template
266 %borrower = ( %$borrower, %borrower );
268 if (@empty_mandatory_fields || @
$invalidformfields) {
270 empty_mandatory_fields
=> \
@empty_mandatory_fields,
271 invalid_form_fields
=> $invalidformfields,
272 borrower
=> \
%borrower,
273 csrf_token
=> Koha
::Token
->new->generate_csrf({
274 session_id
=> scalar $cgi->cookie('CGISESSID'),
277 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber, $attributes ) );
279 $template->param( action
=> 'edit' );
282 my %borrower_changes = DelUnchangedFields
( $borrowernumber, %borrower );
283 $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
284 my $extended_attributes_changes = FilterUnchangedAttributes
( $borrowernumber, $attributes );
286 if ( %borrower_changes || scalar @
{$extended_attributes_changes} > 0 ) {
287 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
289 template_name
=> "opac-memberentry-update-submitted.tt",
292 authnotrequired
=> 1,
296 $borrower_changes{borrowernumber
} = $borrowernumber;
297 $borrower_changes{extended_attributes
} = to_json
($extended_attributes_changes);
299 Koha
::Patron
::Modifications
->search({ borrowernumber
=> $borrowernumber })->delete;
301 my $m = Koha
::Patron
::Modification
->new( \
%borrower_changes )->store();
303 my $patron = Koha
::Patrons
->find( $borrowernumber );
304 $template->param( borrower
=> $patron->unblessed );
307 my $patron = Koha
::Patrons
->find( $borrowernumber );
311 borrower
=> $patron->unblessed,
312 patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber, $attributes ),
313 csrf_token
=> Koha
::Token
->new->generate_csrf({
314 session_id
=> scalar $cgi->cookie('CGISESSID'),
320 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
321 my $patron = Koha
::Patrons
->find( $borrowernumber );
322 my $borrower = $patron->unblessed;
325 borrower
=> $borrower,
326 hidden
=> GetHiddenFields
( $mandatory, 'edit' ),
327 csrf_token
=> Koha
::Token
->new->generate_csrf({
328 session_id
=> scalar $cgi->cookie('CGISESSID'),
332 if (C4
::Context
->preference('OPACpatronimages')) {
333 $template->param( display_patron_image
=> 1 ) if $patron->image;
336 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber ) );
338 # Render self-registration page
339 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
() );
342 my $captcha = random_string
("CCCCC");
343 my $patron_param = Koha
::Patrons
->find( $borrowernumber );
345 has_guarantor_flag
=> $patron_param->guarantor_relationships->guarantors->_resultset->count
350 captcha_digest
=> md5_base64
($captcha),
351 patron
=> $patron_param
354 output_html_with_http_headers
$cgi, $cookie, $template->output, undef, { force_no_caching
=> 1 };
356 sub GetHiddenFields
{
357 my ( $mandatory, $action ) = @_;
360 my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
361 C4
::Context
->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
362 C4
::Context
->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
364 my @fields = split( /\|/, $BorrowerUnwantedField || q
|| );
367 #Don't hide mandatory fields
368 next if $mandatory->{$_};
369 $hidden_fields{$_} = 1;
372 return \
%hidden_fields;
375 sub GetMandatoryFields
{
378 my %mandatory_fields;
380 my $BorrowerMandatoryField =
381 C4
::Context
->preference("PatronSelfRegistrationBorrowerMandatoryField");
383 my @fields = split( /\|/, $BorrowerMandatoryField );
384 push @fields, 'gdpr_proc_consent' if C4
::Context
->preference('GDPR_Policy') && $action eq 'create';
387 $mandatory_fields{$_} = 1;
390 if ( $action eq 'create' || $action eq 'new' ) {
391 $mandatory_fields{'email'} = 1
392 if C4
::Context
->boolean_preference(
393 'PatronSelfRegistrationVerifyByEmail');
396 return \
%mandatory_fields;
399 sub CheckMandatoryFields
{
400 my ( $borrower, $action ) = @_;
402 my @empty_mandatory_fields;
404 my $mandatory_fields = GetMandatoryFields
($action);
405 delete $mandatory_fields->{'cardnumber'};
407 foreach my $key ( keys %$mandatory_fields ) {
408 push( @empty_mandatory_fields, $key )
409 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
412 return @empty_mandatory_fields;
415 sub CheckMandatoryAttributes
{
416 my ( $borrower, $attributes ) = @_;
418 my @empty_mandatory_fields;
420 for my $attribute (@
$attributes ) {
421 my $attr = Koha
::Patron
::Attribute
::Types
->find($attribute->{code
});
422 push @empty_mandatory_fields, $attribute->{code
}
423 if $attr && $attr->mandatory && $attribute->{attribute
} =~ m
|^\s
*$|;
426 return @empty_mandatory_fields;
429 sub CheckForInvalidFields
{
430 my $borrower = shift;
432 if ($borrower->{'email'}) {
433 unless ( Email
::Valid
->address($borrower->{'email'}) ) {
434 push(@invalidFields, "email");
435 } elsif ( C4
::Context
->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
436 my $patrons_with_same_email = Koha
::Patrons
->search( # FIXME Should be search_limited?
438 email
=> $borrower->{email
},
440 exists $borrower->{borrowernumber
}
441 ?
( borrowernumber
=>
442 { '!=' => $borrower->{borrowernumber
} } )
447 if ( $patrons_with_same_email ) {
448 push @invalidFields, "duplicate_email";
450 } elsif ( C4
::Context
->preference("PatronSelfRegistrationConfirmEmail")
451 && $borrower->{'email'} ne $borrower->{'repeat_email'}
452 && !defined $borrower->{borrowernumber
} ) {
453 push @invalidFields, "email_match";
455 # email passed all tests, so prevent attempting to store repeat_email
456 delete $borrower->{'repeat_email'};
458 if ($borrower->{'emailpro'}) {
459 push(@invalidFields, "emailpro") if (!Email
::Valid
->address($borrower->{'emailpro'}));
461 if ($borrower->{'B_email'}) {
462 push(@invalidFields, "B_email") if (!Email
::Valid
->address($borrower->{'B_email'}));
464 if ( defined $borrower->{'password'}
465 and $borrower->{'password'} ne $borrower->{'password2'} )
467 push( @invalidFields, "password_match" );
469 if ( $borrower->{'password'} ) {
470 my ( $is_valid, $error ) = Koha
::AuthUtils
::is_password_valid
( $borrower->{password
} );
471 unless ( $is_valid ) {
472 push @invalidFields, 'password_too_short' if $error eq 'too_short';
473 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
474 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
478 return \
@invalidFields;
481 sub ParseCgiForBorrower
{
484 my $scrubber = C4
::Scrubber
->new();
487 foreach my $field ( $cgi->param ) {
488 if ( $field =~ '^borrower_' ) {
489 my ($key) = substr( $field, 9 );
490 if ( $field !~ '^borrower_password' ) {
491 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
493 # Allow html characters for passwords
494 $borrower{$key} = $cgi->param($field);
499 if ( defined $borrower{'dateofbirth'} ) {
501 $dob_dt = eval { dt_from_string
( $borrower{'dateofbirth'} ); }
502 if ( $borrower{'dateofbirth'} );
505 $borrower{'dateofbirth'} = output_pref
( { dt
=> $dob_dt, dateonly
=> 1, dateformat
=> 'iso' } );
509 $borrower{'dateofbirth'} = undef;
513 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
514 $borrower{gdpr_proc_consent
} = dt_from_string
if $borrower{gdpr_proc_consent
} && $borrower{gdpr_proc_consent
} eq 'agreed';
519 sub DelUnchangedFields
{
520 my ( $borrowernumber, %new_data ) = @_;
521 # get the mandatory fields so we can get the hidden fields
522 my $mandatory = GetMandatoryFields
('edit');
523 my $patron = Koha
::Patrons
->find( $borrowernumber );
524 my $current_data = $patron->unblessed;
525 # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
526 my $hidden_fields = GetHiddenFields
($mandatory, 'edit');
529 foreach my $key ( keys %new_data ) {
530 next if defined($new_data{$key}) xor defined($current_data->{$key});
531 if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
532 delete $new_data{$key};
542 foreach my $key ( keys %borrower ) {
543 delete $borrower{$key} unless $borrower{$key};
549 sub FilterUnchangedAttributes
{
550 my ( $borrowernumber, $entered_attributes ) = @_;
552 my @patron_attributes = grep {$_->type->opac_editable ?
$_ : ()} Koha
::Patron
::Attributes
->search({ borrowernumber
=> $borrowernumber })->as_list;
554 my $patron_attribute_types;
555 foreach my $attr (@patron_attributes) {
556 $patron_attribute_types->{ $attr->code } += 1;
559 my $passed_attribute_types;
560 foreach my $attr (@
{ $entered_attributes }) {
561 $passed_attribute_types->{ $attr->{ code
} } += 1;
564 my @changed_attributes;
566 # Loop through the current patron attributes
567 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
568 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
569 # count differs, overwrite all attributes for given type
570 foreach my $attr (@
{ $entered_attributes }) {
571 push @changed_attributes, $attr
572 if $attr->{ code
} eq $attribute_type;
575 # count matches, check values
577 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
579 unless any
{ $_->{ value
} eq $attr->attribute } @
{ $entered_attributes };
584 foreach my $attr (@
{ $entered_attributes }) {
585 push @changed_attributes, $attr
586 if $attr->{ code
} eq $attribute_type;
592 # Loop through passed attributes, looking for new ones
593 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
594 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
596 foreach my $attr (grep { $_->{code
} eq $attribute_type } @
{ $entered_attributes }) {
597 push @changed_attributes, $attr;
602 return \
@changed_attributes;
605 sub GeneratePatronAttributesForm
{
606 my ( $borrowernumber, $entered_attributes ) = @_;
608 # Get all attribute types and the values for this patron (if applicable)
609 my @types = grep { $_->opac_editable() or $_->opac_display }
610 Koha
::Patron
::Attribute
::Types
->search()->as_list();
611 if ( scalar(@types) == 0 ) {
615 my @displayable_attributes = grep { $_->type->opac_display ?
$_ : () }
616 Koha
::Patron
::Attributes
->search({ borrowernumber
=> $borrowernumber })->as_list;
618 my %attr_values = ();
620 # Build the attribute values list either from the passed values
621 # or taken from the patron itself
622 if ( defined $entered_attributes ) {
623 foreach my $attr (@
$entered_attributes) {
624 push @
{ $attr_values{ $attr->{code
} } }, $attr->{value
};
627 elsif ( defined $borrowernumber ) {
628 my @editable_attributes = grep { $_->type->opac_editable ?
$_ : () } @displayable_attributes;
629 foreach my $attr (@editable_attributes) {
630 push @
{ $attr_values{ $attr->code } }, $attr->attribute;
634 # Add the non-editable attributes (that don't come from the form)
635 foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
636 push @
{ $attr_values{ $attr->code } }, $attr->attribute;
639 # Find all existing classes
640 my @classes = sort( uniq
( map { $_->class } @types ) );
643 foreach my $attr_type (@types) {
644 push @
{ $items_by_class{ $attr_type->class() } }, {
646 # If editable, make sure there's at least one empty entry,
647 # to make the template's job easier
648 values => $attr_values{ $attr_type->code() } || ['']
650 unless !defined $attr_values{ $attr_type->code() }
651 and !$attr_type->opac_editable;
654 # Finally, build a list of containing classes
656 foreach my $class (@classes) {
657 next unless ( $items_by_class{$class} );
659 my $av = Koha
::AuthorisedValues
->search(
660 { category
=> 'PA_CLASS', authorised_value
=> $class } );
662 my $lib = $av->count ?
$av->next->opac_description : $class;
667 items
=> $items_by_class{$class},
675 sub ParsePatronAttributes
{
676 my ( $borrowernumber, $cgi ) = @_;
678 my @codes = $cgi->multi_param('patron_attribute_code');
679 my @values = $cgi->multi_param('patron_attribute_value');
681 my @editable_attribute_types
682 = map { $_->code } Koha
::Patron
::Attribute
::Types
->search({ opac_editable
=> 1 });
684 my $ea = each_array
( @codes, @values );
687 my $delete_candidates = {};
689 while ( my ( $code, $value ) = $ea->() ) {
690 if ( any
{ $_ eq $code } @editable_attribute_types ) {
691 # It is an editable attribute
692 if ( !defined($value) or $value eq '' ) {
693 $delete_candidates->{$code} = 1
694 unless $delete_candidates->{$code};
698 push @attributes, { code
=> $code, attribute
=> $value };
700 # 'code' is no longer a delete candidate
701 delete $delete_candidates->{$code}
702 if defined $delete_candidates->{$code};
707 foreach my $code ( keys %{$delete_candidates} ) {
708 if ( not $borrowernumber # self-registration
709 || Koha
::Patron
::Attributes
->search({
710 borrowernumber
=> $borrowernumber, code
=> $code })->count > 0 )
712 push @attributes, { code
=> $code, attribute
=> '' }
713 unless any
{ $_->{code
} eq $code } @attributes;