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