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