Bug 20006: Spec changes
[koha.git] / opac / opac-memberentry.pl
blobdbb6d99e5c3892eceeca68ad7c10c34a01d4a0ab
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::Members::Attributes qw( GetBorrowerAttributes );
30 use C4::Form::MessagingPreferences;
31 use Koha::AuthUtils;
32 use Koha::Patrons;
33 use Koha::Patron::Consent;
34 use Koha::Patron::Modification;
35 use Koha::Patron::Modifications;
36 use C4::Scrubber;
37 use Email::Valid;
38 use Koha::DateUtils;
39 use Koha::Libraries;
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::Patrons;
46 use Koha::Token;
48 my $cgi = new CGI;
49 my $dbh = C4::Context->dbh;
51 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
53 template_name => "opac-memberentry.tt",
54 type => "opac",
55 query => $cgi,
56 authnotrequired => 1,
60 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
62 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
63 exit;
66 my $action = $cgi->param('action') || q{};
67 if ( $action eq q{} ) {
68 if ($borrowernumber) {
69 $action = 'edit';
71 else {
72 $action = 'new';
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();
83 if ( defined $min ) {
84 $template->param(
85 minlength_cardnumber => $min,
86 maxlength_cardnumber => $max
90 $template->param(
91 action => $action,
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});
104 $template->param(
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 );
136 $template->param(
137 empty_mandatory_fields => \@empty_mandatory_fields,
138 invalid_form_fields => $invalidformfields,
139 borrower => \%borrower
141 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
143 elsif (
144 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
146 $template->param(
147 failed_captcha => 1,
148 borrower => \%borrower
150 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
152 else {
153 if (
154 C4::Context->boolean_preference(
155 'PatronSelfRegistrationVerifyByEmail')
158 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
160 template_name => "opac-registration-email-sent.tt",
161 type => "opac",
162 query => $cgi,
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(
180 module => 'members',
181 letter_code => 'OPAC_REG_VERIFY',
182 lang => 'default', # Patron does not have a preferred language defined yet
183 tables => {
184 borrower_modifications => $verification_token,
188 C4::Letters::EnqueueLetter(
190 letter => $letter,
191 message_transport_type => 'email',
192 to_address => $borrower{'email'},
193 from_address =>
194 C4::Context->preference('KohaAdminEmailAddress'),
198 else {
199 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
201 template_name => "opac-registration-confirmation.tt",
202 type => "opac",
203 query => $cgi,
204 authnotrequired => 1,
208 $template->param( OpacPasswordChange =>
209 C4::Context->preference('OpacPasswordChange') );
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;
216 if ( $patron ) {
217 C4::Members::Attributes::SetBorrowerAttributes( $patron->borrowernumber, $attributes );
218 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
219 C4::Form::MessagingPreferences::handle_form_action(
220 $cgi,
221 { borrowernumber => $patron->borrowernumber },
222 $template,
224 C4::Context->preference('PatronSelfRegistrationDefaultCategory')
228 $template->param( password_cleartext => $patron->plain_text_password );
229 $template->param( borrower => $patron->unblessed );
230 } else {
231 # FIXME Handle possible errors here
233 $template->param(
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 %borrower_changes = DelEmptyFields(%borrower);
254 my @empty_mandatory_fields =
255 CheckMandatoryFields( \%borrower_changes, $action );
256 my $invalidformfields = CheckForInvalidFields(\%borrower);
258 # Send back the data to the template
259 %borrower = ( %$borrower, %borrower );
261 if (@empty_mandatory_fields || @$invalidformfields) {
262 $template->param(
263 empty_mandatory_fields => \@empty_mandatory_fields,
264 invalid_form_fields => $invalidformfields,
265 borrower => \%borrower,
266 csrf_token => Koha::Token->new->generate_csrf({
267 session_id => scalar $cgi->cookie('CGISESSID'),
270 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
272 $template->param( action => 'edit' );
274 else {
275 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
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",
282 type => "opac",
283 query => $cgi,
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 );
298 else {
299 my $patron = Koha::Patrons->find( $borrowernumber );
300 $template->param(
301 action => 'edit',
302 nochanges => 1,
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;
316 $template->param(
317 borrower => $borrower,
318 guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
319 hidden => GetHiddenFields( $mandatory, 'edit' ),
320 csrf_token => Koha::Token->new->generate_csrf({
321 session_id => scalar $cgi->cookie('CGISESSID'),
325 if (C4::Context->preference('OPACpatronimages')) {
326 $template->param( display_patron_image => 1 ) if $patron->image;
329 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
330 } else {
331 # Render self-registration page
332 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
335 my $captcha = random_string("CCCCC");
337 $template->param(
338 captcha => $captcha,
339 captcha_digest => md5_base64($captcha)
342 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
344 sub GetHiddenFields {
345 my ( $mandatory, $action ) = @_;
346 my %hidden_fields;
348 my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
349 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
350 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
352 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
353 foreach (@fields) {
354 next unless m/\w/o;
355 #Don't hide mandatory fields
356 next if $mandatory->{$_};
357 $hidden_fields{$_} = 1;
360 return \%hidden_fields;
363 sub GetMandatoryFields {
364 my ($action) = @_;
366 my %mandatory_fields;
368 my $BorrowerMandatoryField =
369 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
371 my @fields = split( /\|/, $BorrowerMandatoryField );
372 push @fields, 'gdpr_proc_consent' if C4::Context->preference('GDPR_Policy');
374 foreach (@fields) {
375 $mandatory_fields{$_} = 1;
378 if ( $action eq 'create' || $action eq 'new' ) {
379 $mandatory_fields{'email'} = 1
380 if C4::Context->boolean_preference(
381 'PatronSelfRegistrationVerifyByEmail');
384 return \%mandatory_fields;
387 sub CheckMandatoryFields {
388 my ( $borrower, $action ) = @_;
390 my @empty_mandatory_fields;
392 my $mandatory_fields = GetMandatoryFields($action);
393 delete $mandatory_fields->{'cardnumber'};
395 foreach my $key ( keys %$mandatory_fields ) {
396 push( @empty_mandatory_fields, $key )
397 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
400 return @empty_mandatory_fields;
403 sub CheckForInvalidFields {
404 my $borrower = shift;
405 my @invalidFields;
406 if ($borrower->{'email'}) {
407 unless ( Email::Valid->address($borrower->{'email'}) ) {
408 push(@invalidFields, "email");
409 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
410 my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
412 email => $borrower->{email},
414 exists $borrower->{borrowernumber}
415 ? ( borrowernumber =>
416 { '!=' => $borrower->{borrowernumber} } )
417 : ()
420 )->count;
421 if ( $patrons_with_same_email ) {
422 push @invalidFields, "duplicate_email";
426 if ($borrower->{'emailpro'}) {
427 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
429 if ($borrower->{'B_email'}) {
430 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
432 if ( defined $borrower->{'password'}
433 and $borrower->{'password'} ne $borrower->{'password2'} )
435 push( @invalidFields, "password_match" );
437 if ( $borrower->{'password'} ) {
438 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
439 unless ( $is_valid ) {
440 push @invalidFields, 'password_too_short' if $error eq 'too_short';
441 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
442 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
446 return \@invalidFields;
449 sub ParseCgiForBorrower {
450 my ($cgi) = @_;
452 my $scrubber = C4::Scrubber->new();
453 my %borrower;
455 foreach my $field ( $cgi->param ) {
456 if ( $field =~ '^borrower_' ) {
457 my ($key) = substr( $field, 9 );
458 if ( $field !~ '^borrower_password' ) {
459 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
460 } else {
461 # Allow html characters for passwords
462 $borrower{$key} = $cgi->param($field);
467 my $dob_dt;
468 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
469 if ( $borrower{'dateofbirth'} );
471 if ( $dob_dt ) {
472 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
474 else {
475 # Trigger validation
476 $borrower{'dateofbirth'} = undef;
479 # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
480 $borrower{gdpr_proc_consent} = dt_from_string if $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed';
482 return %borrower;
485 sub DelUnchangedFields {
486 my ( $borrowernumber, %new_data ) = @_;
488 my $patron = Koha::Patrons->find( $borrowernumber );
489 my $current_data = $patron->unblessed;
491 foreach my $key ( keys %new_data ) {
492 if ( $current_data->{$key} eq $new_data{$key} ) {
493 delete $new_data{$key};
497 return %new_data;
500 sub DelEmptyFields {
501 my (%borrower) = @_;
503 foreach my $key ( keys %borrower ) {
504 delete $borrower{$key} unless $borrower{$key};
507 return %borrower;
510 sub FilterUnchangedAttributes {
511 my ( $borrowernumber, $entered_attributes ) = @_;
513 my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
515 my $patron_attribute_types;
516 foreach my $attr (@patron_attributes) {
517 $patron_attribute_types->{ $attr->code } += 1;
520 my $passed_attribute_types;
521 foreach my $attr (@{ $entered_attributes }) {
522 $passed_attribute_types->{ $attr->{ code } } += 1;
525 my @changed_attributes;
527 # Loop through the current patron attributes
528 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
529 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
530 # count differs, overwrite all attributes for given type
531 foreach my $attr (@{ $entered_attributes }) {
532 push @changed_attributes, $attr
533 if $attr->{ code } eq $attribute_type;
535 } else {
536 # count matches, check values
537 my $changes = 0;
538 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
539 $changes = 1
540 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
541 last if $changes;
544 if ( $changes ) {
545 foreach my $attr (@{ $entered_attributes }) {
546 push @changed_attributes, $attr
547 if $attr->{ code } eq $attribute_type;
553 # Loop through passed attributes, looking for new ones
554 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
555 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
556 # YAY, new stuff
557 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
558 push @changed_attributes, $attr;
563 return \@changed_attributes;
566 sub GeneratePatronAttributesForm {
567 my ( $borrowernumber, $entered_attributes ) = @_;
569 # Get all attribute types and the values for this patron (if applicable)
570 my @types = grep { $_->opac_editable() or $_->opac_display }
571 Koha::Patron::Attribute::Types->search()->as_list();
572 if ( scalar(@types) == 0 ) {
573 return [];
576 my @displayable_attributes = grep { $_->opac_display }
577 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
579 my %attr_values = ();
581 # Build the attribute values list either from the passed values
582 # or taken from the patron itself
583 if ( defined $entered_attributes ) {
584 foreach my $attr (@$entered_attributes) {
585 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
588 elsif ( defined $borrowernumber ) {
589 my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
590 foreach my $attr (@editable_attributes) {
591 push @{ $attr_values{ $attr->code } }, $attr->attribute;
595 # Add the non-editable attributes (that don't come from the form)
596 foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
597 push @{ $attr_values{ $attr->code } }, $attr->attribute;
600 # Find all existing classes
601 my @classes = sort( uniq( map { $_->class } @types ) );
602 my %items_by_class;
604 foreach my $attr_type (@types) {
605 push @{ $items_by_class{ $attr_type->class() } }, {
606 type => $attr_type,
607 # If editable, make sure there's at least one empty entry,
608 # to make the template's job easier
609 values => $attr_values{ $attr_type->code() } || ['']
611 unless !defined $attr_values{ $attr_type->code() }
612 and !$attr_type->opac_editable;
615 # Finally, build a list of containing classes
616 my @class_loop;
617 foreach my $class (@classes) {
618 next unless ( $items_by_class{$class} );
620 my $av = Koha::AuthorisedValues->search(
621 { category => 'PA_CLASS', authorised_value => $class } );
623 my $lib = $av->count ? $av->next->opac_description : $class;
625 push @class_loop,
627 class => $class,
628 items => $items_by_class{$class},
629 lib => $lib,
633 return \@class_loop;
636 sub ParsePatronAttributes {
637 my ( $borrowernumber, $cgi ) = @_;
639 my @codes = $cgi->multi_param('patron_attribute_code');
640 my @values = $cgi->multi_param('patron_attribute_value');
642 my @editable_attribute_types
643 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
645 my $ea = each_array( @codes, @values );
646 my @attributes;
648 my $delete_candidates = {};
650 while ( my ( $code, $value ) = $ea->() ) {
651 if ( any { $_ eq $code } @editable_attribute_types ) {
652 # It is an editable attribute
653 if ( !defined($value) or $value eq '' ) {
654 $delete_candidates->{$code} = 1
655 unless $delete_candidates->{$code};
657 else {
658 # we've got a value
659 push @attributes, { code => $code, value => $value };
661 # 'code' is no longer a delete candidate
662 delete $delete_candidates->{$code}
663 if defined $delete_candidates->{$code};
668 foreach my $code ( keys %{$delete_candidates} ) {
669 if ( Koha::Patron::Attributes->search({
670 borrowernumber => $borrowernumber, code => $code })->count > 0 )
672 push @attributes, { code => $code, value => '' }
673 unless any { $_->{code} eq $code } @attributes;
677 return \@attributes;