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>.
21 use Digest::MD5 qw( md5_base64 md5_hex );
23 use List::MoreUtils qw( any each_array uniq );
24 use String::Random qw( random_string );
29 use C4::Members::Attributes qw( GetBorrowerAttributes );
30 use C4::Form::MessagingPreferences;
33 use Koha::Patron::Modification;
34 use Koha::Patron::Modifications;
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;
48 my $dbh = C4::Context->dbh;
50 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
52 template_name => "opac-memberentry.tt",
59 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
61 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
65 my $action = $cgi->param('action') || q{};
66 if ( $action eq q{} ) {
67 if ($borrowernumber) {
75 my $mandatory = GetMandatoryFields($action);
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;
81 my ( $min, $max ) = C4::Members::get_cardnumber_length();
84 minlength_cardnumber => $min,
85 maxlength_cardnumber => $max
91 hidden => GetHiddenFields( $mandatory, 'registration' ),
92 mandatory => $mandatory,
93 libraries => \@libraries,
94 OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
97 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
98 my $conflicting_attribute = 0;
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});
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()
108 $conflicting_attribute = 1;
112 if ( $action eq 'create' ) {
114 my %borrower = ParseCgiForBorrower($cgi);
116 %borrower = DelEmptyFields(%borrower);
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} );
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 );
136 empty_mandatory_fields => \@empty_mandatory_fields,
137 invalid_form_fields => $invalidformfields,
138 borrower => \%borrower
140 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
143 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
147 borrower => \%borrower
149 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
153 C4::Context->boolean_preference(
154 'PatronSelfRegistrationVerifyByEmail')
157 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
159 template_name => "opac-registration-email-sent.tt",
162 authnotrequired => 1,
165 $template->param( 'email' => $borrower{'email'} );
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().{}.$$ );
172 $borrower{password} = Koha::AuthUtils::generate_password unless $borrower{password};
173 $borrower{verification_token} = $verification_token;
175 Koha::Patron::Modification->new( \%borrower )->store();
177 #Send verification email
178 my $letter = C4::Letters::GetPreparedLetter(
180 letter_code => 'OPAC_REG_VERIFY',
181 lang => 'default', # Patron does not have a preferred language defined yet
183 borrower_modifications => $verification_token,
187 C4::Letters::EnqueueLetter(
190 message_transport_type => 'email',
191 to_address => $borrower{'email'},
193 C4::Context->preference('KohaAdminEmailAddress'),
198 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
200 template_name => "opac-registration-confirmation.tt",
203 authnotrequired => 1,
207 $template->param( OpacPasswordChange =>
208 C4::Context->preference('OpacPasswordChange') );
210 my $patron = Koha::Patron->new( \%borrower )->store;
212 C4::Members::Attributes::SetBorrowerAttributes( $patron->borrowernumber, $attributes );
213 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
214 C4::Form::MessagingPreferences::handle_form_action(
216 { borrowernumber => $patron->borrowernumber },
219 C4::Context->preference('PatronSelfRegistrationDefaultCategory')
223 $template->param( password_cleartext => $password );
224 $template->param( borrower => $patron->unblessed );
226 # FIXME Handle possible errors here
229 PatronSelfRegistrationAdditionalInstructions =>
230 C4::Context->preference(
231 'PatronSelfRegistrationAdditionalInstructions')
236 elsif ( $action eq 'update' ) {
238 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
239 die "Wrong CSRF token"
240 unless Koha::Token->new->check_csrf({
241 session_id => scalar $cgi->cookie('CGISESSID'),
242 token => scalar $cgi->param('csrf_token'),
245 my %borrower = ParseCgiForBorrower($cgi);
246 $borrower{borrowernumber} = $borrowernumber;
248 my %borrower_changes = DelEmptyFields(%borrower);
249 my @empty_mandatory_fields =
250 CheckMandatoryFields( \%borrower_changes, $action );
251 my $invalidformfields = CheckForInvalidFields(\%borrower);
253 # Send back the data to the template
254 %borrower = ( %$borrower, %borrower );
256 if (@empty_mandatory_fields || @$invalidformfields) {
258 empty_mandatory_fields => \@empty_mandatory_fields,
259 invalid_form_fields => $invalidformfields,
260 borrower => \%borrower,
261 csrf_token => Koha::Token->new->generate_csrf({
262 session_id => scalar $cgi->cookie('CGISESSID'),
265 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
267 $template->param( action => 'edit' );
270 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
271 my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
273 if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
274 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
276 template_name => "opac-memberentry-update-submitted.tt",
279 authnotrequired => 1,
283 $borrower_changes{borrowernumber} = $borrowernumber;
284 $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
286 Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
288 my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
290 my $patron = Koha::Patrons->find( $borrowernumber );
291 $template->param( borrower => $patron->unblessed );
294 my $patron = Koha::Patrons->find( $borrowernumber );
298 borrower => $patron->unblessed,
299 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
300 csrf_token => Koha::Token->new->generate_csrf({
301 session_id => scalar $cgi->cookie('CGISESSID'),
307 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
308 my $patron = Koha::Patrons->find( $borrowernumber );
309 my $borrower = $patron->unblessed;
312 borrower => $borrower,
313 guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
314 hidden => GetHiddenFields( $mandatory, 'modification' ),
315 csrf_token => Koha::Token->new->generate_csrf({
316 session_id => scalar $cgi->cookie('CGISESSID'),
320 if (C4::Context->preference('OPACpatronimages')) {
321 $template->param( display_patron_image => 1 ) if $patron->image;
324 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
326 # Render self-registration page
327 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
330 my $captcha = random_string("CCCCC");
334 captcha_digest => md5_base64($captcha)
337 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
339 sub GetHiddenFields {
340 my ( $mandatory, $action ) = @_;
343 my $BorrowerUnwantedField = $action eq 'modification' ?
344 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
345 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
347 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
350 #Don't hide mandatory fields
351 next if $mandatory->{$_};
352 $hidden_fields{$_} = 1;
355 return \%hidden_fields;
358 sub GetMandatoryFields {
361 my %mandatory_fields;
363 my $BorrowerMandatoryField =
364 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
366 my @fields = split( /\|/, $BorrowerMandatoryField );
369 $mandatory_fields{$_} = 1;
372 if ( $action eq 'create' || $action eq 'new' ) {
373 $mandatory_fields{'email'} = 1
374 if C4::Context->boolean_preference(
375 'PatronSelfRegistrationVerifyByEmail');
378 return \%mandatory_fields;
381 sub CheckMandatoryFields {
382 my ( $borrower, $action ) = @_;
384 my @empty_mandatory_fields;
386 my $mandatory_fields = GetMandatoryFields($action);
387 delete $mandatory_fields->{'cardnumber'};
389 foreach my $key ( keys %$mandatory_fields ) {
390 push( @empty_mandatory_fields, $key )
391 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
394 return @empty_mandatory_fields;
397 sub CheckForInvalidFields {
398 my $borrower = shift;
400 if ($borrower->{'email'}) {
401 unless ( Email::Valid->address($borrower->{'email'}) ) {
402 push(@invalidFields, "email");
403 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
404 my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
406 email => $borrower->{email},
408 exists $borrower->{borrowernumber}
409 ? ( borrowernumber =>
410 { '!=' => $borrower->{borrowernumber} } )
415 if ( $patrons_with_same_email ) {
416 push @invalidFields, "duplicate_email";
420 if ($borrower->{'emailpro'}) {
421 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
423 if ($borrower->{'B_email'}) {
424 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
426 if ( defined $borrower->{'password'}
427 and $borrower->{'password'} ne $borrower->{'password2'} )
429 push( @invalidFields, "password_match" );
431 if ( $borrower->{'password'} ) {
432 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
433 unless ( $is_valid ) {
434 push @invalidFields, 'password_too_short' if $error eq 'too_short';
435 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
436 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
440 return \@invalidFields;
443 sub ParseCgiForBorrower {
446 my $scrubber = C4::Scrubber->new();
449 foreach my $field ( $cgi->param ) {
450 if ( $field =~ '^borrower_' ) {
451 my ($key) = substr( $field, 9 );
452 if ( $field !~ '^borrower_password' ) {
453 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
455 # Allow html characters for passwords
456 $borrower{$key} = $cgi->param($field);
462 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
463 if ( $borrower{'dateofbirth'} );
466 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
470 $borrower{'dateofbirth'} = undef;
476 sub DelUnchangedFields {
477 my ( $borrowernumber, %new_data ) = @_;
479 my $patron = Koha::Patrons->find( $borrowernumber );
480 my $current_data = $patron->unblessed;
482 foreach my $key ( keys %new_data ) {
483 if ( $current_data->{$key} eq $new_data{$key} ) {
484 delete $new_data{$key};
494 foreach my $key ( keys %borrower ) {
495 delete $borrower{$key} unless $borrower{$key};
501 sub FilterUnchangedAttributes {
502 my ( $borrowernumber, $entered_attributes ) = @_;
504 my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
506 my $patron_attribute_types;
507 foreach my $attr (@patron_attributes) {
508 $patron_attribute_types->{ $attr->code } += 1;
511 my $passed_attribute_types;
512 foreach my $attr (@{ $entered_attributes }) {
513 $passed_attribute_types->{ $attr->{ code } } += 1;
516 my @changed_attributes;
518 # Loop through the current patron attributes
519 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
520 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
521 # count differs, overwrite all attributes for given type
522 foreach my $attr (@{ $entered_attributes }) {
523 push @changed_attributes, $attr
524 if $attr->{ code } eq $attribute_type;
527 # count matches, check values
529 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
531 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
536 foreach my $attr (@{ $entered_attributes }) {
537 push @changed_attributes, $attr
538 if $attr->{ code } eq $attribute_type;
544 # Loop through passed attributes, looking for new ones
545 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
546 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
548 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
549 push @changed_attributes, $attr;
554 return \@changed_attributes;
557 sub GeneratePatronAttributesForm {
558 my ( $borrowernumber, $entered_attributes ) = @_;
560 # Get all attribute types and the values for this patron (if applicable)
561 my @types = grep { $_->opac_editable() or $_->opac_display }
562 Koha::Patron::Attribute::Types->search()->as_list();
563 if ( scalar(@types) == 0 ) {
567 my @displayable_attributes = grep { $_->opac_display }
568 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
570 my %attr_values = ();
572 # Build the attribute values list either from the passed values
573 # or taken from the patron itself
574 if ( defined $entered_attributes ) {
575 foreach my $attr (@$entered_attributes) {
576 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
579 elsif ( defined $borrowernumber ) {
580 my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
581 foreach my $attr (@editable_attributes) {
582 push @{ $attr_values{ $attr->code } }, $attr->attribute;
586 # Add the non-editable attributes (that don't come from the form)
587 foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
588 push @{ $attr_values{ $attr->code } }, $attr->attribute;
591 # Find all existing classes
592 my @classes = sort( uniq( map { $_->class } @types ) );
595 foreach my $attr_type (@types) {
596 push @{ $items_by_class{ $attr_type->class() } }, {
598 # If editable, make sure there's at least one empty entry,
599 # to make the template's job easier
600 values => $attr_values{ $attr_type->code() } || ['']
602 unless !defined $attr_values{ $attr_type->code() }
603 and !$attr_type->opac_editable;
606 # Finally, build a list of containing classes
608 foreach my $class (@classes) {
609 next unless ( $items_by_class{$class} );
611 my $av = Koha::AuthorisedValues->search(
612 { category => 'PA_CLASS', authorised_value => $class } );
614 my $lib = $av->count ? $av->next->opac_description : $class;
619 items => $items_by_class{$class},
627 sub ParsePatronAttributes {
628 my ( $borrowernumber, $cgi ) = @_;
630 my @codes = $cgi->multi_param('patron_attribute_code');
631 my @values = $cgi->multi_param('patron_attribute_value');
633 my @editable_attribute_types
634 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
636 my $ea = each_array( @codes, @values );
639 my $delete_candidates = {};
641 while ( my ( $code, $value ) = $ea->() ) {
642 if ( any { $_ eq $code } @editable_attribute_types ) {
643 # It is an editable attribute
644 if ( !defined($value) or $value eq '' ) {
645 $delete_candidates->{$code} = 1
646 unless $delete_candidates->{$code};
650 push @attributes, { code => $code, value => $value };
652 # 'code' is no longer a delete candidate
653 delete $delete_candidates->{$code}
654 if defined $delete_candidates->{$code};
659 foreach my $code ( keys %{$delete_candidates} ) {
660 if ( Koha::Patron::Attributes->search({
661 borrowernumber => $borrowernumber, code => $code })->count > 0 )
663 push @attributes, { code => $code, value => '' }
664 unless any { $_->{code} eq $code } @attributes;