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
::Members
::Attributes
qw( GetBorrowerAttributes );
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
;
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;
79 if ( my @libraries_to_display = split '\|', C4
::Context
->preference('PatronSelfRegistrationLibraryList') ) {
80 @libraries = map { my $b = $_; my $branchcode = $_->branchcode; grep( /^$branchcode$/, @libraries_to_display ) ?
$b : () } @libraries;
82 my ( $min, $max ) = C4
::Members
::get_cardnumber_length
();
85 minlength_cardnumber
=> $min,
86 maxlength_cardnumber
=> $max
92 hidden
=> GetHiddenFields
( $mandatory, $action ),
93 mandatory
=> $mandatory,
94 libraries
=> \
@libraries,
95 OPACPatronDetails
=> C4
::Context
->preference('OPACPatronDetails'),
98 my $attributes = ParsePatronAttributes
($borrowernumber,$cgi);
99 my $conflicting_attribute = 0;
101 foreach my $attr (@
$attributes) {
102 unless ( C4
::Members
::Attributes
::CheckUniqueness
($attr->{code
}, $attr->{value
}, $borrowernumber) ) {
103 my $attr_info = C4
::Members
::AttributeTypes
->fetch($attr->{code
});
105 extended_unique_id_failed_code
=> $attr->{code
},
106 extended_unique_id_failed_value
=> $attr->{value
},
107 extended_unique_id_failed_description
=> $attr_info->description()
109 $conflicting_attribute = 1;
113 if ( $action eq 'create' ) {
115 my %borrower = ParseCgiForBorrower
($cgi);
117 %borrower = DelEmptyFields
(%borrower);
119 my @empty_mandatory_fields = CheckMandatoryFields
( \
%borrower, $action );
120 my $invalidformfields = CheckForInvalidFields
(\
%borrower);
121 delete $borrower{'password2'};
122 my $cardnumber_error_code;
123 if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
124 # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
125 # spurious length warning.
126 $cardnumber_error_code = checkcardnumber
( $borrower{cardnumber
}, $borrower{borrowernumber
} );
129 if ( @empty_mandatory_fields || @
$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
130 if ( $cardnumber_error_code == 1 ) {
131 $template->param( cardnumber_already_exists
=> 1 );
132 } elsif ( $cardnumber_error_code == 2 ) {
133 $template->param( cardnumber_wrong_length
=> 1 );
137 empty_mandatory_fields
=> \
@empty_mandatory_fields,
138 invalid_form_fields
=> $invalidformfields,
139 borrower
=> \
%borrower
141 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
144 md5_base64
( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
148 borrower
=> \
%borrower
150 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( undef, $attributes ) );
154 C4
::Context
->boolean_preference(
155 'PatronSelfRegistrationVerifyByEmail')
158 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
160 template_name
=> "opac-registration-email-sent.tt",
163 authnotrequired
=> 1,
166 $template->param( 'email' => $borrower{'email'} );
168 my $verification_token = md5_hex
( time().{}.rand().{}.$$ );
169 while ( Koha
::Patron
::Modifications
->search( { verification_token
=> $verification_token } )->count() ) {
170 $verification_token = md5_hex
( time().{}.rand().{}.$$ );
173 $borrower{password
} = Koha
::AuthUtils
::generate_password
unless $borrower{password
};
174 $borrower{verification_token
} = $verification_token;
176 Koha
::Patron
::Modification
->new( \
%borrower )->store();
178 #Send verification email
179 my $letter = C4
::Letters
::GetPreparedLetter
(
181 letter_code
=> 'OPAC_REG_VERIFY',
182 lang
=> 'default', # Patron does not have a preferred language defined yet
184 borrower_modifications
=> $verification_token,
188 C4
::Letters
::EnqueueLetter
(
191 message_transport_type
=> 'email',
192 to_address
=> $borrower{'email'},
194 C4
::Context
->preference('KohaAdminEmailAddress'),
197 my $num_letters_attempted = C4
::Letters
::SendQueuedMessages
( {
198 letter_code
=> 'OPAC_REG_VERIFY'
202 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
204 template_name
=> "opac-registration-confirmation.tt",
207 authnotrequired
=> 1,
211 $borrower{categorycode
} ||= C4
::Context
->preference('PatronSelfRegistrationDefaultCategory');
212 $borrower{password
} ||= Koha
::AuthUtils
::generate_password
;
213 my $consent_dt = delete $borrower{gdpr_proc_consent
};
214 my $patron = Koha
::Patron
->new( \
%borrower )->store;
215 Koha
::Patron
::Consent
->new({ borrowernumber
=> $patron->borrowernumber, type
=> 'GDPR_PROCESSING', given_on
=> $consent_dt })->store if $consent_dt;
217 C4
::Members
::Attributes
::SetBorrowerAttributes
( $patron->borrowernumber, $attributes );
218 if ( C4
::Context
->preference('EnhancedMessagingPreferences') ) {
219 C4
::Form
::MessagingPreferences
::handle_form_action
(
221 { borrowernumber
=> $patron->borrowernumber },
224 C4
::Context
->preference('PatronSelfRegistrationDefaultCategory')
228 $template->param( password_cleartext
=> $patron->plain_text_password );
229 $template->param( borrower
=> $patron->unblessed );
231 # FIXME Handle possible errors here
234 PatronSelfRegistrationAdditionalInstructions
=>
235 C4
::Context
->preference(
236 'PatronSelfRegistrationAdditionalInstructions')
241 elsif ( $action eq 'update' ) {
243 my $borrower = Koha
::Patrons
->find( $borrowernumber )->unblessed;
244 die "Wrong CSRF token"
245 unless Koha
::Token
->new->check_csrf({
246 session_id
=> scalar $cgi->cookie('CGISESSID'),
247 token
=> scalar $cgi->param('csrf_token'),
250 my %borrower = ParseCgiForBorrower
($cgi);
251 $borrower{borrowernumber
} = $borrowernumber;
253 my @empty_mandatory_fields =
254 CheckMandatoryFields
( \
%borrower, $action );
255 my $invalidformfields = CheckForInvalidFields
(\
%borrower);
257 # Send back the data to the template
258 %borrower = ( %$borrower, %borrower );
260 if (@empty_mandatory_fields || @
$invalidformfields) {
262 empty_mandatory_fields
=> \
@empty_mandatory_fields,
263 invalid_form_fields
=> $invalidformfields,
264 borrower
=> \
%borrower,
265 csrf_token
=> Koha
::Token
->new->generate_csrf({
266 session_id
=> scalar $cgi->cookie('CGISESSID'),
269 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber, $attributes ) );
271 $template->param( action
=> 'edit' );
274 my %borrower_changes = DelUnchangedFields
( $borrowernumber, %borrower );
275 $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
276 my $extended_attributes_changes = FilterUnchangedAttributes
( $borrowernumber, $attributes );
278 if ( %borrower_changes || scalar @
{$extended_attributes_changes} > 0 ) {
279 ( $template, $borrowernumber, $cookie ) = get_template_and_user
(
281 template_name
=> "opac-memberentry-update-submitted.tt",
284 authnotrequired
=> 1,
288 $borrower_changes{borrowernumber
} = $borrowernumber;
289 $borrower_changes{extended_attributes
} = to_json
($extended_attributes_changes);
291 Koha
::Patron
::Modifications
->search({ borrowernumber
=> $borrowernumber })->delete;
293 my $m = Koha
::Patron
::Modification
->new( \
%borrower_changes )->store();
295 my $patron = Koha
::Patrons
->find( $borrowernumber );
296 $template->param( borrower
=> $patron->unblessed );
299 my $patron = Koha
::Patrons
->find( $borrowernumber );
303 borrower
=> $patron->unblessed,
304 patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber, $attributes ),
305 csrf_token
=> Koha
::Token
->new->generate_csrf({
306 session_id
=> scalar $cgi->cookie('CGISESSID'),
312 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
313 my $patron = Koha
::Patrons
->find( $borrowernumber );
314 my $borrower = $patron->unblessed;
317 borrower
=> $borrower,
318 hidden
=> GetHiddenFields
( $mandatory, 'edit' ),
319 csrf_token
=> Koha
::Token
->new->generate_csrf({
320 session_id
=> scalar $cgi->cookie('CGISESSID'),
324 if (C4
::Context
->preference('OPACpatronimages')) {
325 $template->param( display_patron_image
=> 1 ) if $patron->image;
328 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
( $borrowernumber ) );
330 # Render self-registration page
331 $template->param( patron_attribute_classes
=> GeneratePatronAttributesForm
() );
334 my $captcha = random_string
("CCCCC");
335 my $patron_param = Koha
::Patrons
->find( $borrowernumber );
337 has_guarantor_flag
=> $patron_param->guarantor_relationships->guarantors->_resultset->count
342 captcha_digest
=> md5_base64
($captcha),
343 patron
=> $patron_param
346 output_html_with_http_headers
$cgi, $cookie, $template->output, undef, { force_no_caching
=> 1 };
348 sub GetHiddenFields
{
349 my ( $mandatory, $action ) = @_;
352 my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
353 C4
::Context
->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
354 C4
::Context
->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
356 my @fields = split( /\|/, $BorrowerUnwantedField || q
|| );
359 #Don't hide mandatory fields
360 next if $mandatory->{$_};
361 $hidden_fields{$_} = 1;
364 return \
%hidden_fields;
367 sub GetMandatoryFields
{
370 my %mandatory_fields;
372 my $BorrowerMandatoryField =
373 C4
::Context
->preference("PatronSelfRegistrationBorrowerMandatoryField");
375 my @fields = split( /\|/, $BorrowerMandatoryField );
376 push @fields, 'gdpr_proc_consent' if C4
::Context
->preference('GDPR_Policy') && $action eq 'create';
379 $mandatory_fields{$_} = 1;
382 if ( $action eq 'create' || $action eq 'new' ) {
383 $mandatory_fields{'email'} = 1
384 if C4
::Context
->boolean_preference(
385 'PatronSelfRegistrationVerifyByEmail');
388 return \
%mandatory_fields;
391 sub CheckMandatoryFields
{
392 my ( $borrower, $action ) = @_;
394 my @empty_mandatory_fields;
396 my $mandatory_fields = GetMandatoryFields
($action);
397 delete $mandatory_fields->{'cardnumber'};
399 foreach my $key ( keys %$mandatory_fields ) {
400 push( @empty_mandatory_fields, $key )
401 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
404 return @empty_mandatory_fields;
407 sub CheckForInvalidFields
{
408 my $borrower = shift;
410 if ($borrower->{'email'}) {
411 unless ( Email
::Valid
->address($borrower->{'email'}) ) {
412 push(@invalidFields, "email");
413 } elsif ( C4
::Context
->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
414 my $patrons_with_same_email = Koha
::Patrons
->search( # FIXME Should be search_limited?
416 email
=> $borrower->{email
},
418 exists $borrower->{borrowernumber
}
419 ?
( borrowernumber
=>
420 { '!=' => $borrower->{borrowernumber
} } )
425 if ( $patrons_with_same_email ) {
426 push @invalidFields, "duplicate_email";
430 if ($borrower->{'emailpro'}) {
431 push(@invalidFields, "emailpro") if (!Email
::Valid
->address($borrower->{'emailpro'}));
433 if ($borrower->{'B_email'}) {
434 push(@invalidFields, "B_email") if (!Email
::Valid
->address($borrower->{'B_email'}));
436 if ( defined $borrower->{'password'}
437 and $borrower->{'password'} ne $borrower->{'password2'} )
439 push( @invalidFields, "password_match" );
441 if ( $borrower->{'password'} ) {
442 my ( $is_valid, $error ) = Koha
::AuthUtils
::is_password_valid
( $borrower->{password
} );
443 unless ( $is_valid ) {
444 push @invalidFields, 'password_too_short' if $error eq 'too_short';
445 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
446 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
450 return \
@invalidFields;
453 sub ParseCgiForBorrower
{
456 my $scrubber = C4
::Scrubber
->new();
459 foreach my $field ( $cgi->param ) {
460 if ( $field =~ '^borrower_' ) {
461 my ($key) = substr( $field, 9 );
462 if ( $field !~ '^borrower_password' ) {
463 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
465 # Allow html characters for passwords
466 $borrower{$key} = $cgi->param($field);
472 $dob_dt = eval { dt_from_string
( $borrower{'dateofbirth'} ); }
473 if ( $borrower{'dateofbirth'} );
476 $borrower{'dateofbirth'} = output_pref
( { dt
=> $dob_dt, dateonly
=> 1, dateformat
=> 'iso' } );
480 $borrower{'dateofbirth'} = undef;
483 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
484 $borrower{gdpr_proc_consent
} = dt_from_string
if $borrower{gdpr_proc_consent
} && $borrower{gdpr_proc_consent
} eq 'agreed';
489 sub DelUnchangedFields
{
490 my ( $borrowernumber, %new_data ) = @_;
491 # get the mandatory fields so we can get the hidden fields
492 my $mandatory = GetMandatoryFields
('edit');
493 my $patron = Koha
::Patrons
->find( $borrowernumber );
494 my $current_data = $patron->unblessed;
495 # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
496 my $hidden_fields = GetHiddenFields
($mandatory, 'edit');
499 foreach my $key ( keys %new_data ) {
500 if ( ($current_data->{$key} eq $new_data{$key}) || $hidden_fields->{$key} ) {
501 delete $new_data{$key};
511 foreach my $key ( keys %borrower ) {
512 delete $borrower{$key} unless $borrower{$key};
518 sub FilterUnchangedAttributes
{
519 my ( $borrowernumber, $entered_attributes ) = @_;
521 my @patron_attributes = grep {$_->opac_editable} Koha
::Patron
::Attributes
->search({ borrowernumber
=> $borrowernumber })->as_list;
523 my $patron_attribute_types;
524 foreach my $attr (@patron_attributes) {
525 $patron_attribute_types->{ $attr->code } += 1;
528 my $passed_attribute_types;
529 foreach my $attr (@
{ $entered_attributes }) {
530 $passed_attribute_types->{ $attr->{ code
} } += 1;
533 my @changed_attributes;
535 # Loop through the current patron attributes
536 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
537 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
538 # count differs, overwrite all attributes for given type
539 foreach my $attr (@
{ $entered_attributes }) {
540 push @changed_attributes, $attr
541 if $attr->{ code
} eq $attribute_type;
544 # count matches, check values
546 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
548 unless any
{ $_->{ value
} eq $attr->attribute } @
{ $entered_attributes };
553 foreach my $attr (@
{ $entered_attributes }) {
554 push @changed_attributes, $attr
555 if $attr->{ code
} eq $attribute_type;
561 # Loop through passed attributes, looking for new ones
562 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
563 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
565 foreach my $attr (grep { $_->{code
} eq $attribute_type } @
{ $entered_attributes }) {
566 push @changed_attributes, $attr;
571 return \
@changed_attributes;
574 sub GeneratePatronAttributesForm
{
575 my ( $borrowernumber, $entered_attributes ) = @_;
577 # Get all attribute types and the values for this patron (if applicable)
578 my @types = grep { $_->opac_editable() or $_->opac_display }
579 Koha
::Patron
::Attribute
::Types
->search()->as_list();
580 if ( scalar(@types) == 0 ) {
584 my @displayable_attributes = grep { $_->opac_display }
585 Koha
::Patron
::Attributes
->search({ borrowernumber
=> $borrowernumber })->as_list;
587 my %attr_values = ();
589 # Build the attribute values list either from the passed values
590 # or taken from the patron itself
591 if ( defined $entered_attributes ) {
592 foreach my $attr (@
$entered_attributes) {
593 push @
{ $attr_values{ $attr->{code
} } }, $attr->{value
};
596 elsif ( defined $borrowernumber ) {
597 my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
598 foreach my $attr (@editable_attributes) {
599 push @
{ $attr_values{ $attr->code } }, $attr->attribute;
603 # Add the non-editable attributes (that don't come from the form)
604 foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
605 push @
{ $attr_values{ $attr->code } }, $attr->attribute;
608 # Find all existing classes
609 my @classes = sort( uniq
( map { $_->class } @types ) );
612 foreach my $attr_type (@types) {
613 push @
{ $items_by_class{ $attr_type->class() } }, {
615 # If editable, make sure there's at least one empty entry,
616 # to make the template's job easier
617 values => $attr_values{ $attr_type->code() } || ['']
619 unless !defined $attr_values{ $attr_type->code() }
620 and !$attr_type->opac_editable;
623 # Finally, build a list of containing classes
625 foreach my $class (@classes) {
626 next unless ( $items_by_class{$class} );
628 my $av = Koha
::AuthorisedValues
->search(
629 { category
=> 'PA_CLASS', authorised_value
=> $class } );
631 my $lib = $av->count ?
$av->next->opac_description : $class;
636 items
=> $items_by_class{$class},
644 sub ParsePatronAttributes
{
645 my ( $borrowernumber, $cgi ) = @_;
647 my @codes = $cgi->multi_param('patron_attribute_code');
648 my @values = $cgi->multi_param('patron_attribute_value');
650 my @editable_attribute_types
651 = map { $_->code } Koha
::Patron
::Attribute
::Types
->search({ opac_editable
=> 1 });
653 my $ea = each_array
( @codes, @values );
656 my $delete_candidates = {};
658 while ( my ( $code, $value ) = $ea->() ) {
659 if ( any
{ $_ eq $code } @editable_attribute_types ) {
660 # It is an editable attribute
661 if ( !defined($value) or $value eq '' ) {
662 $delete_candidates->{$code} = 1
663 unless $delete_candidates->{$code};
667 push @attributes, { code
=> $code, value
=> $value };
669 # 'code' is no longer a delete candidate
670 delete $delete_candidates->{$code}
671 if defined $delete_candidates->{$code};
676 foreach my $code ( keys %{$delete_candidates} ) {
677 if ( Koha
::Patron
::Attributes
->search({
678 borrowernumber
=> $borrowernumber, code
=> $code })->count > 0 )
680 push @attributes, { code
=> $code, value
=> '' }
681 unless any
{ $_->{code
} eq $code } @attributes;