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