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