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;
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
();
84 minlength_cardnumber
=> $min,
85 maxlength_cardnumber
=> $max
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};
104 my $attr_type = Koha
::Patron
::Attribute
::Types
->find($attr->{code
});
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 );
138 empty_mandatory_fields
=> \
@empty_mandatory_fields,
139 invalid_form_fields
=> $invalidformfields,
140 borrower
=> \
%borrower
142 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
145 md5_base64
( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
149 borrower
=> \
%borrower
151 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
155 C4
::Context
->boolean_preference(
156 'PatronSelfRegistrationVerifyByEmail')
159 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
161 template_name
=> "opac-registration-email-sent.tt",
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
(
182 letter_code
=> 'OPAC_REG_VERIFY',
183 lang
=> 'default', # Patron does not have a preferred language defined yet
185 borrower_modifications
=> $verification_token,
189 C4
::Letters
::EnqueueLetter
(
192 message_transport_type
=> 'email',
193 to_address
=> $borrower{'email'},
195 C4
::Context
->preference('KohaAdminEmailAddress'),
198 my $num_letters_attempted = C4
::Letters
::SendQueuedMessages
( {
199 letter_code
=> 'OPAC_REG_VERIFY'
203 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
205 template_name
=> "opac-registration-confirmation.tt",
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;
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
(
223 { borrowernumber
=> $patron->borrowernumber },
226 C4
::Context
->preference('PatronSelfRegistrationDefaultCategory')
230 $template->param( password_cleartext
=> $patron->plain_text_password );
231 $template->param( borrower
=> $patron->unblessed );
233 # FIXME Handle possible errors here
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) {
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' );
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",
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 );
301 my $patron = Koha
::Patrons
->find( $borrowernumber );
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;
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 ) );
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 );
339 has_guarantor_flag
=> $patron_param->guarantor_relationships->guarantors->_resultset->count
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 ) = @_;
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
|| );
361 #Don't hide mandatory fields
362 next if $mandatory->{$_};
363 $hidden_fields{$_} = 1;
366 return \
%hidden_fields;
369 sub GetMandatoryFields
{
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';
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;
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
} } )
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
{
458 my $scrubber = C4
::Scrubber
->new();
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) );
467 # Allow html characters for passwords
468 $borrower{$key} = $cgi->param($field);
474 $dob_dt = eval { dt_from_string
( $borrower{'dateofbirth'} ); }
475 if ( $borrower{'dateofbirth'} );
478 $borrower{'dateofbirth'} = output_pref
( { dt
=> $dob_dt, dateonly
=> 1, dateformat
=> 'iso' } );
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';
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};
514 foreach my $key ( keys %borrower ) {
515 delete $borrower{$key} unless $borrower{$key};
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;
547 # count matches, check values
549 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
551 unless any
{ $_->{ value
} eq $attr->attribute } @
{ $entered_attributes };
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 } ) {
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 ) {
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 ) );
615 foreach my $attr_type (@types) {
616 push @
{ $items_by_class{ $attr_type->class() } }, {
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
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;
639 items
=> $items_by_class{$class},
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 );
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};
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;