Bug 21116: Unit tests
[koha.git] / opac / opac-memberentry.pl
blob4eeacf093a47b5a86383c513b74256fd13c8b8ce
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 Koha::AuthUtils;
32 use Koha::Patrons;
33 use Koha::Patron::Modification;
34 use Koha::Patron::Modifications;
35 use C4::Scrubber;
36 use Email::Valid;
37 use Koha::DateUtils;
38 use Koha::Libraries;
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;
44 use Koha::Patrons;
45 use Koha::Token;
47 my $cgi = new CGI;
48 my $dbh = C4::Context->dbh;
50 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
52 template_name => "opac-memberentry.tt",
53 type => "opac",
54 query => $cgi,
55 authnotrequired => 1,
59 unless ( C4::Context->preference('PatronSelfRegistration') || $borrowernumber )
61 print $cgi->redirect("/cgi-bin/koha/opac-main.pl");
62 exit;
65 my $action = $cgi->param('action') || q{};
66 if ( $action eq q{} ) {
67 if ($borrowernumber) {
68 $action = 'edit';
70 else {
71 $action = 'new';
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();
82 if ( defined $min ) {
83 $template->param(
84 minlength_cardnumber => $min,
85 maxlength_cardnumber => $max
89 $template->param(
90 action => $action,
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});
103 $template->param(
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 );
135 $template->param(
136 empty_mandatory_fields => \@empty_mandatory_fields,
137 invalid_form_fields => $invalidformfields,
138 borrower => \%borrower
140 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
142 elsif (
143 md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') )
145 $template->param(
146 failed_captcha => 1,
147 borrower => \%borrower
149 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
151 else {
152 if (
153 C4::Context->boolean_preference(
154 'PatronSelfRegistrationVerifyByEmail')
157 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
159 template_name => "opac-registration-email-sent.tt",
160 type => "opac",
161 query => $cgi,
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(
179 module => 'members',
180 letter_code => 'OPAC_REG_VERIFY',
181 lang => 'default', # Patron does not have a preferred language defined yet
182 tables => {
183 borrower_modifications => $verification_token,
187 C4::Letters::EnqueueLetter(
189 letter => $letter,
190 message_transport_type => 'email',
191 to_address => $borrower{'email'},
192 from_address =>
193 C4::Context->preference('KohaAdminEmailAddress'),
197 else {
198 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
200 template_name => "opac-registration-confirmation.tt",
201 type => "opac",
202 query => $cgi,
203 authnotrequired => 1,
207 $template->param( OpacPasswordChange =>
208 C4::Context->preference('OpacPasswordChange') );
210 $borrower{categorycode} ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
211 $borrower{password} ||= Koha::AuthUtils::generate_password;
212 my $patron = Koha::Patron->new( \%borrower )->store;
213 if ( $patron ) {
214 C4::Members::Attributes::SetBorrowerAttributes( $patron->borrowernumber, $attributes );
215 if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
216 C4::Form::MessagingPreferences::handle_form_action(
217 $cgi,
218 { borrowernumber => $patron->borrowernumber },
219 $template,
221 C4::Context->preference('PatronSelfRegistrationDefaultCategory')
225 $template->param( password_cleartext => $patron->plain_text_password );
226 $template->param( borrower => $patron->unblessed );
227 } else {
228 # FIXME Handle possible errors here
230 $template->param(
231 PatronSelfRegistrationAdditionalInstructions =>
232 C4::Context->preference(
233 'PatronSelfRegistrationAdditionalInstructions')
238 elsif ( $action eq 'update' ) {
240 my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
241 die "Wrong CSRF token"
242 unless Koha::Token->new->check_csrf({
243 session_id => scalar $cgi->cookie('CGISESSID'),
244 token => scalar $cgi->param('csrf_token'),
247 my %borrower = ParseCgiForBorrower($cgi);
248 $borrower{borrowernumber} = $borrowernumber;
250 my %borrower_changes = DelEmptyFields(%borrower);
251 my @empty_mandatory_fields =
252 CheckMandatoryFields( \%borrower_changes, $action );
253 my $invalidformfields = CheckForInvalidFields(\%borrower);
255 # Send back the data to the template
256 %borrower = ( %$borrower, %borrower );
258 if (@empty_mandatory_fields || @$invalidformfields) {
259 $template->param(
260 empty_mandatory_fields => \@empty_mandatory_fields,
261 invalid_form_fields => $invalidformfields,
262 borrower => \%borrower,
263 csrf_token => Koha::Token->new->generate_csrf({
264 session_id => scalar $cgi->cookie('CGISESSID'),
267 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
269 $template->param( action => 'edit' );
271 else {
272 my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
273 my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
275 if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
276 ( $template, $borrowernumber, $cookie ) = get_template_and_user(
278 template_name => "opac-memberentry-update-submitted.tt",
279 type => "opac",
280 query => $cgi,
281 authnotrequired => 1,
285 $borrower_changes{borrowernumber} = $borrowernumber;
286 $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
288 Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
290 my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
292 my $patron = Koha::Patrons->find( $borrowernumber );
293 $template->param( borrower => $patron->unblessed );
295 else {
296 my $patron = Koha::Patrons->find( $borrowernumber );
297 $template->param(
298 action => 'edit',
299 nochanges => 1,
300 borrower => $patron->unblessed,
301 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
302 csrf_token => Koha::Token->new->generate_csrf({
303 session_id => scalar $cgi->cookie('CGISESSID'),
309 elsif ( $action eq 'edit' ) { #Display logged in borrower's data
310 my $patron = Koha::Patrons->find( $borrowernumber );
311 my $borrower = $patron->unblessed;
313 $template->param(
314 borrower => $borrower,
315 guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
316 hidden => GetHiddenFields( $mandatory, 'modification' ),
317 csrf_token => Koha::Token->new->generate_csrf({
318 session_id => scalar $cgi->cookie('CGISESSID'),
322 if (C4::Context->preference('OPACpatronimages')) {
323 $template->param( display_patron_image => 1 ) if $patron->image;
326 $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
327 } else {
328 # Render self-registration page
329 $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
332 my $captcha = random_string("CCCCC");
334 $template->param(
335 captcha => $captcha,
336 captcha_digest => md5_base64($captcha)
339 output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 };
341 sub GetHiddenFields {
342 my ( $mandatory, $action ) = @_;
343 my %hidden_fields;
345 my $BorrowerUnwantedField = $action eq 'modification' ?
346 C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) :
347 C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" );
349 my @fields = split( /\|/, $BorrowerUnwantedField || q|| );
350 foreach (@fields) {
351 next unless m/\w/o;
352 #Don't hide mandatory fields
353 next if $mandatory->{$_};
354 $hidden_fields{$_} = 1;
357 return \%hidden_fields;
360 sub GetMandatoryFields {
361 my ($action) = @_;
363 my %mandatory_fields;
365 my $BorrowerMandatoryField =
366 C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
368 my @fields = split( /\|/, $BorrowerMandatoryField );
370 foreach (@fields) {
371 $mandatory_fields{$_} = 1;
374 if ( $action eq 'create' || $action eq 'new' ) {
375 $mandatory_fields{'email'} = 1
376 if C4::Context->boolean_preference(
377 'PatronSelfRegistrationVerifyByEmail');
380 return \%mandatory_fields;
383 sub CheckMandatoryFields {
384 my ( $borrower, $action ) = @_;
386 my @empty_mandatory_fields;
388 my $mandatory_fields = GetMandatoryFields($action);
389 delete $mandatory_fields->{'cardnumber'};
391 foreach my $key ( keys %$mandatory_fields ) {
392 push( @empty_mandatory_fields, $key )
393 unless ( defined( $borrower->{$key} ) && $borrower->{$key} );
396 return @empty_mandatory_fields;
399 sub CheckForInvalidFields {
400 my $borrower = shift;
401 my @invalidFields;
402 if ($borrower->{'email'}) {
403 unless ( Email::Valid->address($borrower->{'email'}) ) {
404 push(@invalidFields, "email");
405 } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
406 my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
408 email => $borrower->{email},
410 exists $borrower->{borrowernumber}
411 ? ( borrowernumber =>
412 { '!=' => $borrower->{borrowernumber} } )
413 : ()
416 )->count;
417 if ( $patrons_with_same_email ) {
418 push @invalidFields, "duplicate_email";
422 if ($borrower->{'emailpro'}) {
423 push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
425 if ($borrower->{'B_email'}) {
426 push(@invalidFields, "B_email") if (!Email::Valid->address($borrower->{'B_email'}));
428 if ( defined $borrower->{'password'}
429 and $borrower->{'password'} ne $borrower->{'password2'} )
431 push( @invalidFields, "password_match" );
433 if ( $borrower->{'password'} ) {
434 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
435 unless ( $is_valid ) {
436 push @invalidFields, 'password_too_short' if $error eq 'too_short';
437 push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
438 push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
442 return \@invalidFields;
445 sub ParseCgiForBorrower {
446 my ($cgi) = @_;
448 my $scrubber = C4::Scrubber->new();
449 my %borrower;
451 foreach my $field ( $cgi->param ) {
452 if ( $field =~ '^borrower_' ) {
453 my ($key) = substr( $field, 9 );
454 if ( $field !~ '^borrower_password' ) {
455 $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
456 } else {
457 # Allow html characters for passwords
458 $borrower{$key} = $cgi->param($field);
463 my $dob_dt;
464 $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
465 if ( $borrower{'dateofbirth'} );
467 if ( $dob_dt ) {
468 $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
470 else {
471 # Trigger validation
472 $borrower{'dateofbirth'} = undef;
475 return %borrower;
478 sub DelUnchangedFields {
479 my ( $borrowernumber, %new_data ) = @_;
481 my $patron = Koha::Patrons->find( $borrowernumber );
482 my $current_data = $patron->unblessed;
484 foreach my $key ( keys %new_data ) {
485 if ( $current_data->{$key} eq $new_data{$key} ) {
486 delete $new_data{$key};
490 return %new_data;
493 sub DelEmptyFields {
494 my (%borrower) = @_;
496 foreach my $key ( keys %borrower ) {
497 delete $borrower{$key} unless $borrower{$key};
500 return %borrower;
503 sub FilterUnchangedAttributes {
504 my ( $borrowernumber, $entered_attributes ) = @_;
506 my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
508 my $patron_attribute_types;
509 foreach my $attr (@patron_attributes) {
510 $patron_attribute_types->{ $attr->code } += 1;
513 my $passed_attribute_types;
514 foreach my $attr (@{ $entered_attributes }) {
515 $passed_attribute_types->{ $attr->{ code } } += 1;
518 my @changed_attributes;
520 # Loop through the current patron attributes
521 foreach my $attribute_type ( keys %{ $patron_attribute_types } ) {
522 if ( $patron_attribute_types->{ $attribute_type } != $passed_attribute_types->{ $attribute_type } ) {
523 # count differs, overwrite all attributes for given type
524 foreach my $attr (@{ $entered_attributes }) {
525 push @changed_attributes, $attr
526 if $attr->{ code } eq $attribute_type;
528 } else {
529 # count matches, check values
530 my $changes = 0;
531 foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) {
532 $changes = 1
533 unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes };
534 last if $changes;
537 if ( $changes ) {
538 foreach my $attr (@{ $entered_attributes }) {
539 push @changed_attributes, $attr
540 if $attr->{ code } eq $attribute_type;
546 # Loop through passed attributes, looking for new ones
547 foreach my $attribute_type ( keys %{ $passed_attribute_types } ) {
548 if ( !defined $patron_attribute_types->{ $attribute_type } ) {
549 # YAY, new stuff
550 foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) {
551 push @changed_attributes, $attr;
556 return \@changed_attributes;
559 sub GeneratePatronAttributesForm {
560 my ( $borrowernumber, $entered_attributes ) = @_;
562 # Get all attribute types and the values for this patron (if applicable)
563 my @types = grep { $_->opac_editable() or $_->opac_display }
564 Koha::Patron::Attribute::Types->search()->as_list();
565 if ( scalar(@types) == 0 ) {
566 return [];
569 my @displayable_attributes = grep { $_->opac_display }
570 Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
572 my %attr_values = ();
574 # Build the attribute values list either from the passed values
575 # or taken from the patron itself
576 if ( defined $entered_attributes ) {
577 foreach my $attr (@$entered_attributes) {
578 push @{ $attr_values{ $attr->{code} } }, $attr->{value};
581 elsif ( defined $borrowernumber ) {
582 my @editable_attributes = grep { $_->opac_editable } @displayable_attributes;
583 foreach my $attr (@editable_attributes) {
584 push @{ $attr_values{ $attr->code } }, $attr->attribute;
588 # Add the non-editable attributes (that don't come from the form)
589 foreach my $attr ( grep { !$_->opac_editable } @displayable_attributes ) {
590 push @{ $attr_values{ $attr->code } }, $attr->attribute;
593 # Find all existing classes
594 my @classes = sort( uniq( map { $_->class } @types ) );
595 my %items_by_class;
597 foreach my $attr_type (@types) {
598 push @{ $items_by_class{ $attr_type->class() } }, {
599 type => $attr_type,
600 # If editable, make sure there's at least one empty entry,
601 # to make the template's job easier
602 values => $attr_values{ $attr_type->code() } || ['']
604 unless !defined $attr_values{ $attr_type->code() }
605 and !$attr_type->opac_editable;
608 # Finally, build a list of containing classes
609 my @class_loop;
610 foreach my $class (@classes) {
611 next unless ( $items_by_class{$class} );
613 my $av = Koha::AuthorisedValues->search(
614 { category => 'PA_CLASS', authorised_value => $class } );
616 my $lib = $av->count ? $av->next->opac_description : $class;
618 push @class_loop,
620 class => $class,
621 items => $items_by_class{$class},
622 lib => $lib,
626 return \@class_loop;
629 sub ParsePatronAttributes {
630 my ( $borrowernumber, $cgi ) = @_;
632 my @codes = $cgi->multi_param('patron_attribute_code');
633 my @values = $cgi->multi_param('patron_attribute_value');
635 my @editable_attribute_types
636 = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
638 my $ea = each_array( @codes, @values );
639 my @attributes;
641 my $delete_candidates = {};
643 while ( my ( $code, $value ) = $ea->() ) {
644 if ( any { $_ eq $code } @editable_attribute_types ) {
645 # It is an editable attribute
646 if ( !defined($value) or $value eq '' ) {
647 $delete_candidates->{$code} = 1
648 unless $delete_candidates->{$code};
650 else {
651 # we've got a value
652 push @attributes, { code => $code, value => $value };
654 # 'code' is no longer a delete candidate
655 delete $delete_candidates->{$code}
656 if defined $delete_candidates->{$code};
661 foreach my $code ( keys %{$delete_candidates} ) {
662 if ( Koha::Patron::Attributes->search({
663 borrowernumber => $borrowernumber, code => $code })->count > 0 )
665 push @attributes, { code => $code, value => '' }
666 unless any { $_->{code} eq $code } @attributes;
670 return \@attributes;