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 );
22 use Encode qw( encode );
24 use List::MoreUtils qw( any each_array uniq );
25 use String::Random qw( random_string );
30 use C4::Members::Attributes qw( GetBorrowerAttributes );
31 use C4::Form::MessagingPreferences;
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;
45 my $dbh = C4::Context->dbh;
47 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
49 template_name => "opac-memberentry.tt",
56 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
58 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
62 my $action = $cgi->param('action') || q{};
63 if ( $action eq q{} ) {
64 if ($borrowernumber) {
72 my $mandatory = GetMandatoryFields($action);
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;
78 my ( $min, $max ) = C4::Members::get_cardnumber_length();
81 minlength_cardnumber => $min,
82 maxlength_cardnumber => $max
88 hidden => GetHiddenFields( $mandatory, 'registration' ),
89 mandatory => $mandatory,
90 libraries => \@libraries,
91 OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
94 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
95 my $conflicting_attribute = 0;
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});
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()
105 $conflicting_attribute = 1;
109 if ( $action eq 'create' ) {
111 my %borrower = ParseCgiForBorrower($cgi);
113 %borrower = DelEmptyFields(%borrower);
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} );
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 );
133 empty_mandatory_fields => \@empty_mandatory_fields,
134 invalid_form_fields => $invalidformfields,
135 borrower => \%borrower
137 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
140 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
144 borrower => \%borrower
146 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
150 C4::Context->boolean_preference(
151 'PatronSelfRegistrationVerifyByEmail')
154 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
156 template_name => "opac-registration-email-sent.tt",
159 authnotrequired => 1,
162 $template->param( 'email' => $borrower{'email'} );
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().{}.$$ );
169 $borrower{password} = random_string("..........");
170 $borrower{verification_token} = $verification_token;
172 Koha::Patron::Modification->new( \%borrower )->store();
174 #Send verification email
175 my $letter = C4::Letters::GetPreparedLetter(
177 letter_code => 'OPAC_REG_VERIFY',
179 borrower_modifications => $verification_token,
183 C4::Letters::EnqueueLetter(
186 message_transport_type => 'email',
187 to_address => $borrower{'email'},
189 C4::Context->preference('KohaAdminEmailAddress'),
194 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
196 template_name => "opac-registration-confirmation.tt",
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 );
212 borrower => GetMember( borrowernumber => $borrowernumber ) );
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 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'),
231 my %borrower = ParseCgiForBorrower($cgi);
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) {
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') ) ),
251 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
253 $template->param( action => 'edit' );
256 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
257 my $extended_attributes_changes = FilterUnchagedAttributes( $borrowernumber, $attributes );
259 if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
260 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
262 template_name => "opac-memberentry-update-submitted.tt",
265 authnotrequired => 1,
269 $borrower_changes{borrowernumber} = $borrowernumber;
270 $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
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;
280 my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
283 borrower => GetMember( borrowernumber => $borrowernumber ),
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') ) ),
300 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
301 my $borrower = GetMember( borrowernumber => $borrowernumber );
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') ) ),
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;
318 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
320 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
323 my $captcha = random_string("CCCCC");
327 captcha_digest => md5_base64($captcha)
330 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
332 sub GetHiddenFields {
333 my ( $mandatory, $action ) = @_;
336 my $BorrowerUnwantedField = $action eq 'modification' ?
337 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
338 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
340 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
343 #Don't hide mandatory fields
344 next if $mandatory->{$_};
345 $hidden_fields{$_} = 1;
348 return \%hidden_fields;
351 sub GetMandatoryFields {
354 my %mandatory_fields;
356 my $BorrowerMandatoryField =
357 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
359 my @fields = split( /\|/, $BorrowerMandatoryField );
362 $mandatory_fields{$_} = 1;
365 if ( $action eq 'create' || $action eq 'new' ) {
366 $mandatory_fields{'email'} = 1
367 if C4::Context->boolean_preference(
368 'PatronSelfRegistrationVerifyByEmail');
371 return \%mandatory_fields;
374 sub CheckMandatoryFields {
375 my ( $borrower, $action ) = @_;
377 my @empty_mandatory_fields;
379 my $mandatory_fields = GetMandatoryFields($action);
380 delete $mandatory_fields->{'cardnumber'};
382 foreach my $key ( keys %$mandatory_fields ) {
383 push( @empty_mandatory_fields, $key )
384 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
387 return @empty_mandatory_fields;
390 sub CheckForInvalidFields {
391 my $minpw = C4::Context->preference('minPasswordLength');
392 my $borrower = shift;
394 if ($borrower->{'email'}) {
395 unless ( Email::Valid->address($borrower->{'email'}) ) {
396 push(@invalidFields, "email");
397 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
398 my $patrons_with_same_email = Koha::Patrons->search( { email => $borrower->{email} })->count;
399 if ( $patrons_with_same_email ) {
400 push @invalidFields, "duplicate_email";
404 if ($borrower->{'emailpro'}) {
405 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
407 if ($borrower->{'B_email'}) {
408 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
410 if ( defined $borrower->{'password'}
411 and $borrower->{'password'} ne $borrower->{'password2'} )
413 push( @invalidFields, "password_match" );
415 if ( $borrower->{'password'} && $minpw && (length($borrower->{'password'}) < $minpw) ) {
416 push(@invalidFields, "password_invalid");
418 if ( $borrower->{'password'} ) {
419 push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
422 return \@invalidFields;
425 sub ParseCgiForBorrower {
428 my $scrubber = C4::Scrubber->new();
431 foreach ( $cgi->param ) {
432 if ( $_ =~ '^borrower_' ) {
433 my ($key) = substr( $_, 9 );
434 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
439 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
440 if ( $borrower{'dateofbirth'} );
443 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
447 $borrower{'dateofbirth'} = undef;
453 sub DelUnchangedFields {
454 my ( $borrowernumber, %new_data ) = @_;
456 my $current_data = GetMember( borrowernumber => $borrowernumber );
458 foreach my $key ( keys %new_data ) {
459 if ( $current_data->{$key} eq $new_data{$key} ) {
460 delete $new_data{$key};
470 foreach my $key ( keys %borrower ) {
471 delete $borrower{$key} unless $borrower{$key};
477 sub FilterUnchagedAttributes {
478 my ( $borrowernumber, $entered_attributes ) = @_;
480 my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
482 my $patron_attribute_types;
483 foreach my $attr (@patron_attributes) {
484 $patron_attribute_types->{ $attr->code } += 1;
487 my $passed_attribute_types;
488 foreach my $attr (@{ $entered_attributes }) {
489 $passed_attribute_types->{ $attr->{ code } } += 1;
492 my @changed_attributes;
494 # Loop through the current patron attributes
495 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
496 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
497 # count differs, overwrite all attributes for given type
498 foreach my $attr (@{ $entered_attributes }) {
499 push @changed_attributes, $attr
500 if $attr->{ code } eq $attribute_type;
503 # count matches, check values
505 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
507 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
512 foreach my $attr (@{ $entered_attributes }) {
513 push @changed_attributes, $attr
514 if $attr->{ code } eq $attribute_type;
520 # Loop through passed attributes, looking for new ones
521 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
522 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
524 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
525 push @changed_attributes, $attr;
530 return \@changed_attributes;
533 sub GeneratePatronAttributesForm {
534 my ( $borrowernumber, $entered_attributes ) = @_;
536 # Get all attribute types and the values for this patron (if applicable)
537 my @types = grep { $_->opac_editable() or $_->opac_display }
538 Koha::Patron::Attribute::Types->search()->as_list();
539 if ( scalar(@types) == 0 ) {
543 my @displayable_attributes = grep { $_->opac_display }
544 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
546 my %attr_values = ();
548 # Build the attribute values list either from the passed values
549 # or taken from the patron itself
550 if ( defined $entered_attributes ) {
551 foreach my $attr (@$entered_attributes) {
552 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
555 elsif ( defined $borrowernumber ) {
556 my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
557 foreach my $attr (@editable_attributes) {
558 push @{ $attr_values{ $attr->code } }, $attr->attribute;
562 # Add the non-editable attributes (that don't come from the form)
563 foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
564 push @{ $attr_values{ $attr->code } }, $attr->attribute;
567 # Find all existing classes
568 my @classes = sort( uniq( map { $_->class } @types ) );
571 foreach my $attr_type (@types) {
572 push @{ $items_by_class{ $attr_type->class() } }, {
574 # If editable, make sure there's at least one empty entry,
575 # to make the template's job easier
576 values => $attr_values{ $attr_type->code() } || ['']
580 # Finally, build a list of containing classes
582 foreach my $class (@classes) {
583 next unless ( $items_by_class{$class} );
585 my $av = Koha::AuthorisedValues->search(
586 { category => 'PA_CLASS', authorised_value => $class } );
588 my $lib = $av->count ? $av->next->opac_description : $class;
593 items => $items_by_class{$class},
601 sub ParsePatronAttributes {
602 my ( $borrowernumber, $cgi ) = @_;
604 my @codes = $cgi->multi_param('patron_attribute_code');
605 my @values = $cgi->multi_param('patron_attribute_value');
607 my $ea = each_array( @codes, @values );
610 my $delete_candidates = {};
612 while ( my ( $code, $value ) = $ea->() ) {
613 if ( !defined($value) or $value eq '' ) {
614 $delete_candidates->{$code} = 1
615 unless $delete_candidates->{$code};
619 push @attributes, { code => $code, value => $value };
621 # 'code' is no longer a delete candidate
622 delete $delete_candidates->{$code};
626 foreach my $code ( keys %{$delete_candidates} ) {
627 if (Koha::Patron::Attributes->search(
628 { borrowernumber => $borrowernumber, code => $code }
632 push @attributes, { code => $code, value => '' }
633 unless any { $_->{code} eq $code } @attributes;