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