Bug 17268: DBRev 19.12.00.084
[koha.git] / opac / opac-memberentry.pl
blobfaf32e828542f985608907e30a8470f969e084b9
1 #!/usr/bin/perl
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>.
18 use Modern::Perl;
20 use CGI qw ( -utf8 );
21 use Digest::MD5 qw( md5_base64 md5_hex );
22 use JSON;
23 use List::MoreUtils qw( any each_array uniq );
24 use String::Random qw( random_string );
26 use C4::Auth;
27 use C4::Output;
28 use C4::Members;
29 use C4::Form::MessagingPreferences;
30 use Koha::AuthUtils;
31 use Koha::Patrons;
32 use Koha::Patron::Consent;
33 use Koha::Patron::Modification;
34 use Koha::Patron::Modifications;
35 use C4::Scrubber;
36 use Email::Valid;
37 use Koha::DateUtils;
38 use Koha::Libraries;
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;
44 use Koha::Patrons;
45 use Koha::Token;
47 my $cgi = new CGI;
48 my $dbh = C4::Context->dbh;
50 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
52 template_name => "opac-memberentry.tt",
53 type => "opac",
54 query => $cgi,
55 authnotrequired => 1,
59 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
61 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
62 exit;
65 my $action = $cgi->param('action') || q{};
66 if ( $action eq q{} ) {
67 if ($borrowernumber) {
68 $action = 'edit';
70 else {
71 $action = 'new';
75 my $mandatory = GetMandatoryFields($action);
77 my @libraries = Koha::Libraries->search;
78 if ( $action eq 'new'
79 && ( my @libraries_to_display = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList') )
80 ) {
81 @libraries = map {
82 my $b = $_;
83 my $branchcode = $_->branchcode;
84 ( grep { $_ eq $branchcode } @libraries_to_display ) ? $b : ()
85 } @libraries;
87 my ( $min, $max ) = C4::Members::get_cardnumber_length();
88 if ( defined $min ) {
89 $template->param(
90 minlength_cardnumber => $min,
91 maxlength_cardnumber => $max
95 $template->param(
96 action => $action,
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};
109 if ( $@ ) {
110 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
111 $template->param(
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 );
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 );
143 $template->param(
144 empty_mandatory_fields => \@empty_mandatory_fields,
145 invalid_form_fields => $invalidformfields,
146 borrower => \%borrower
148 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
150 elsif (
151 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
153 $template->param(
154 failed_captcha => 1,
155 borrower => \%borrower
157 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
159 else {
160 if (
161 C4::Context->boolean_preference(
162 'PatronSelfRegistrationVerifyByEmail')
165 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
167 template_name => "opac-registration-email-sent.tt",
168 type => "opac",
169 query => $cgi,
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(
187 module => 'members',
188 letter_code => 'OPAC_REG_VERIFY',
189 lang => 'default', # Patron does not have a preferred language defined yet
190 tables => {
191 borrower_modifications => $verification_token,
195 C4::Letters::EnqueueLetter(
197 letter => $letter,
198 message_transport_type => 'email',
199 to_address => $borrower{'email'},
200 from_address =>
201 C4::Context->preference('KohaAdminEmailAddress'),
204 my $num_letters_attempted = C4::Letters::SendQueuedMessages( {
205 letter_code => 'OPAC_REG_VERIFY'
206 } );
208 else {
209 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
211 template_name => "opac-registration-confirmation.tt",
212 type => "opac",
213 query => $cgi,
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;
223 if ( $patron ) {
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(
228 $cgi,
229 { borrowernumber => $patron->borrowernumber },
230 $template,
232 C4::Context->preference('PatronSelfRegistrationDefaultCategory')
236 $template->param( password_cleartext => $patron->plain_text_password );
237 $template->param( borrower => $patron->unblessed );
238 } else {
239 # FIXME Handle possible errors here
241 $template->param(
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 );
263 my $invalidformfields = CheckForInvalidFields(\%borrower);
265 # Send back the data to the template
266 %borrower = ( %$borrower, %borrower );
268 if (@empty_mandatory_fields || @$invalidformfields) {
269 $template->param(
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' );
281 else {
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",
290 type => "opac",
291 query => $cgi,
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 );
306 else {
307 my $patron = Koha::Patrons->find( $borrowernumber );
308 $template->param(
309 action => 'edit',
310 nochanges => 1,
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;
324 $template->param(
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 ) );
337 } else {
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 );
344 $template->param(
345 has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count
346 ) if $patron_param;
348 $template->param(
349 captcha => $captcha,
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 ) = @_;
358 my %hidden_fields;
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|| );
365 foreach (@fields) {
366 next unless m/\w/o;
367 #Don't hide mandatory fields
368 next if $mandatory->{$_};
369 $hidden_fields{$_} = 1;
372 return \%hidden_fields;
375 sub GetMandatoryFields {
376 my ($action) = @_;
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';
386 foreach (@fields) {
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 CheckForInvalidFields {
416 my $borrower = shift;
417 my @invalidFields;
418 if ($borrower->{'email'}) {
419 unless ( Email::Valid->address($borrower->{'email'}) ) {
420 push(@invalidFields, "email");
421 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
422 my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
424 email => $borrower->{email},
426 exists $borrower->{borrowernumber}
427 ? ( borrowernumber =>
428 { '!=' => $borrower->{borrowernumber} } )
429 : ()
432 )->count;
433 if ( $patrons_with_same_email ) {
434 push @invalidFields, "duplicate_email";
436 } elsif ( C4::Context->preference("PatronSelfRegistrationConfirmEmail")
437 && $borrower->{'email'} ne $borrower->{'repeat_email'}
438 && !defined $borrower->{borrowernumber} ) {
439 push @invalidFields, "email_match";
441 # email passed all tests, so prevent attempting to store repeat_email
442 delete $borrower->{'repeat_email'};
444 if ($borrower->{'emailpro'}) {
445 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
447 if ($borrower->{'B_email'}) {
448 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
450 if ( defined $borrower->{'password'}
451 and $borrower->{'password'} ne $borrower->{'password2'} )
453 push( @invalidFields, "password_match" );
455 if ( $borrower->{'password'} ) {
456 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
457 unless ( $is_valid ) {
458 push @invalidFields, 'password_too_short' if $error eq 'too_short';
459 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
460 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
464 return \@invalidFields;
467 sub ParseCgiForBorrower {
468 my ($cgi) = @_;
470 my $scrubber = C4::Scrubber->new();
471 my %borrower;
473 foreach my $field ( $cgi->param ) {
474 if ( $field =~ '^borrower_' ) {
475 my ($key) = substr( $field, 9 );
476 if ( $field !~ '^borrower_password' ) {
477 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
478 } else {
479 # Allow html characters for passwords
480 $borrower{$key} = $cgi->param($field);
485 my $dob_dt;
486 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
487 if ( $borrower{'dateofbirth'} );
489 if ( $dob_dt ) {
490 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
492 else {
493 # Trigger validation
494 $borrower{'dateofbirth'} = undef;
497 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
498 $borrower{gdpr_proc_consent} = dt_from_string if $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed';
500 return %borrower;
503 sub DelUnchangedFields {
504 my ( $borrowernumber, %new_data ) = @_;
505 # get the mandatory fields so we can get the hidden fields
506 my $mandatory = GetMandatoryFields('edit');
507 my $patron = Koha::Patrons->find( $borrowernumber );
508 my $current_data = $patron->unblessed;
509 # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
510 my $hidden_fields = GetHiddenFields($mandatory, 'edit');
513 foreach my $key ( keys %new_data ) {
514 next if defined($new_data{$key}) xor defined($current_data->{$key});
515 if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
516 delete $new_data{$key};
520 return %new_data;
523 sub DelEmptyFields {
524 my (%borrower) = @_;
526 foreach my $key ( keys %borrower ) {
527 delete $borrower{$key} unless $borrower{$key};
530 return %borrower;
533 sub FilterUnchangedAttributes {
534 my ( $borrowernumber, $entered_attributes ) = @_;
536 my @patron_attributes = grep {$_->type->opac_editable ? $_ : ()} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
538 my $patron_attribute_types;
539 foreach my $attr (@patron_attributes) {
540 $patron_attribute_types->{ $attr->code } += 1;
543 my $passed_attribute_types;
544 foreach my $attr (@{ $entered_attributes }) {
545 $passed_attribute_types->{ $attr->{ code } } += 1;
548 my @changed_attributes;
550 # Loop through the current patron attributes
551 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
552 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
553 # count differs, overwrite all attributes for given type
554 foreach my $attr (@{ $entered_attributes }) {
555 push @changed_attributes, $attr
556 if $attr->{ code } eq $attribute_type;
558 } else {
559 # count matches, check values
560 my $changes = 0;
561 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
562 $changes = 1
563 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
564 last if $changes;
567 if ( $changes ) {
568 foreach my $attr (@{ $entered_attributes }) {
569 push @changed_attributes, $attr
570 if $attr->{ code } eq $attribute_type;
576 # Loop through passed attributes, looking for new ones
577 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
578 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
579 # YAY, new stuff
580 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
581 push @changed_attributes, $attr;
586 return \@changed_attributes;
589 sub GeneratePatronAttributesForm {
590 my ( $borrowernumber, $entered_attributes ) = @_;
592 # Get all attribute types and the values for this patron (if applicable)
593 my @types = grep { $_->opac_editable() or $_->opac_display }
594 Koha::Patron::Attribute::Types->search()->as_list();
595 if ( scalar(@types) == 0 ) {
596 return [];
599 my @displayable_attributes = grep { $_->type->opac_display ? $_ : () }
600 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
602 my %attr_values = ();
604 # Build the attribute values list either from the passed values
605 # or taken from the patron itself
606 if ( defined $entered_attributes ) {
607 foreach my $attr (@$entered_attributes) {
608 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
611 elsif ( defined $borrowernumber ) {
612 my @editable_attributes = grep { $_->type->opac_editable ? $_ : () } @displayable_attributes;
613 foreach my $attr (@editable_attributes) {
614 push @{ $attr_values{ $attr->code } }, $attr->attribute;
618 # Add the non-editable attributes (that don't come from the form)
619 foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
620 push @{ $attr_values{ $attr->code } }, $attr->attribute;
623 # Find all existing classes
624 my @classes = sort( uniq( map { $_->class } @types ) );
625 my %items_by_class;
627 foreach my $attr_type (@types) {
628 push @{ $items_by_class{ $attr_type->class() } }, {
629 type => $attr_type,
630 # If editable, make sure there's at least one empty entry,
631 # to make the template's job easier
632 values => $attr_values{ $attr_type->code() } || ['']
634 unless !defined $attr_values{ $attr_type->code() }
635 and !$attr_type->opac_editable;
638 # Finally, build a list of containing classes
639 my @class_loop;
640 foreach my $class (@classes) {
641 next unless ( $items_by_class{$class} );
643 my $av = Koha::AuthorisedValues->search(
644 { category => 'PA_CLASS', authorised_value => $class } );
646 my $lib = $av->count ? $av->next->opac_description : $class;
648 push @class_loop,
650 class => $class,
651 items => $items_by_class{$class},
652 lib => $lib,
656 return \@class_loop;
659 sub ParsePatronAttributes {
660 my ( $borrowernumber, $cgi ) = @_;
662 my @codes = $cgi->multi_param('patron_attribute_code');
663 my @values = $cgi->multi_param('patron_attribute_value');
665 my @editable_attribute_types
666 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
668 my $ea = each_array( @codes, @values );
669 my @attributes;
671 my $delete_candidates = {};
673 while ( my ( $code, $value ) = $ea->() ) {
674 if ( any { $_ eq $code } @editable_attribute_types ) {
675 # It is an editable attribute
676 if ( !defined($value) or $value eq '' ) {
677 $delete_candidates->{$code} = 1
678 unless $delete_candidates->{$code};
680 else {
681 # we've got a value
682 push @attributes, { code => $code, attribute => $value };
684 # 'code' is no longer a delete candidate
685 delete $delete_candidates->{$code}
686 if defined $delete_candidates->{$code};
691 foreach my $code ( keys %{$delete_candidates} ) {
692 if ( Koha::Patron::Attributes->search({
693 borrowernumber => $borrowernumber, code => $code })->count > 0 )
695 push @attributes, { code => $code, attribute => '' }
696 unless any { $_->{code} eq $code } @attributes;
700 return \@attributes;