Bug 20042: 00-load.t fails when Elasticsearch is not installed
[koha.git] / opac / opac-memberentry.pl
blob76fe04684a4c022e49f8928dba47ab47cea22cad
1 #!/usr/bin/perl
3 # This file is part of Koha.
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.
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.
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>.
18 use Modern::Perl;
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 );
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;
43 my $cgi = new CGI;
44 my $dbh = C4::Context->dbh;
46 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
48 template_name => "opac-memberentry.tt",
49 type => "opac",
50 query => $cgi,
51 authnotrequired => 1,
55 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
57 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
58 exit;
61 my $action = $cgi->param('action') || q{};
62 if ( $action eq q{} ) {
63 if ($borrowernumber) {
64 $action = 'edit';
66 else {
67 $action = 'new';
71 my $mandatory = GetMandatoryFields($action);
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;
77 my ( $min, $max ) = C4::Members::get_cardnumber_length();
78 if ( defined $min ) {
79 $template->param(
80 minlength_cardnumber => $min,
81 maxlength_cardnumber => $max
85 $template->param(
86 action => $action,
87 hidden => GetHiddenFields( $mandatory, 'registration' ),
88 mandatory => $mandatory,
89 libraries => \@libraries,
90 OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
93 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
94 my $conflicting_attribute = 0;
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()
104 $conflicting_attribute = 1;
108 if ( $action eq 'create' ) {
110 my %borrower = ParseCgiForBorrower($cgi);
112 %borrower = DelEmptyFields(%borrower);
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} );
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 );
131 $template->param(
132 empty_mandatory_fields => \@empty_mandatory_fields,
133 invalid_form_fields => $invalidformfields,
134 borrower => \%borrower
136 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
138 elsif (
139 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
141 $template->param(
142 failed_captcha => 1,
143 borrower => \%borrower
145 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
147 else {
148 if (
149 C4::Context->boolean_preference(
150 'PatronSelfRegistrationVerifyByEmail')
153 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
155 template_name => "opac-registration-email-sent.tt",
156 type => "opac",
157 query => $cgi,
158 authnotrequired => 1,
161 $template->param( 'email' => $borrower{'email'} );
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().{}.$$ );
168 $borrower{password} = random_string("..........");
169 $borrower{verification_token} = $verification_token;
171 Koha::Patron::Modification->new( \%borrower )->store();
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,
183 C4::Letters::EnqueueLetter(
185 letter => $letter,
186 message_transport_type => 'email',
187 to_address => $borrower{'email'},
188 from_address =>
189 C4::Context->preference('KohaAdminEmailAddress'),
193 else {
194 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
196 template_name => "opac-registration-confirmation.tt",
197 type => "opac",
198 query => $cgi,
199 authnotrequired => 1,
203 $template->param( OpacPasswordChange =>
204 C4::Context->preference('OpacPasswordChange') );
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');
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')
221 elsif ( $action eq 'update' ) {
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'),
230 my %borrower = ParseCgiForBorrower($cgi);
231 $borrower{borrowernumber} = $borrowernumber;
233 my %borrower_changes = DelEmptyFields(%borrower);
234 my @empty_mandatory_fields =
235 CheckMandatoryFields( \%borrower_changes, $action );
236 my $invalidformfields = CheckForInvalidFields(\%borrower);
238 # Send back the data to the template
239 %borrower = ( %$borrower, %borrower );
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 session_id => scalar $cgi->cookie('CGISESSID'),
250 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
252 $template->param( action => 'edit' );
254 else {
255 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
256 my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
258 if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
259 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
261 template_name => "opac-memberentry-update-submitted.tt",
262 type => "opac",
263 query => $cgi,
264 authnotrequired => 1,
268 $borrower_changes{borrowernumber} = $borrowernumber;
269 $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
271 # FIXME update the following with
272 # Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
273 # when bug 17091 will be pushed
274 my $patron_modifications = Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber });
275 while ( my $patron_modification = $patron_modifications->next ) {
276 $patron_modification->delete;
279 my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
281 $template->param(
282 borrower => GetMember( borrowernumber => $borrowernumber ),
285 else {
286 $template->param(
287 action => 'edit',
288 nochanges => 1,
289 borrower => GetMember( borrowernumber => $borrowernumber ),
290 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
291 csrf_token => Koha::Token->new->generate_csrf({
292 session_id => scalar $cgi->cookie('CGISESSID'),
298 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
299 my $borrower = GetMember( borrowernumber => $borrowernumber );
301 $template->param(
302 borrower => $borrower,
303 guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
304 hidden => GetHiddenFields( $mandatory, 'modification' ),
305 csrf_token => Koha::Token->new->generate_csrf({
306 session_id => scalar $cgi->cookie('CGISESSID'),
310 if (C4::Context->preference('OPACpatronimages')) {
311 my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
312 $template->param( display_patron_image => 1 ) if $patron_image;
315 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
316 } else {
317 # Render self-registration page
318 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
321 my $captcha = random_string("CCCCC");
323 $template->param(
324 captcha => $captcha,
325 captcha_digest => md5_base64($captcha)
328 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
330 sub GetHiddenFields {
331 my ( $mandatory, $action ) = @_;
332 my %hidden_fields;
334 my $BorrowerUnwantedField = $action eq 'modification' ?
335 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
336 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
338 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
339 foreach (@fields) {
340 next unless m/\w/o;
341 #Don't hide mandatory fields
342 next if $mandatory->{$_};
343 $hidden_fields{$_} = 1;
346 return \%hidden_fields;
349 sub GetMandatoryFields {
350 my ($action) = @_;
352 my %mandatory_fields;
354 my $BorrowerMandatoryField =
355 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
357 my @fields = split( /\|/, $BorrowerMandatoryField );
359 foreach (@fields) {
360 $mandatory_fields{$_} = 1;
363 if ( $action eq 'create' || $action eq 'new' ) {
364 $mandatory_fields{'email'} = 1
365 if C4::Context->boolean_preference(
366 'PatronSelfRegistrationVerifyByEmail');
369 return \%mandatory_fields;
372 sub CheckMandatoryFields {
373 my ( $borrower, $action ) = @_;
375 my @empty_mandatory_fields;
377 my $mandatory_fields = GetMandatoryFields($action);
378 delete $mandatory_fields->{'cardnumber'};
380 foreach my $key ( keys %$mandatory_fields ) {
381 push( @empty_mandatory_fields, $key )
382 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
385 return @empty_mandatory_fields;
388 sub CheckForInvalidFields {
389 my $minpw = C4::Context->preference('minPasswordLength');
390 my $borrower = shift;
391 my @invalidFields;
392 if ($borrower->{'email'}) {
393 unless ( Email::Valid->address($borrower->{'email'}) ) {
394 push(@invalidFields, "email");
395 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
396 my $patrons_with_same_email = Koha::Patrons->search(
398 email => $borrower->{email},
400 exists $borrower->{borrowernumber}
401 ? ( borrowernumber =>
402 { '!=' => $borrower->{borrowernumber} } )
403 : ()
406 )->count;
407 if ( $patrons_with_same_email ) {
408 push @invalidFields, "duplicate_email";
412 if ($borrower->{'emailpro'}) {
413 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
415 if ($borrower->{'B_email'}) {
416 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
418 if ( defined $borrower->{'password'}
419 and $borrower->{'password'} ne $borrower->{'password2'} )
421 push( @invalidFields, "password_match" );
423 if ( $borrower->{'password'} && $minpw && (length($borrower->{'password'}) < $minpw) ) {
424 push(@invalidFields, "password_invalid");
426 if ( $borrower->{'password'} ) {
427 push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
430 return \@invalidFields;
433 sub ParseCgiForBorrower {
434 my ($cgi) = @_;
436 my $scrubber = C4::Scrubber->new();
437 my %borrower;
439 foreach my $field ( $cgi->param ) {
440 if ( $field =~ '^borrower_' ) {
441 my ($key) = substr( $field, 9 );
442 if ( $field !~ '^borrower_password' ) {
443 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
444 } else {
445 # Allow html characters for passwords
446 $borrower{$key} = $cgi->param($field);
451 my $dob_dt;
452 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
453 if ( $borrower{'dateofbirth'} );
455 if ( $dob_dt ) {
456 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
458 else {
459 # Trigger validation
460 $borrower{'dateofbirth'} = undef;
463 return %borrower;
466 sub DelUnchangedFields {
467 my ( $borrowernumber, %new_data ) = @_;
469 my $current_data = GetMember( borrowernumber => $borrowernumber );
471 foreach my $key ( keys %new_data ) {
472 if ( $current_data->{$key} eq $new_data{$key} ) {
473 delete $new_data{$key};
477 return %new_data;
480 sub DelEmptyFields {
481 my (%borrower) = @_;
483 foreach my $key ( keys %borrower ) {
484 delete $borrower{$key} unless $borrower{$key};
487 return %borrower;
490 sub FilterUnchangedAttributes {
491 my ( $borrowernumber, $entered_attributes ) = @_;
493 my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
495 my $patron_attribute_types;
496 foreach my $attr (@patron_attributes) {
497 $patron_attribute_types->{ $attr->code } += 1;
500 my $passed_attribute_types;
501 foreach my $attr (@{ $entered_attributes }) {
502 $passed_attribute_types->{ $attr->{ code } } += 1;
505 my @changed_attributes;
507 # Loop through the current patron attributes
508 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
509 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
510 # count differs, overwrite all attributes for given type
511 foreach my $attr (@{ $entered_attributes }) {
512 push @changed_attributes, $attr
513 if $attr->{ code } eq $attribute_type;
515 } else {
516 # count matches, check values
517 my $changes = 0;
518 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
519 $changes = 1
520 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
521 last if $changes;
524 if ( $changes ) {
525 foreach my $attr (@{ $entered_attributes }) {
526 push @changed_attributes, $attr
527 if $attr->{ code } eq $attribute_type;
533 # Loop through passed attributes, looking for new ones
534 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
535 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
536 # YAY, new stuff
537 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
538 push @changed_attributes, $attr;
543 return \@changed_attributes;
546 sub GeneratePatronAttributesForm {
547 my ( $borrowernumber, $entered_attributes ) = @_;
549 # Get all attribute types and the values for this patron (if applicable)
550 my @types = grep { $_->opac_editable() or $_->opac_display }
551 Koha::Patron::Attribute::Types->search()->as_list();
552 if ( scalar(@types) == 0 ) {
553 return [];
556 my @displayable_attributes = grep { $_->opac_display }
557 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
559 my %attr_values = ();
561 # Build the attribute values list either from the passed values
562 # or taken from the patron itself
563 if ( defined $entered_attributes ) {
564 foreach my $attr (@$entered_attributes) {
565 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
568 elsif ( defined $borrowernumber ) {
569 my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
570 foreach my $attr (@editable_attributes) {
571 push @{ $attr_values{ $attr->code } }, $attr->attribute;
575 # Add the non-editable attributes (that don't come from the form)
576 foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
577 push @{ $attr_values{ $attr->code } }, $attr->attribute;
580 # Find all existing classes
581 my @classes = sort( uniq( map { $_->class } @types ) );
582 my %items_by_class;
584 foreach my $attr_type (@types) {
585 push @{ $items_by_class{ $attr_type->class() } }, {
586 type => $attr_type,
587 # If editable, make sure there's at least one empty entry,
588 # to make the template's job easier
589 values => $attr_values{ $attr_type->code() } || ['']
591 unless !defined $attr_values{ $attr_type->code() }
592 and !$attr_type->opac_editable;
595 # Finally, build a list of containing classes
596 my @class_loop;
597 foreach my $class (@classes) {
598 next unless ( $items_by_class{$class} );
600 my $av = Koha::AuthorisedValues->search(
601 { category => 'PA_CLASS', authorised_value => $class } );
603 my $lib = $av->count ? $av->next->opac_description : $class;
605 push @class_loop,
607 class => $class,
608 items => $items_by_class{$class},
609 lib => $lib,
613 return \@class_loop;
616 sub ParsePatronAttributes {
617 my ( $borrowernumber, $cgi ) = @_;
619 my @codes = $cgi->multi_param('patron_attribute_code');
620 my @values = $cgi->multi_param('patron_attribute_value');
622 my @editable_attribute_types
623 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
625 my $ea = each_array( @codes, @values );
626 my @attributes;
628 my $delete_candidates = {};
630 while ( my ( $code, $value ) = $ea->() ) {
631 if ( any { $_ eq $code } @editable_attribute_types ) {
632 # It is an editable attribute
633 if ( !defined($value) or $value eq '' ) {
634 $delete_candidates->{$code} = 1
635 unless $delete_candidates->{$code};
637 else {
638 # we've got a value
639 push @attributes, { code => $code, value => $value };
641 # 'code' is no longer a delete candidate
642 delete $delete_candidates->{$code}
643 if defined $delete_candidates->{$code};
648 foreach my $code ( keys %{$delete_candidates} ) {
649 if ( Koha::Patron::Attributes->search({
650 borrowernumber => $borrowernumber, code => $code })->count > 0 )
652 push @attributes, { code => $code, value => '' }
653 unless any { $_->{code} eq $code } @attributes;
657 return \@attributes;