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