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