6fdc765b574d23468c91d786f8480c3065fe71c0
[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                 $patron->extended_attributes->filter_by_branch_limitations->delete;
217                 $patron->extended_attributes($attributes);
218                 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
219                     C4::Form::MessagingPreferences::handle_form_action(
220                         $cgi,
221                         { borrowernumber => $patron->borrowernumber },
222                         $template,
223                         1,
224                         C4::Context->preference('PatronSelfRegistrationDefaultCategory')
225                     );
226                 }
227
228                 $template->param( password_cleartext => $patron->plain_text_password );
229                 $template->param( borrower => $patron->unblessed );
230             } else {
231                 # FIXME Handle possible errors here
232             }
233             $template->param(
234                 PatronSelfRegistrationAdditionalInstructions =>
235                   C4::Context->preference(
236                     'PatronSelfRegistrationAdditionalInstructions')
237             );
238         }
239     }
240 }
241 elsif ( $action eq 'update' ) {
242
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'),
248         });
249
250     my %borrower = ParseCgiForBorrower($cgi);
251     $borrower{borrowernumber} = $borrowernumber;
252
253     my @empty_mandatory_fields =
254       CheckMandatoryFields( \%borrower, $action );
255     my $invalidformfields = CheckForInvalidFields(\%borrower);
256
257     # Send back the data to the template
258     %borrower = ( %$borrower, %borrower );
259
260     if (@empty_mandatory_fields || @$invalidformfields) {
261         $template->param(
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'),
267             }),
268         );
269         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
270
271         $template->param( action => 'edit' );
272     }
273     else {
274         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
275         $borrower_changes{'changed_fields'} = join ',', keys %borrower_changes;
276         my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
277
278         if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
279             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
280                 {
281                     template_name   => "opac-memberentry-update-submitted.tt",
282                     type            => "opac",
283                     query           => $cgi,
284                     authnotrequired => 1,
285                 }
286             );
287
288             $borrower_changes{borrowernumber} = $borrowernumber;
289             $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
290
291             Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
292
293             my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
294
295             my $patron = Koha::Patrons->find( $borrowernumber );
296             $template->param( borrower => $patron->unblessed );
297         }
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'),
307                 }),
308             );
309         }
310     }
311 }
312 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
313     my $patron = Koha::Patrons->find( $borrowernumber );
314     my $borrower = $patron->unblessed;
315
316     $template->param(
317         borrower  => $borrower,
318         hidden => GetHiddenFields( $mandatory, 'edit' ),
319         csrf_token => Koha::Token->new->generate_csrf({
320             session_id => scalar $cgi->cookie('CGISESSID'),
321         }),
322     );
323
324     if (C4::Context->preference('OPACpatronimages')) {
325         $template->param( display_patron_image => 1 ) if $patron->image;
326     }
327
328     $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
329 } else {
330     # Render self-registration page
331     $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
332 }
333
334 my $captcha = random_string("CCCCC");
335 my $patron_param = Koha::Patrons->find( $borrowernumber );
336 $template->param(
337     has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count
338 ) if $patron_param;
339
340 $template->param(
341     captcha        => $captcha,
342     captcha_digest => md5_base64($captcha),
343     patron         => $patron_param
344 );
345
346 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
347
348 sub GetHiddenFields {
349     my ( $mandatory, $action ) = @_;
350     my %hidden_fields;
351
352     my $BorrowerUnwantedField = $action eq 'edit' || $action eq 'update' ?
353       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
354       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
355
356     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
357     foreach (@fields) {
358         next unless m/\w/o;
359         #Don't hide mandatory fields
360         next if $mandatory->{$_};
361         $hidden_fields{$_} = 1;
362     }
363
364     return \%hidden_fields;
365 }
366
367 sub GetMandatoryFields {
368     my ($action) = @_;
369
370     my %mandatory_fields;
371
372     my $BorrowerMandatoryField =
373       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
374
375     my @fields = split( /\|/, $BorrowerMandatoryField );
376     push @fields, 'gdpr_proc_consent' if C4::Context->preference('GDPR_Policy') && $action eq 'create';
377
378     foreach (@fields) {
379         $mandatory_fields{$_} = 1;
380     }
381
382     if ( $action eq 'create' || $action eq 'new' ) {
383         $mandatory_fields{'email'} = 1
384           if C4::Context->boolean_preference(
385             'PatronSelfRegistrationVerifyByEmail');
386     }
387
388     return \%mandatory_fields;
389 }
390
391 sub CheckMandatoryFields {
392     my ( $borrower, $action ) = @_;
393
394     my @empty_mandatory_fields;
395
396     my $mandatory_fields = GetMandatoryFields($action);
397     delete $mandatory_fields->{'cardnumber'};
398
399     foreach my $key ( keys %$mandatory_fields ) {
400         push( @empty_mandatory_fields, $key )
401           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
402     }
403
404     return @empty_mandatory_fields;
405 }
406
407 sub CheckForInvalidFields {
408     my $borrower = shift;
409     my @invalidFields;
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?
415                 {
416                     email => $borrower->{email},
417                     (
418                         exists $borrower->{borrowernumber}
419                         ? ( borrowernumber =>
420                               { '!=' => $borrower->{borrowernumber} } )
421                         : ()
422                     )
423                 }
424             )->count;
425             if ( $patrons_with_same_email ) {
426                 push @invalidFields, "duplicate_email";
427             }
428         }
429     }
430     if ($borrower->{'emailpro'}) {
431         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
432     }
433     if ($borrower->{'B_email'}) {
434         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
435     }
436     if ( defined $borrower->{'password'}
437         and $borrower->{'password'} ne $borrower->{'password2'} )
438     {
439         push( @invalidFields, "password_match" );
440     }
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';
447           }
448     }
449
450     return \@invalidFields;
451 }
452
453 sub ParseCgiForBorrower {
454     my ($cgi) = @_;
455
456     my $scrubber = C4::Scrubber->new();
457     my %borrower;
458
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) );
464             } else {
465                 # Allow html characters for passwords
466                 $borrower{$key} = $cgi->param($field);
467             }
468         }
469     }
470
471     my $dob_dt;
472     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
473         if ( $borrower{'dateofbirth'} );
474
475     if ( $dob_dt ) {
476         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
477     }
478     else {
479         # Trigger validation
480         $borrower{'dateofbirth'} = undef;
481     }
482
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';
485
486     return %borrower;
487 }
488
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');
497
498
499     foreach my $key ( keys %new_data ) {
500         next if defined($new_data{$key}) xor defined($current_data->{$key});
501         if ( !defined($new_data{$key}) || $current_data->{$key} eq $new_data{$key} || $hidden_fields->{$key} ) {
502            delete $new_data{$key};
503         }
504     }
505
506     return %new_data;
507 }
508
509 sub DelEmptyFields {
510     my (%borrower) = @_;
511
512     foreach my $key ( keys %borrower ) {
513         delete $borrower{$key} unless $borrower{$key};
514     }
515
516     return %borrower;
517 }
518
519 sub FilterUnchangedAttributes {
520     my ( $borrowernumber, $entered_attributes ) = @_;
521
522     my @patron_attributes = grep {$_->type->opac_editable ? $_ : ()} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
523
524     my $patron_attribute_types;
525     foreach my $attr (@patron_attributes) {
526         $patron_attribute_types->{ $attr->code } += 1;
527     }
528
529     my $passed_attribute_types;
530     foreach my $attr (@{ $entered_attributes }) {
531         $passed_attribute_types->{ $attr->{ code } } += 1;
532     }
533
534     my @changed_attributes;
535
536     # Loop through the current patron attributes
537     foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
538         if ( $patron_attribute_types->{ $attribute_type } !=  $passed_attribute_types->{ $attribute_type } ) {
539             # count differs, overwrite all attributes for given type
540             foreach my $attr (@{ $entered_attributes }) {
541                 push @changed_attributes, $attr
542                     if $attr->{ code } eq $attribute_type;
543             }
544         } else {
545             # count matches, check values
546             my $changes = 0;
547             foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
548                 $changes = 1
549                     unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
550                 last if $changes;
551             }
552
553             if ( $changes ) {
554                 foreach my $attr (@{ $entered_attributes }) {
555                     push @changed_attributes, $attr
556                         if $attr->{ code } eq $attribute_type;
557                 }
558             }
559         }
560     }
561
562     # Loop through passed attributes, looking for new ones
563     foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
564         if ( !defined $patron_attribute_types->{ $attribute_type } ) {
565             # YAY, new stuff
566             foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
567                 push @changed_attributes, $attr;
568             }
569         }
570     }
571
572     return \@changed_attributes;
573 }
574
575 sub GeneratePatronAttributesForm {
576     my ( $borrowernumber, $entered_attributes ) = @_;
577
578     # Get all attribute types and the values for this patron (if applicable)
579     my @types = grep { $_->opac_editable() or $_->opac_display }
580         Koha::Patron::Attribute::Types->search()->as_list();
581     if ( scalar(@types) == 0 ) {
582         return [];
583     }
584
585     my @displayable_attributes = grep { $_->type->opac_display ? $_ : () }
586         Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
587
588     my %attr_values = ();
589
590     # Build the attribute values list either from the passed values
591     # or taken from the patron itself
592     if ( defined $entered_attributes ) {
593         foreach my $attr (@$entered_attributes) {
594             push @{ $attr_values{ $attr->{code} } }, $attr->{value};
595         }
596     }
597     elsif ( defined $borrowernumber ) {
598         my @editable_attributes = grep { $_->type->opac_editable ? $_ : () } @displayable_attributes;
599         foreach my $attr (@editable_attributes) {
600             push @{ $attr_values{ $attr->code } }, $attr->attribute;
601         }
602     }
603
604     # Add the non-editable attributes (that don't come from the form)
605     foreach my $attr ( grep { !$_->type->opac_editable } @displayable_attributes ) {
606         push @{ $attr_values{ $attr->code } }, $attr->attribute;
607     }
608
609     # Find all existing classes
610     my @classes = sort( uniq( map { $_->class } @types ) );
611     my %items_by_class;
612
613     foreach my $attr_type (@types) {
614         push @{ $items_by_class{ $attr_type->class() } }, {
615             type => $attr_type,
616             # If editable, make sure there's at least one empty entry,
617             # to make the template's job easier
618             values => $attr_values{ $attr_type->code() } || ['']
619         }
620             unless !defined $attr_values{ $attr_type->code() }
621                     and !$attr_type->opac_editable;
622     }
623
624     # Finally, build a list of containing classes
625     my @class_loop;
626     foreach my $class (@classes) {
627         next unless ( $items_by_class{$class} );
628
629         my $av = Koha::AuthorisedValues->search(
630             { category => 'PA_CLASS', authorised_value => $class } );
631
632         my $lib = $av->count ? $av->next->opac_description : $class;
633
634         push @class_loop,
635             {
636             class => $class,
637             items => $items_by_class{$class},
638             lib   => $lib,
639             };
640     }
641
642     return \@class_loop;
643 }
644
645 sub ParsePatronAttributes {
646     my ( $borrowernumber, $cgi ) = @_;
647
648     my @codes  = $cgi->multi_param('patron_attribute_code');
649     my @values = $cgi->multi_param('patron_attribute_value');
650
651     my @editable_attribute_types
652         = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
653
654     my $ea = each_array( @codes, @values );
655     my @attributes;
656
657     my $delete_candidates = {};
658
659     while ( my ( $code, $value ) = $ea->() ) {
660         if ( any { $_ eq $code } @editable_attribute_types ) {
661             # It is an editable attribute
662             if ( !defined($value) or $value eq '' ) {
663                 $delete_candidates->{$code} = 1
664                     unless $delete_candidates->{$code};
665             }
666             else {
667                 # we've got a value
668                 push @attributes, { code => $code, value => $value };
669
670                 # 'code' is no longer a delete candidate
671                 delete $delete_candidates->{$code}
672                     if defined $delete_candidates->{$code};
673             }
674         }
675     }
676
677     foreach my $code ( keys %{$delete_candidates} ) {
678         if ( Koha::Patron::Attributes->search({
679                 borrowernumber => $borrowernumber, code => $code })->count > 0 )
680         {
681             push @attributes, { code => $code, value => '' }
682                 unless any { $_->{code} eq $code } @attributes;
683         }
684     }
685
686     return \@attributes;
687 }
688
689
690 1;