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