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