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