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