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