669687eeed6abe8a192154cc2a4c2a1053f5cc34
[koha.git] / opac / opac-memberentry.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
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.
9 #
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.
14 #
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>.
17
18 use Modern::Perl;
19
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 );
25
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;
46
47 my $cgi = new CGI;
48 my $dbh = C4::Context->dbh;
49
50 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
51     {
52         template_name   => "opac-memberentry.tt",
53         type            => "opac",
54         query           => $cgi,
55         authnotrequired => 1,
56     }
57 );
58
59 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
60 {
61     print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
62     exit;
63 }
64
65 my $action = $cgi->param('action') || q{};
66 if ( $action eq q{} ) {
67     if ($borrowernumber) {
68         $action = 'edit';
69     }
70     else {
71         $action = 'new';
72     }
73 }
74
75 my $mandatory = GetMandatoryFields($action);
76
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;
80 }
81 my ( $min, $max ) = C4::Members::get_cardnumber_length();
82 if ( defined $min ) {
83      $template->param(
84          minlength_cardnumber => $min,
85          maxlength_cardnumber => $max
86      );
87  }
88
89 $template->param(
90     action            => $action,
91     hidden            => GetHiddenFields( $mandatory, $action ),
92     mandatory         => $mandatory,
93     libraries         => \@libraries,
94     OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
95 );
96
97 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
98 my $conflicting_attribute = 0;
99
100 foreach my $attr (@$attributes) {
101     unless ( C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber) ) {
102         my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
103         $template->param(
104             extended_unique_id_failed_code => $attr->{code},
105             extended_unique_id_failed_value => $attr->{value},
106             extended_unique_id_failed_description => $attr_info->description()
107         );
108         $conflicting_attribute = 1;
109     }
110 }
111
112 if ( $action eq 'create' ) {
113
114     my %borrower = ParseCgiForBorrower($cgi);
115
116     %borrower = DelEmptyFields(%borrower);
117
118     my @empty_mandatory_fields = CheckMandatoryFields( \%borrower, $action );
119     my $invalidformfields = CheckForInvalidFields(\%borrower);
120     delete $borrower{'password2'};
121     my $cardnumber_error_code;
122     if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
123         # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
124         # spurious length warning.
125         $cardnumber_error_code = checkcardnumber( $borrower{cardnumber}, $borrower{borrowernumber} );
126     }
127
128     if ( @empty_mandatory_fields || @$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
129         if ( $cardnumber_error_code == 1 ) {
130             $template->param( cardnumber_already_exists => 1 );
131         } elsif ( $cardnumber_error_code == 2 ) {
132             $template->param( cardnumber_wrong_length => 1 );
133         }
134
135         $template->param(
136             empty_mandatory_fields => \@empty_mandatory_fields,
137             invalid_form_fields    => $invalidformfields,
138             borrower               => \%borrower
139         );
140         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
141     }
142     elsif (
143         md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
144     {
145         $template->param(
146             failed_captcha => 1,
147             borrower       => \%borrower
148         );
149         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
150     }
151     else {
152         if (
153             C4::Context->boolean_preference(
154                 'PatronSelfRegistrationVerifyByEmail')
155           )
156         {
157             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
158                 {
159                     template_name   => "opac-registration-email-sent.tt",
160                     type            => "opac",
161                     query           => $cgi,
162                     authnotrequired => 1,
163                 }
164             );
165             $template->param( 'email' => $borrower{'email'} );
166
167             my $verification_token = md5_hex( time().{}.rand().{}.$$ );
168             while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
169                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
170             }
171
172             $borrower{password}          = Koha::AuthUtils::generate_password unless $borrower{password};
173             $borrower{verification_token} = $verification_token;
174
175             Koha::Patron::Modification->new( \%borrower )->store();
176
177             #Send verification email
178             my $letter = C4::Letters::GetPreparedLetter(
179                 module      => 'members',
180                 letter_code => 'OPAC_REG_VERIFY',
181                 lang        => 'default', # Patron does not have a preferred language defined yet
182                 tables      => {
183                     borrower_modifications => $verification_token,
184                 },
185             );
186
187             C4::Letters::EnqueueLetter(
188                 {
189                     letter                 => $letter,
190                     message_transport_type => 'email',
191                     to_address             => $borrower{'email'},
192                     from_address =>
193                       C4::Context->preference('KohaAdminEmailAddress'),
194                 }
195             );
196             my $num_letters_attempted = C4::Letters::SendQueuedMessages( {
197                     letter_code => 'OPAC_REG_VERIFY'
198                     } );
199         }
200         else {
201             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
202                 {
203                     template_name   => "opac-registration-confirmation.tt",
204                     type            => "opac",
205                     query           => $cgi,
206                     authnotrequired => 1,
207                 }
208             );
209
210             $borrower{categorycode}     ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
211             $borrower{password}         ||= Koha::AuthUtils::generate_password;
212             my $consent_dt = delete $borrower{gdpr_proc_consent};
213             my $patron = Koha::Patron->new( \%borrower )->store;
214             Koha::Patron::Consent->new({ borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt })->store if $consent_dt;
215             if ( $patron ) {
216                 C4::Members::Attributes::SetBorrowerAttributes( $patron->borrowernumber, $attributes );
217                 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
218                     C4::Form::MessagingPreferences::handle_form_action(
219                         $cgi,
220                         { borrowernumber => $patron->borrowernumber },
221                         $template,
222                         1,
223                         C4::Context->preference('PatronSelfRegistrationDefaultCategory')
224                     );
225                 }
226
227                 $template->param( password_cleartext => $patron->plain_text_password );
228                 $template->param( borrower => $patron->unblessed );
229             } else {
230                 # FIXME Handle possible errors here
231             }
232             $template->param(
233                 PatronSelfRegistrationAdditionalInstructions =>
234                   C4::Context->preference(
235                     'PatronSelfRegistrationAdditionalInstructions')
236             );
237         }
238     }
239 }
240 elsif ( $action eq 'update' ) {
241
242     my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
243     die "Wrong CSRF token"
244         unless Koha::Token->new->check_csrf({
245             session_id => scalar $cgi->cookie('CGISESSID'),
246             token  => scalar $cgi->param('csrf_token'),
247         });
248
249     my %borrower = ParseCgiForBorrower($cgi);
250     $borrower{borrowernumber} = $borrowernumber;
251
252     my @empty_mandatory_fields =
253       CheckMandatoryFields( \%borrower, $action );
254     my $invalidformfields = CheckForInvalidFields(\%borrower);
255
256     # Send back the data to the template
257     %borrower = ( %$borrower, %borrower );
258
259     if (@empty_mandatory_fields || @$invalidformfields) {
260         $template->param(
261             empty_mandatory_fields => \@empty_mandatory_fields,
262             invalid_form_fields    => $invalidformfields,
263             borrower               => \%borrower,
264             csrf_token             => Koha::Token->new->generate_csrf({
265                 session_id => scalar $cgi->cookie('CGISESSID'),
266             }),
267         );
268         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
269
270         $template->param( action => 'edit' );
271     }
272     else {
273         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
274         $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
275         my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
276
277         if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
278             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
279                 {
280                     template_name   => "opac-memberentry-update-submitted.tt",
281                     type            => "opac",
282                     query           => $cgi,
283                     authnotrequired => 1,
284                 }
285             );
286
287             $borrower_changes{borrowernumber} = $borrowernumber;
288             $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
289
290             Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
291
292             my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
293
294             my $patron = Koha::Patrons->find( $borrowernumber );
295             $template->param( borrower => $patron->unblessed );
296         }
297         else {
298             my $patron = Koha::Patrons->find( $borrowernumber );
299             $template->param(
300                 action => 'edit',
301                 nochanges => 1,
302                 borrower => $patron->unblessed,
303                 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
304                 csrf_token => Koha::Token->new->generate_csrf({
305                     session_id => scalar $cgi->cookie('CGISESSID'),
306                 }),
307             );
308         }
309     }
310 }
311 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
312     my $patron = Koha::Patrons->find( $borrowernumber );
313     my $borrower = $patron->unblessed;
314
315     $template->param(
316         borrower  => $borrower,
317         hidden => GetHiddenFields( $mandatory, 'edit' ),
318         csrf_token => Koha::Token->new->generate_csrf({
319             session_id => scalar $cgi->cookie('CGISESSID'),
320         }),
321     );
322
323     if (C4::Context->preference('OPACpatronimages')) {
324         $template->param( display_patron_image => 1 ) if $patron->image;
325     }
326
327     $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
328 } else {
329     # Render self-registration page
330     $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
331 }
332
333 my $captcha = random_string("CCCCC");
334 my $patron_param = Koha::Patrons->find( $borrowernumber );
335 $template->param(
336     has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count
337 ) if $patron_param;
338
339 $template->param(
340     captcha        => $captcha,
341     captcha_digest => md5_base64($captcha),
342     patron         => $patron_param
343 );
344
345 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
346
347 sub GetHiddenFields {
348     my ( $mandatory, $action ) = @_;
349     my %hidden_fields;
350
351     my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
352       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
353       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
354
355     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
356     foreach (@fields) {
357         next unless m/\w/o;
358         #Don't hide mandatory fields
359         next if $mandatory->{$_};
360         $hidden_fields{$_} = 1;
361     }
362
363     return \%hidden_fields;
364 }
365
366 sub GetMandatoryFields {
367     my ($action) = @_;
368
369     my %mandatory_fields;
370
371     my $BorrowerMandatoryField =
372       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
373
374     my @fields = split( /\|/, $BorrowerMandatoryField );
375     push @fields, 'gdpr_proc_consent' if C4::Context->preference('GDPR_Policy') && $action eq 'create';
376
377     foreach (@fields) {
378         $mandatory_fields{$_} = 1;
379     }
380
381     if ( $action eq 'create' || $action eq 'new' ) {
382         $mandatory_fields{'email'} = 1
383           if C4::Context->boolean_preference(
384             'PatronSelfRegistrationVerifyByEmail');
385     }
386
387     return \%mandatory_fields;
388 }
389
390 sub CheckMandatoryFields {
391     my ( $borrower, $action ) = @_;
392
393     my @empty_mandatory_fields;
394
395     my $mandatory_fields = GetMandatoryFields($action);
396     delete $mandatory_fields->{'cardnumber'};
397
398     foreach my $key ( keys %$mandatory_fields ) {
399         push( @empty_mandatory_fields, $key )
400           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
401     }
402
403     return @empty_mandatory_fields;
404 }
405
406 sub CheckForInvalidFields {
407     my $borrower = shift;
408     my @invalidFields;
409     if ($borrower->{'email'}) {
410         unless ( Email::Valid->address($borrower->{'email'}) ) {
411             push(@invalidFields, "email");
412         } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
413             my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
414                 {
415                     email => $borrower->{email},
416                     (
417                         exists $borrower->{borrowernumber}
418                         ? ( borrowernumber =>
419                               { '!=' => $borrower->{borrowernumber} } )
420                         : ()
421                     )
422                 }
423             )->count;
424             if ( $patrons_with_same_email ) {
425                 push @invalidFields, "duplicate_email";
426             }
427         }
428     }
429     if ($borrower->{'emailpro'}) {
430         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
431     }
432     if ($borrower->{'B_email'}) {
433         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
434     }
435     if ( defined $borrower->{'password'}
436         and $borrower->{'password'} ne $borrower->{'password2'} )
437     {
438         push( @invalidFields, "password_match" );
439     }
440     if ( $borrower->{'password'} ) {
441         my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
442           unless ( $is_valid ) {
443               push @invalidFields, 'password_too_short' if $error eq 'too_short';
444               push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
445               push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
446           }
447     }
448
449     return \@invalidFields;
450 }
451
452 sub ParseCgiForBorrower {
453     my ($cgi) = @_;
454
455     my $scrubber = C4::Scrubber->new();
456     my %borrower;
457
458     foreach my $field ( $cgi->param ) {
459         if ( $field =~ '^borrower_' ) {
460             my ($key) = substr( $field, 9 );
461             if ( $field !~ '^borrower_password' ) {
462                 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
463             } else {
464                 # Allow html characters for passwords
465                 $borrower{$key} = $cgi->param($field);
466             }
467         }
468     }
469
470     my $dob_dt;
471     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
472         if ( $borrower{'dateofbirth'} );
473
474     if ( $dob_dt ) {
475         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
476     }
477     else {
478         # Trigger validation
479         $borrower{'dateofbirth'} = undef;
480     }
481
482     # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
483     $borrower{gdpr_proc_consent} = dt_from_string if  $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed';
484
485     return %borrower;
486 }
487
488 sub DelUnchangedFields {
489     my ( $borrowernumber, %new_data ) = @_;
490     # get the mandatory fields so we can get the hidden fields
491     my $mandatory = GetMandatoryFields('edit');
492     my $patron = Koha::Patrons->find( $borrowernumber );
493     my $current_data = $patron->unblessed;
494     # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify
495     my $hidden_fields = GetHiddenFields($mandatory, 'edit');
496
497
498     foreach my $key ( keys %new_data ) {
499         next if defined($new_data{$key}) xor defined($current_data->{$key});
500         if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
501            delete $new_data{$key};
502         }
503     }
504
505     return %new_data;
506 }
507
508 sub DelEmptyFields {
509     my (%borrower) = @_;
510
511     foreach my $key ( keys %borrower ) {
512         delete $borrower{$key} unless $borrower{$key};
513     }
514
515     return %borrower;
516 }
517
518 sub FilterUnchangedAttributes {
519     my ( $borrowernumber, $entered_attributes ) = @_;
520
521     my @patron_attributes = grep {$_->type->opac_editable ? $_ : ()} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
522
523     my $patron_attribute_types;
524     foreach my $attr (@patron_attributes) {
525         $patron_attribute_types->{ $attr->code } += 1;
526     }
527
528     my $passed_attribute_types;
529     foreach my $attr (@{ $entered_attributes }) {
530         $passed_attribute_types->{ $attr->{ code } } += 1;
531     }
532
533     my @changed_attributes;
534
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;
542             }
543         } else {
544             # count matches, check values
545             my $changes = 0;
546             foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
547                 $changes = 1
548                     unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
549                 last if $changes;
550             }
551
552             if ( $changes ) {
553                 foreach my $attr (@{ $entered_attributes }) {
554                     push @changed_attributes, $attr
555                         if $attr->{ code } eq $attribute_type;
556                 }
557             }
558         }
559     }
560
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 } ) {
564             # YAY, new stuff
565             foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
566                 push @changed_attributes, $attr;
567             }
568         }
569     }
570
571     return \@changed_attributes;
572 }
573
574 sub GeneratePatronAttributesForm {
575     my ( $borrowernumber, $entered_attributes ) = @_;
576
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 ) {
581         return [];
582     }
583
584     my @displayable_attributes = grep { $_->type->opac_display ? $_ : () }
585         Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
586
587     my %attr_values = ();
588
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};
594         }
595     }
596     elsif ( defined $borrowernumber ) {
597         my @editable_attributes = grep { $_->type->opac_editable ? $_ : () } @displayable_attributes;
598         foreach my $attr (@editable_attributes) {
599             push @{ $attr_values{ $attr->code } }, $attr->attribute;
600         }
601     }
602
603     # Add the non-editable attributes (that don't come from the form)
604     foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
605         push @{ $attr_values{ $attr->code } }, $attr->attribute;
606     }
607
608     # Find all existing classes
609     my @classes = sort( uniq( map { $_->class } @types ) );
610     my %items_by_class;
611
612     foreach my $attr_type (@types) {
613         push @{ $items_by_class{ $attr_type->class() } }, {
614             type => $attr_type,
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() } || ['']
618         }
619             unless !defined $attr_values{ $attr_type->code() }
620                     and !$attr_type->opac_editable;
621     }
622
623     # Finally, build a list of containing classes
624     my @class_loop;
625     foreach my $class (@classes) {
626         next unless ( $items_by_class{$class} );
627
628         my $av = Koha::AuthorisedValues->search(
629             { category => 'PA_CLASS', authorised_value => $class } );
630
631         my $lib = $av->count ? $av->next->opac_description : $class;
632
633         push @class_loop,
634             {
635             class => $class,
636             items => $items_by_class{$class},
637             lib   => $lib,
638             };
639     }
640
641     return \@class_loop;
642 }
643
644 sub ParsePatronAttributes {
645     my ( $borrowernumber, $cgi ) = @_;
646
647     my @codes  = $cgi->multi_param('patron_attribute_code');
648     my @values = $cgi->multi_param('patron_attribute_value');
649
650     my @editable_attribute_types
651         = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
652
653     my $ea = each_array( @codes, @values );
654     my @attributes;
655
656     my $delete_candidates = {};
657
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};
664             }
665             else {
666                 # we've got a value
667                 push @attributes, { code => $code, value => $value };
668
669                 # 'code' is no longer a delete candidate
670                 delete $delete_candidates->{$code}
671                     if defined $delete_candidates->{$code};
672             }
673         }
674     }
675
676     foreach my $code ( keys %{$delete_candidates} ) {
677         if ( Koha::Patron::Attributes->search({
678                 borrowernumber => $borrowernumber, code => $code })->count > 0 )
679         {
680             push @attributes, { code => $code, value => '' }
681                 unless any { $_->{code} eq $code } @attributes;
682         }
683     }
684
685     return \@attributes;
686 }
687
688
689 1;