Bug 13757: (QA followup) Exclude empty attributes from rendering if non-editable
[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 = FilterUnchangedAttributes( $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     # Render self-registration page
321     $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
322 }
323
324 my $captcha = random_string("CCCCC");
325
326 $template->param(
327     captcha        => $captcha,
328     captcha_digest => md5_base64($captcha)
329 );
330
331 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
332
333 sub GetHiddenFields {
334     my ( $mandatory, $action ) = @_;
335     my %hidden_fields;
336
337     my $BorrowerUnwantedField = $action eq 'modification' ?
338       C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
339       C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
340
341     my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
342     foreach (@fields) {
343         next unless m/\w/o;
344         #Don't hide mandatory fields
345         next if $mandatory->{$_};
346         $hidden_fields{$_} = 1;
347     }
348
349     return \%hidden_fields;
350 }
351
352 sub GetMandatoryFields {
353     my ($action) = @_;
354
355     my %mandatory_fields;
356
357     my $BorrowerMandatoryField =
358       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
359
360     my @fields = split( /\|/, $BorrowerMandatoryField );
361
362     foreach (@fields) {
363         $mandatory_fields{$_} = 1;
364     }
365
366     if ( $action eq 'create' || $action eq 'new' ) {
367         $mandatory_fields{'email'} = 1
368           if C4::Context->boolean_preference(
369             'PatronSelfRegistrationVerifyByEmail');
370     }
371
372     return \%mandatory_fields;
373 }
374
375 sub CheckMandatoryFields {
376     my ( $borrower, $action ) = @_;
377
378     my @empty_mandatory_fields;
379
380     my $mandatory_fields = GetMandatoryFields($action);
381     delete $mandatory_fields->{'cardnumber'};
382
383     foreach my $key ( keys %$mandatory_fields ) {
384         push( @empty_mandatory_fields, $key )
385           unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
386     }
387
388     return @empty_mandatory_fields;
389 }
390
391 sub CheckForInvalidFields {
392     my $minpw = C4::Context->preference('minPasswordLength');
393     my $borrower = shift;
394     my @invalidFields;
395     if ($borrower->{'email'}) {
396         unless ( Email::Valid->address($borrower->{'email'}) ) {
397             push(@invalidFields, "email");
398         } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
399             my $patrons_with_same_email = Koha::Patrons->search( { email => $borrower->{email} })->count;
400             if ( $patrons_with_same_email ) {
401                 push @invalidFields, "duplicate_email";
402             }
403         }
404     }
405     if ($borrower->{'emailpro'}) {
406         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
407     }
408     if ($borrower->{'B_email'}) {
409         push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
410     }
411     if ( defined $borrower->{'password'}
412         and $borrower->{'password'} ne $borrower->{'password2'} )
413     {
414         push( @invalidFields, "password_match" );
415     }
416     if ( $borrower->{'password'}  && $minpw && (length($borrower->{'password'}) < $minpw) ) {
417        push(@invalidFields, "password_invalid");
418     }
419     if ( $borrower->{'password'} ) {
420        push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
421     }
422
423     return \@invalidFields;
424 }
425
426 sub ParseCgiForBorrower {
427     my ($cgi) = @_;
428
429     my $scrubber = C4::Scrubber->new();
430     my %borrower;
431
432     foreach ( $cgi->param ) {
433         if ( $_ =~ '^borrower_' ) {
434             my ($key) = substr( $_, 9 );
435             $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
436         }
437     }
438
439     my $dob_dt;
440     $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
441         if ( $borrower{'dateofbirth'} );
442
443     if ( $dob_dt ) {
444         $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
445     }
446     else {
447         # Trigger validation
448         $borrower{'dateofbirth'} = undef;
449     }
450
451     return %borrower;
452 }
453
454 sub DelUnchangedFields {
455     my ( $borrowernumber, %new_data ) = @_;
456
457     my $current_data = GetMember( borrowernumber => $borrowernumber );
458
459     foreach my $key ( keys %new_data ) {
460         if ( $current_data->{$key} eq $new_data{$key} ) {
461             delete $new_data{$key};
462         }
463     }
464
465     return %new_data;
466 }
467
468 sub DelEmptyFields {
469     my (%borrower) = @_;
470
471     foreach my $key ( keys %borrower ) {
472         delete $borrower{$key} unless $borrower{$key};
473     }
474
475     return %borrower;
476 }
477
478 sub FilterUnchangedAttributes {
479     my ( $borrowernumber, $entered_attributes ) = @_;
480
481     my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
482
483     my $patron_attribute_types;
484     foreach my $attr (@patron_attributes) {
485         $patron_attribute_types->{ $attr->code } += 1;
486     }
487
488     my $passed_attribute_types;
489     foreach my $attr (@{ $entered_attributes }) {
490         $passed_attribute_types->{ $attr->{ code } } += 1;
491     }
492
493     my @changed_attributes;
494
495     # Loop through the current patron attributes
496     foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
497         if ( $patron_attribute_types->{ $attribute_type } !=  $passed_attribute_types->{ $attribute_type } ) {
498             # count differs, overwrite all attributes for given type
499             foreach my $attr (@{ $entered_attributes }) {
500                 push @changed_attributes, $attr
501                     if $attr->{ code } eq $attribute_type;
502             }
503         } else {
504             # count matches, check values
505             my $changes = 0;
506             foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
507                 $changes = 1
508                     unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
509                 last if $changes;
510             }
511
512             if ( $changes ) {
513                 foreach my $attr (@{ $entered_attributes }) {
514                     push @changed_attributes, $attr
515                         if $attr->{ code } eq $attribute_type;
516                 }
517             }
518         }
519     }
520
521     # Loop through passed attributes, looking for new ones
522     foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
523         if ( !defined $patron_attribute_types->{ $attribute_type } ) {
524             # YAY, new stuff
525             foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
526                 push @changed_attributes, $attr;
527             }
528         }
529     }
530
531     return \@changed_attributes;
532 }
533
534 sub GeneratePatronAttributesForm {
535     my ( $borrowernumber, $entered_attributes ) = @_;
536
537     # Get all attribute types and the values for this patron (if applicable)
538     my @types = grep { $_->opac_editable() or $_->opac_display }
539         Koha::Patron::Attribute::Types->search()->as_list();
540     if ( scalar(@types) == 0 ) {
541         return [];
542     }
543
544     my @displayable_attributes = grep { $_->opac_display }
545         Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
546
547     my %attr_values = ();
548
549     # Build the attribute values list either from the passed values
550     # or taken from the patron itself
551     if ( defined $entered_attributes ) {
552         foreach my $attr (@$entered_attributes) {
553             push @{ $attr_values{ $attr->{code} } }, $attr->{value};
554         }
555     }
556     elsif ( defined $borrowernumber ) {
557         my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
558         foreach my $attr (@editable_attributes) {
559             push @{ $attr_values{ $attr->code } }, $attr->attribute;
560         }
561     }
562
563     # Add the non-editable attributes (that don't come from the form)
564     foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
565         push @{ $attr_values{ $attr->code } }, $attr->attribute;
566     }
567
568     # Find all existing classes
569     my @classes = sort( uniq( map { $_->class } @types ) );
570     my %items_by_class;
571
572     foreach my $attr_type (@types) {
573         push @{ $items_by_class{ $attr_type->class() } }, {
574             type => $attr_type,
575             # If editable, make sure there's at least one empty entry,
576             # to make the template's job easier
577             values => $attr_values{ $attr_type->code() } || ['']
578         }
579             unless !defined $attr_values{ $attr_type->code() }
580                     and !$attr_type->opac_editable;
581     }
582
583     # Finally, build a list of containing classes
584     my @class_loop;
585     foreach my $class (@classes) {
586         next unless ( $items_by_class{$class} );
587
588         my $av = Koha::AuthorisedValues->search(
589             { category => 'PA_CLASS', authorised_value => $class } );
590
591         my $lib = $av->count ? $av->next->opac_description : $class;
592
593         push @class_loop,
594             {
595             class => $class,
596             items => $items_by_class{$class},
597             lib   => $lib,
598             };
599     }
600
601     return \@class_loop;
602 }
603
604 sub ParsePatronAttributes {
605     my ( $borrowernumber, $cgi ) = @_;
606
607     my @codes  = $cgi->multi_param('patron_attribute_code');
608     my @values = $cgi->multi_param('patron_attribute_value');
609
610     my $ea = each_array( @codes, @values );
611     my @attributes;
612
613     my $delete_candidates = {};
614
615     while ( my ( $code, $value ) = $ea->() ) {
616         if ( !defined($value) or $value eq '' ) {
617             $delete_candidates->{$code} = 1
618                 unless $delete_candidates->{$code};
619         }
620         else {
621             # we've got a value
622             push @attributes, { code => $code, value => $value };
623
624             # 'code' is no longer a delete candidate
625             delete $delete_candidates->{$code};
626         }
627     }
628
629     foreach my $code ( keys %{$delete_candidates} ) {
630         if (Koha::Patron::Attributes->search(
631                 { borrowernumber => $borrowernumber, code => $code }
632             )->count > 0
633             )
634         {
635             push @attributes, { code => $code, value => '' }
636                 unless any { $_->{code} eq $code } @attributes;
637         }
638     }
639
640     return \@attributes;
641 }
642
643
644 1;