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