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