Bug 13757: (QA followup) Fix non-editable attrs on failed save
[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 Encode qw( encode );
23 use JSON;
24 use List::MoreUtils qw( any each_array uniq );
25 use String::Random qw( random_string );
26
27 use C4::Auth;
28 use C4::Output;
29 use C4::Members;
30 use C4::Members::Attributes qw( GetBorrowerAttributes );
31 use C4::Form::MessagingPreferences;
32 use C4::Scrubber;
33 use Email::Valid;
34 use Koha::DateUtils;
35 use Koha::Libraries;
36 use Koha::Patron::Attribute::Types;
37 use Koha::Patron::Attributes;
38 use Koha::Patron::Images;
39 use Koha::Patron::Modification;
40 use Koha::Patron::Modifications;
41 use Koha::Patrons;
42 use Koha::Token;
43
44 my $cgi = new CGI;
45 my $dbh = C4::Context->dbh;
46
47 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
48     {
49         template_name   => "opac-memberentry.tt",
50         type            => "opac",
51         query           => $cgi,
52         authnotrequired => 1,
53     }
54 );
55
56 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
57 {
58     print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
59     exit;
60 }
61
62 my $action = $cgi->param('action') || q{};
63 if ( $action eq q{} ) {
64     if ($borrowernumber) {
65         $action = 'edit';
66     }
67     else {
68         $action = 'new';
69     }
70 }
71
72 my $mandatory = GetMandatoryFields($action);
73
74 my @libraries = Koha::Libraries->search;
75 if ( my @libraries_to_display = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList') ) {
76     @libraries = map { my $b = $_; my $branchcode = $_->branchcode; grep( /^$branchcode$/, @libraries_to_display ) ? $b : () } @libraries;
77 }
78 my ( $min, $max ) = C4::Members::get_cardnumber_length();
79 if ( defined $min ) {
80      $template->param(
81          minlength_cardnumber => $min,
82          maxlength_cardnumber => $max
83      );
84  }
85
86 $template->param(
87     action            => $action,
88     hidden            => GetHiddenFields( $mandatory, 'registration' ),
89     mandatory         => $mandatory,
90     libraries         => \@libraries,
91     OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
92 );
93
94 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
95 my $conflicting_attribute = 0;
96
97 foreach my $attr (@$attributes) {
98     unless ( C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber) ) {
99         my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
100         $template->param(
101             extended_unique_id_failed_code => $attr->{code},
102             extended_unique_id_failed_value => $attr->{value},
103             extended_unique_id_failed_description => $attr_info->description()
104         );
105         $conflicting_attribute = 1;
106     }
107 }
108
109 if ( $action eq 'create' ) {
110
111     my %borrower = ParseCgiForBorrower($cgi);
112
113     %borrower = DelEmptyFields(%borrower);
114
115     my @empty_mandatory_fields = CheckMandatoryFields( \%borrower, $action );
116     my $invalidformfields = CheckForInvalidFields(\%borrower);
117     delete $borrower{'password2'};
118     my $cardnumber_error_code;
119     if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) {
120         # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a
121         # spurious length warning.
122         $cardnumber_error_code = checkcardnumber( $borrower{cardnumber}, $borrower{borrowernumber} );
123     }
124
125     if ( @empty_mandatory_fields || @$invalidformfields || $cardnumber_error_code || $conflicting_attribute ) {
126         if ( $cardnumber_error_code == 1 ) {
127             $template->param( cardnumber_already_exists => 1 );
128         } elsif ( $cardnumber_error_code == 2 ) {
129             $template->param( cardnumber_wrong_length => 1 );
130         }
131
132         $template->param(
133             empty_mandatory_fields => \@empty_mandatory_fields,
134             invalid_form_fields    => $invalidformfields,
135             borrower               => \%borrower
136         );
137         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
138     }
139     elsif (
140         md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
141     {
142         $template->param(
143             failed_captcha => 1,
144             borrower       => \%borrower
145         );
146         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
147     }
148     else {
149         if (
150             C4::Context->boolean_preference(
151                 'PatronSelfRegistrationVerifyByEmail')
152           )
153         {
154             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
155                 {
156                     template_name   => "opac-registration-email-sent.tt",
157                     type            => "opac",
158                     query           => $cgi,
159                     authnotrequired => 1,
160                 }
161             );
162             $template->param( 'email' => $borrower{'email'} );
163
164             my $verification_token = md5_hex( time().{}.rand().{}.$$ );
165             while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) {
166                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
167             }
168
169             $borrower{password}           = random_string("..........");
170             $borrower{verification_token} = $verification_token;
171
172             Koha::Patron::Modification->new( \%borrower )->store();
173
174             #Send verification email
175             my $letter = C4::Letters::GetPreparedLetter(
176                 module      => 'members',
177                 letter_code => 'OPAC_REG_VERIFY',
178                 tables      => {
179                     borrower_modifications => $verification_token,
180                 },
181             );
182
183             C4::Letters::EnqueueLetter(
184                 {
185                     letter                 => $letter,
186                     message_transport_type => 'email',
187                     to_address             => $borrower{'email'},
188                     from_address =>
189                       C4::Context->preference('KohaAdminEmailAddress'),
190                 }
191             );
192         }
193         else {
194             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
195                 {
196                     template_name   => "opac-registration-confirmation.tt",
197                     type            => "opac",
198                     query           => $cgi,
199                     authnotrequired => 1,
200                 }
201             );
202
203             $template->param( OpacPasswordChange =>
204                   C4::Context->preference('OpacPasswordChange') );
205
206             my ( $borrowernumber, $password ) = AddMember_Opac(%borrower);
207             C4::Members::Attributes::SetBorrowerAttributes( $borrowernumber, $attributes );
208             C4::Form::MessagingPreferences::handle_form_action($cgi, { borrowernumber => $borrowernumber }, $template, 1, C4::Context->preference('PatronSelfRegistrationDefaultCategory') ) if $borrowernumber && C4::Context->preference('EnhancedMessagingPreferences');
209
210             $template->param( password_cleartext => $password );
211             $template->param(
212                 borrower => GetMember( borrowernumber => $borrowernumber ) );
213             $template->param(
214                 PatronSelfRegistrationAdditionalInstructions =>
215                   C4::Context->preference(
216                     'PatronSelfRegistrationAdditionalInstructions')
217             );
218         }
219     }
220 }
221 elsif ( $action eq 'update' ) {
222
223     my $borrower = GetMember( borrowernumber => $borrowernumber );
224     die "Wrong CSRF token"
225         unless Koha::Token->new->check_csrf({
226             id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
227             secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
228             token  => scalar $cgi->param('csrf_token'),
229         });
230
231     my %borrower = ParseCgiForBorrower($cgi);
232
233     my %borrower_changes = DelEmptyFields(%borrower);
234     my @empty_mandatory_fields =
235       CheckMandatoryFields( \%borrower_changes, $action );
236     my $invalidformfields = CheckForInvalidFields(\%borrower);
237
238     # Send back the data to the template
239     %borrower = ( %$borrower, %borrower );
240
241     if (@empty_mandatory_fields || @$invalidformfields) {
242         $template->param(
243             empty_mandatory_fields => \@empty_mandatory_fields,
244             invalid_form_fields    => $invalidformfields,
245             borrower               => \%borrower,
246             csrf_token             => Koha::Token->new->generate_csrf({
247                 id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
248                 secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
249             }),
250         );
251         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
252
253         $template->param( action => 'edit' );
254     }
255     else {
256         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
257         my $extended_attributes_changes = FilterUnchagedAttributes( $borrowernumber, $attributes );
258
259         if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
260             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
261                 {
262                     template_name   => "opac-memberentry-update-submitted.tt",
263                     type            => "opac",
264                     query           => $cgi,
265                     authnotrequired => 1,
266                 }
267             );
268
269             $borrower_changes{borrowernumber} = $borrowernumber;
270             $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
271
272             # FIXME update the following with
273             # Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
274             # when bug 17091 will be pushed
275             my $patron_modifications = Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber });
276             while ( my $patron_modification = $patron_modifications->next ) {
277                 $patron_modification->delete;
278             }
279
280             my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
281
282             $template->param(
283                 borrower => GetMember( borrowernumber => $borrowernumber ),
284             );
285         }
286         else {
287             $template->param(
288                 action => 'edit',
289                 nochanges => 1,
290                 borrower => GetMember( borrowernumber => $borrowernumber ),
291                 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
292                 csrf_token => Koha::Token->new->generate_csrf({
293                     id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
294                     secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
295                 }),
296             );
297         }
298     }
299 }
300 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
301     my $borrower = GetMember( borrowernumber => $borrowernumber );
302
303     $template->param(
304         borrower  => $borrower,
305         guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
306         hidden => GetHiddenFields( $mandatory, 'modification' ),
307         csrf_token => Koha::Token->new->generate_csrf({
308             id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
309             secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
310         }),
311     );
312
313     if (C4::Context->preference('OPACpatronimages')) {
314         my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
315         $template->param( display_patron_image => 1 ) if $patron_image;
316     }
317
318     $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
319 } else {
320     $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
321 }
322
323 my $captcha = random_string("CCCCC");
324
325 $template->param(
326     captcha        => $captcha,
327     captcha_digest => md5_base64($captcha)
328 );
329
330 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
331
332 sub GetHiddenFields {
333     my ( $mandatory, $action ) = @_;
334     my %hidden_fields;
335
336     my $BorrowerUnwantedField = $action eq 'modification' ?
337       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
338       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
339
340     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
341     foreach (@fields) {
342         next unless m/\w/o;
343         #Don't hide mandatory fields
344         next if $mandatory->{$_};
345         $hidden_fields{$_} = 1;
346     }
347
348     return \%hidden_fields;
349 }
350
351 sub GetMandatoryFields {
352     my ($action) = @_;
353
354     my %mandatory_fields;
355
356     my $BorrowerMandatoryField =
357       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
358
359     my @fields = split( /\|/, $BorrowerMandatoryField );
360
361     foreach (@fields) {
362         $mandatory_fields{$_} = 1;
363     }
364
365     if ( $action eq 'create' || $action eq 'new' ) {
366         $mandatory_fields{'email'} = 1
367           if C4::Context->boolean_preference(
368             'PatronSelfRegistrationVerifyByEmail');
369     }
370
371     return \%mandatory_fields;
372 }
373
374 sub CheckMandatoryFields {
375     my ( $borrower, $action ) = @_;
376
377     my @empty_mandatory_fields;
378
379     my $mandatory_fields = GetMandatoryFields($action);
380     delete $mandatory_fields->{'cardnumber'};
381
382     foreach my $key ( keys %$mandatory_fields ) {
383         push( @empty_mandatory_fields, $key )
384           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
385     }
386
387     return @empty_mandatory_fields;
388 }
389
390 sub CheckForInvalidFields {
391     my $minpw = C4::Context->preference('minPasswordLength');
392     my $borrower = shift;
393     my @invalidFields;
394     if ($borrower->{'email'}) {
395         unless ( Email::Valid->address($borrower->{'email'}) ) {
396             push(@invalidFields, "email");
397         } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
398             my $patrons_with_same_email = Koha::Patrons->search( { email => $borrower->{email} })->count;
399             if ( $patrons_with_same_email ) {
400                 push @invalidFields, "duplicate_email";
401             }
402         }
403     }
404     if ($borrower->{'emailpro'}) {
405         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
406     }
407     if ($borrower->{'B_email'}) {
408         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
409     }
410     if ( defined $borrower->{'password'}
411         and $borrower->{'password'} ne $borrower->{'password2'} )
412     {
413         push( @invalidFields, "password_match" );
414     }
415     if ( $borrower->{'password'}  && $minpw && (length($borrower->{'password'}) < $minpw) ) {
416        push(@invalidFields, "password_invalid");
417     }
418     if ( $borrower->{'password'} ) {
419        push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
420     }
421
422     return \@invalidFields;
423 }
424
425 sub ParseCgiForBorrower {
426     my ($cgi) = @_;
427
428     my $scrubber = C4::Scrubber->new();
429     my %borrower;
430
431     foreach ( $cgi->param ) {
432         if ( $_ =~ '^borrower_' ) {
433             my ($key) = substr( $_, 9 );
434             $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
435         }
436     }
437
438     my $dob_dt;
439     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
440         if ( $borrower{'dateofbirth'} );
441
442     if ( $dob_dt ) {
443         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
444     }
445     else {
446         # Trigger validation
447         $borrower{'dateofbirth'} = undef;
448     }
449
450     return %borrower;
451 }
452
453 sub DelUnchangedFields {
454     my ( $borrowernumber, %new_data ) = @_;
455
456     my $current_data = GetMember( borrowernumber => $borrowernumber );
457
458     foreach my $key ( keys %new_data ) {
459         if ( $current_data->{$key} eq $new_data{$key} ) {
460             delete $new_data{$key};
461         }
462     }
463
464     return %new_data;
465 }
466
467 sub DelEmptyFields {
468     my (%borrower) = @_;
469
470     foreach my $key ( keys %borrower ) {
471         delete $borrower{$key} unless $borrower{$key};
472     }
473
474     return %borrower;
475 }
476
477 sub FilterUnchagedAttributes {
478     my ( $borrowernumber, $entered_attributes ) = @_;
479
480     my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
481
482     my $patron_attribute_types;
483     foreach my $attr (@patron_attributes) {
484         $patron_attribute_types->{ $attr->code } += 1;
485     }
486
487     my $passed_attribute_types;
488     foreach my $attr (@{ $entered_attributes }) {
489         $passed_attribute_types->{ $attr->{ code } } += 1;
490     }
491
492     my @changed_attributes;
493
494     # Loop through the current patron attributes
495     foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
496         if ( $patron_attribute_types->{ $attribute_type } !=  $passed_attribute_types->{ $attribute_type } ) {
497             # count differs, overwrite all attributes for given type
498             foreach my $attr (@{ $entered_attributes }) {
499                 push @changed_attributes, $attr
500                     if $attr->{ code } eq $attribute_type;
501             }
502         } else {
503             # count matches, check values
504             my $changes = 0;
505             foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
506                 $changes = 1
507                     unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
508                 last if $changes;
509             }
510
511             if ( $changes ) {
512                 foreach my $attr (@{ $entered_attributes }) {
513                     push @changed_attributes, $attr
514                         if $attr->{ code } eq $attribute_type;
515                 }
516             }
517         }
518     }
519
520     # Loop through passed attributes, looking for new ones
521     foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
522         if ( !defined $patron_attribute_types->{ $attribute_type } ) {
523             # YAY, new stuff
524             foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
525                 push @changed_attributes, $attr;
526             }
527         }
528     }
529
530     return \@changed_attributes;
531 }
532
533 sub GeneratePatronAttributesForm {
534     my ( $borrowernumber, $entered_attributes ) = @_;
535
536     # Get all attribute types and the values for this patron (if applicable)
537     my @types = grep { $_->opac_editable() or $_->opac_display }
538         Koha::Patron::Attribute::Types->search()->as_list();
539     if ( scalar(@types) == 0 ) {
540         return [];
541     }
542
543     my @displayable_attributes = grep { $_->opac_display }
544         Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
545
546     my %attr_values = ();
547
548     # Build the attribute values list either from the passed values
549     # or taken from the patron itself
550     if ( defined $entered_attributes ) {
551         foreach my $attr (@$entered_attributes) {
552             push @{ $attr_values{ $attr->{code} } }, $attr->{value};
553         }
554     }
555     elsif ( defined $borrowernumber ) {
556         my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
557         foreach my $attr (@editable_attributes) {
558             push @{ $attr_values{ $attr->code } }, $attr->attribute;
559         }
560     }
561
562     # Add the non-editable attributes (that don't come from the form)
563     foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
564         push @{ $attr_values{ $attr->code } }, $attr->attribute;
565     }
566
567     # Find all existing classes
568     my @classes = sort( uniq( map { $_->class } @types ) );
569     my %items_by_class;
570
571     foreach my $attr_type (@types) {
572         push @{ $items_by_class{ $attr_type->class() } }, {
573             type => $attr_type,
574             # If editable, make sure there's at least one empty entry,
575             # to make the template's job easier
576             values => $attr_values{ $attr_type->code() } || ['']
577         };
578     }
579
580     # Finally, build a list of containing classes
581     my @class_loop;
582     foreach my $class (@classes) {
583         next unless ( $items_by_class{$class} );
584
585         my $av = Koha::AuthorisedValues->search(
586             { category => 'PA_CLASS', authorised_value => $class } );
587
588         my $lib = $av->count ? $av->next->opac_description : $class;
589
590         push @class_loop,
591             {
592             class => $class,
593             items => $items_by_class{$class},
594             lib   => $lib,
595             };
596     }
597
598     return \@class_loop;
599 }
600
601 sub ParsePatronAttributes {
602     my ( $borrowernumber, $cgi ) = @_;
603
604     my @codes  = $cgi->multi_param('patron_attribute_code');
605     my @values = $cgi->multi_param('patron_attribute_value');
606
607     my $ea = each_array( @codes, @values );
608     my @attributes;
609
610     my $delete_candidates = {};
611
612     while ( my ( $code, $value ) = $ea->() ) {
613         if ( !defined($value) or $value eq '' ) {
614             $delete_candidates->{$code} = 1
615                 unless $delete_candidates->{$code};
616         }
617         else {
618             # we've got a value
619             push @attributes, { code => $code, value => $value };
620
621             # 'code' is no longer a delete candidate
622             delete $delete_candidates->{$code};
623         }
624     }
625
626     foreach my $code ( keys %{$delete_candidates} ) {
627         if (Koha::Patron::Attributes->search(
628                 { borrowernumber => $borrowernumber, code => $code }
629             )->count > 0
630             )
631         {
632             push @attributes, { code => $code, value => '' }
633                 unless any { $_->{code} eq $code } @attributes;
634         }
635     }
636
637     return \@attributes;
638 }
639
640
641 1;