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