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