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