Bug 13757 - DBRev 16.12.00.016
[koha.git] / opac / opac-memberentry.pl
blobd62d89c74917573b61c17175bb77374f6071b865
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 Encode qw( encode );
23 use JSON;
24 use List::MoreUtils qw( any each_array uniq );
25 use String::Random qw( random_string );
27 use C4::Auth;
28 use C4::Output;
29 use C4::Members;
30 use C4::Members::Attributes qw( GetBorrowerAttributes );
31 use C4::Form::MessagingPreferences;
32 use C4::Scrubber;
33 use Email::Valid;
34 use Koha::DateUtils;
35 use Koha::Libraries;
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;
41 use Koha::Patrons;
42 use Koha::Token;
44 my $cgi = new CGI;
45 my $dbh = C4::Context->dbh;
47 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
49 template_name => "opac-memberentry.tt",
50 type => "opac",
51 query => $cgi,
52 authnotrequired => 1,
56 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
58 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
59 exit;
62 my $action = $cgi->param('action') || q{};
63 if ( $action eq q{} ) {
64 if ($borrowernumber) {
65 $action = 'edit';
67 else {
68 $action = 'new';
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();
79 if ( defined $min ) {
80 $template->param(
81 minlength_cardnumber => $min,
82 maxlength_cardnumber => $max
86 $template->param(
87 action => $action,
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});
100 $template->param(
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 );
132 $template->param(
133 empty_mandatory_fields => \@empty_mandatory_fields,
134 invalid_form_fields => $invalidformfields,
135 borrower => \%borrower
137 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
139 elsif (
140 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
142 $template->param(
143 failed_captcha => 1,
144 borrower => \%borrower
146 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
148 else {
149 if (
150 C4::Context->boolean_preference(
151 'PatronSelfRegistrationVerifyByEmail')
154 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
156 template_name => "opac-registration-email-sent.tt",
157 type => "opac",
158 query => $cgi,
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(
176 module => 'members',
177 letter_code => 'OPAC_REG_VERIFY',
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 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) {
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 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' );
255 else {
256 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
257 my $extended_attributes_changes = FilterUnchangedAttributes( $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",
263 type => "opac",
264 query => $cgi,
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();
282 $template->param(
283 borrower => GetMember( borrowernumber => $borrowernumber ),
286 else {
287 $template->param(
288 action => 'edit',
289 nochanges => 1,
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 );
303 $template->param(
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 ) );
319 } else {
320 # Render self-registration page
321 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
324 my $captcha = random_string("CCCCC");
326 $template->param(
327 captcha => $captcha,
328 captcha_digest => md5_base64($captcha)
331 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
333 sub GetHiddenFields {
334 my ( $mandatory, $action ) = @_;
335 my %hidden_fields;
337 my $BorrowerUnwantedField = $action eq 'modification' ?
338 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
339 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
341 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
342 foreach (@fields) {
343 next unless m/\w/o;
344 #Don't hide mandatory fields
345 next if $mandatory->{$_};
346 $hidden_fields{$_} = 1;
349 return \%hidden_fields;
352 sub GetMandatoryFields {
353 my ($action) = @_;
355 my %mandatory_fields;
357 my $BorrowerMandatoryField =
358 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
360 my @fields = split( /\|/, $BorrowerMandatoryField );
362 foreach (@fields) {
363 $mandatory_fields{$_} = 1;
366 if ( $action eq 'create' || $action eq 'new' ) {
367 $mandatory_fields{'email'} = 1
368 if C4::Context->boolean_preference(
369 'PatronSelfRegistrationVerifyByEmail');
372 return \%mandatory_fields;
375 sub CheckMandatoryFields {
376 my ( $borrower, $action ) = @_;
378 my @empty_mandatory_fields;
380 my $mandatory_fields = GetMandatoryFields($action);
381 delete $mandatory_fields->{'cardnumber'};
383 foreach my $key ( keys %$mandatory_fields ) {
384 push( @empty_mandatory_fields, $key )
385 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
388 return @empty_mandatory_fields;
391 sub CheckForInvalidFields {
392 my $minpw = C4::Context->preference('minPasswordLength');
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( { email => $borrower->{email} })->count;
400 if ( $patrons_with_same_email ) {
401 push @invalidFields, "duplicate_email";
405 if ($borrower->{'emailpro'}) {
406 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
408 if ($borrower->{'B_email'}) {
409 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
411 if ( defined $borrower->{'password'}
412 and $borrower->{'password'} ne $borrower->{'password2'} )
414 push( @invalidFields, "password_match" );
416 if ( $borrower->{'password'} && $minpw && (length($borrower->{'password'}) < $minpw) ) {
417 push(@invalidFields, "password_invalid");
419 if ( $borrower->{'password'} ) {
420 push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
423 return \@invalidFields;
426 sub ParseCgiForBorrower {
427 my ($cgi) = @_;
429 my $scrubber = C4::Scrubber->new();
430 my %borrower;
432 foreach ( $cgi->param ) {
433 if ( $_ =~ '^borrower_' ) {
434 my ($key) = substr( $_, 9 );
435 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
439 my $dob_dt;
440 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
441 if ( $borrower{'dateofbirth'} );
443 if ( $dob_dt ) {
444 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
446 else {
447 # Trigger validation
448 $borrower{'dateofbirth'} = undef;
451 return %borrower;
454 sub DelUnchangedFields {
455 my ( $borrowernumber, %new_data ) = @_;
457 my $current_data = GetMember( borrowernumber => $borrowernumber );
459 foreach my $key ( keys %new_data ) {
460 if ( $current_data->{$key} eq $new_data{$key} ) {
461 delete $new_data{$key};
465 return %new_data;
468 sub DelEmptyFields {
469 my (%borrower) = @_;
471 foreach my $key ( keys %borrower ) {
472 delete $borrower{$key} unless $borrower{$key};
475 return %borrower;
478 sub FilterUnchangedAttributes {
479 my ( $borrowernumber, $entered_attributes ) = @_;
481 my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
483 my $patron_attribute_types;
484 foreach my $attr (@patron_attributes) {
485 $patron_attribute_types->{ $attr->code } += 1;
488 my $passed_attribute_types;
489 foreach my $attr (@{ $entered_attributes }) {
490 $passed_attribute_types->{ $attr->{ code } } += 1;
493 my @changed_attributes;
495 # Loop through the current patron attributes
496 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
497 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
498 # count differs, overwrite all attributes for given type
499 foreach my $attr (@{ $entered_attributes }) {
500 push @changed_attributes, $attr
501 if $attr->{ code } eq $attribute_type;
503 } else {
504 # count matches, check values
505 my $changes = 0;
506 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
507 $changes = 1
508 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
509 last if $changes;
512 if ( $changes ) {
513 foreach my $attr (@{ $entered_attributes }) {
514 push @changed_attributes, $attr
515 if $attr->{ code } eq $attribute_type;
521 # Loop through passed attributes, looking for new ones
522 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
523 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
524 # YAY, new stuff
525 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
526 push @changed_attributes, $attr;
531 return \@changed_attributes;
534 sub GeneratePatronAttributesForm {
535 my ( $borrowernumber, $entered_attributes ) = @_;
537 # Get all attribute types and the values for this patron (if applicable)
538 my @types = grep { $_->opac_editable() or $_->opac_display }
539 Koha::Patron::Attribute::Types->search()->as_list();
540 if ( scalar(@types) == 0 ) {
541 return [];
544 my @displayable_attributes = grep { $_->opac_display }
545 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
547 my %attr_values = ();
549 # Build the attribute values list either from the passed values
550 # or taken from the patron itself
551 if ( defined $entered_attributes ) {
552 foreach my $attr (@$entered_attributes) {
553 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
556 elsif ( defined $borrowernumber ) {
557 my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
558 foreach my $attr (@editable_attributes) {
559 push @{ $attr_values{ $attr->code } }, $attr->attribute;
563 # Add the non-editable attributes (that don't come from the form)
564 foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
565 push @{ $attr_values{ $attr->code } }, $attr->attribute;
568 # Find all existing classes
569 my @classes = sort( uniq( map { $_->class } @types ) );
570 my %items_by_class;
572 foreach my $attr_type (@types) {
573 push @{ $items_by_class{ $attr_type->class() } }, {
574 type => $attr_type,
575 # If editable, make sure there's at least one empty entry,
576 # to make the template's job easier
577 values => $attr_values{ $attr_type->code() } || ['']
579 unless !defined $attr_values{ $attr_type->code() }
580 and !$attr_type->opac_editable;
583 # Finally, build a list of containing classes
584 my @class_loop;
585 foreach my $class (@classes) {
586 next unless ( $items_by_class{$class} );
588 my $av = Koha::AuthorisedValues->search(
589 { category => 'PA_CLASS', authorised_value => $class } );
591 my $lib = $av->count ? $av->next->opac_description : $class;
593 push @class_loop,
595 class => $class,
596 items => $items_by_class{$class},
597 lib => $lib,
601 return \@class_loop;
604 sub ParsePatronAttributes {
605 my ( $borrowernumber, $cgi ) = @_;
607 my @codes = $cgi->multi_param('patron_attribute_code');
608 my @values = $cgi->multi_param('patron_attribute_value');
610 my @editable_attribute_types
611 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
613 my $ea = each_array( @codes, @values );
614 my @attributes;
616 my $delete_candidates = {};
618 while ( my ( $code, $value ) = $ea->() ) {
619 if ( any { $_ eq $code } @editable_attribute_types ) {
620 # It is an editable attribute
621 if ( !defined($value) or $value eq '' ) {
622 $delete_candidates->{$code} = 1
623 unless $delete_candidates->{$code};
625 else {
626 # we've got a value
627 push @attributes, { code => $code, value => $value };
629 # 'code' is no longer a delete candidate
630 delete $delete_candidates->{$code}
631 if defined $delete_candidates->{$code};
636 foreach my $code ( keys %{$delete_candidates} ) {
637 if ( Koha::Patron::Attributes->search({
638 borrowernumber => $borrowernumber, code => $code })->count > 0 )
640 push @attributes, { code => $code, value => '' }
641 unless any { $_->{code} eq $code } @attributes;
645 return \@attributes;