Bug 21082: Update OverDrive authentication method
[koha.git] / opac / opac-memberentry.pl
index 2a20d63..335d1c4 100755 (executable)
@@ -19,7 +19,6 @@ use Modern::Perl;
 
 use CGI qw ( -utf8 );
 use Digest::MD5 qw( md5_base64 md5_hex );
-use Encode qw( encode );
 use JSON;
 use List::MoreUtils qw( any each_array uniq );
 use String::Random qw( random_string );
@@ -29,6 +28,11 @@ use C4::Output;
 use C4::Members;
 use C4::Members::Attributes qw( GetBorrowerAttributes );
 use C4::Form::MessagingPreferences;
+use Koha::AuthUtils;
+use Koha::Patrons;
+use Koha::Patron::Consent;
+use Koha::Patron::Modification;
+use Koha::Patron::Modifications;
 use C4::Scrubber;
 use Email::Valid;
 use Koha::DateUtils;
@@ -166,7 +170,7 @@ if ( $action eq 'create' ) {
                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
             }
 
-            $borrower{password}           = random_string("..........");
+            $borrower{password}          = Koha::AuthUtils::generate_password unless $borrower{password};
             $borrower{verification_token} = $verification_token;
 
             Koha::Patron::Modification->new( \%borrower )->store();
@@ -175,6 +179,7 @@ if ( $action eq 'create' ) {
             my $letter = C4::Letters::GetPreparedLetter(
                 module      => 'members',
                 letter_code => 'OPAC_REG_VERIFY',
+                lang        => 'default', # Patron does not have a preferred language defined yet
                 tables      => {
                     borrower_modifications => $verification_token,
                 },
@@ -203,13 +208,28 @@ if ( $action eq 'create' ) {
             $template->param( OpacPasswordChange =>
                   C4::Context->preference('OpacPasswordChange') );
 
-            my ( $borrowernumber, $password ) = AddMember_Opac(%borrower);
-            C4::Members::Attributes::SetBorrowerAttributes( $borrowernumber, $attributes );
-            C4::Form::MessagingPreferences::handle_form_action($cgi, { borrowernumber => $borrowernumber }, $template, 1, C4::Context->preference('PatronSelfRegistrationDefaultCategory') ) if $borrowernumber && C4::Context->preference('EnhancedMessagingPreferences');
+            $borrower{categorycode}     ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
+            $borrower{password}         ||= Koha::AuthUtils::generate_password;
+            my $consent_dt = delete $borrower{gdpr_proc_consent};
+            my $patron = Koha::Patron->new( \%borrower )->store;
+            Koha::Patron::Consent->new({ borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt })->store if $consent_dt;
+            if ( $patron ) {
+                C4::Members::Attributes::SetBorrowerAttributes( $patron->borrowernumber, $attributes );
+                if ( C4::Context->preference('EnhancedMessagingPreferences') ) {
+                    C4::Form::MessagingPreferences::handle_form_action(
+                        $cgi,
+                        { borrowernumber => $patron->borrowernumber },
+                        $template,
+                        1,
+                        C4::Context->preference('PatronSelfRegistrationDefaultCategory')
+                    );
+                }
 
-            $template->param( password_cleartext => $password );
-            $template->param(
-                borrower => GetMember( borrowernumber => $borrowernumber ) );
+                $template->param( password_cleartext => $patron->plain_text_password );
+                $template->param( borrower => $patron->unblessed );
+            } else {
+                # FIXME Handle possible errors here
+            }
             $template->param(
                 PatronSelfRegistrationAdditionalInstructions =>
                   C4::Context->preference(
@@ -220,15 +240,15 @@ if ( $action eq 'create' ) {
 }
 elsif ( $action eq 'update' ) {
 
-    my $borrower = GetMember( borrowernumber => $borrowernumber );
+    my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed;
     die "Wrong CSRF token"
         unless Koha::Token->new->check_csrf({
-            id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
-            secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
+            session_id => scalar $cgi->cookie('CGISESSID'),
             token  => scalar $cgi->param('csrf_token'),
         });
 
     my %borrower = ParseCgiForBorrower($cgi);
+    $borrower{borrowernumber} = $borrowernumber;
 
     my %borrower_changes = DelEmptyFields(%borrower);
     my @empty_mandatory_fields =
@@ -244,8 +264,7 @@ elsif ( $action eq 'update' ) {
             invalid_form_fields    => $invalidformfields,
             borrower               => \%borrower,
             csrf_token             => Koha::Token->new->generate_csrf({
-                id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
-                secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
+                session_id => scalar $cgi->cookie('CGISESSID'),
             }),
         );
         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) );
@@ -254,7 +273,7 @@ elsif ( $action eq 'update' ) {
     }
     else {
         my %borrower_changes = DelUnchangedFields( $borrowernumber, %borrower );
-        my $extended_attributes_changes = FilterUnchagedAttributes( $borrowernumber, $attributes );
+        my $extended_attributes_changes = FilterUnchangedAttributes( $borrowernumber, $attributes );
 
         if ( %borrower_changes || scalar @{$extended_attributes_changes} > 0 ) {
             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
@@ -269,54 +288,47 @@ elsif ( $action eq 'update' ) {
             $borrower_changes{borrowernumber} = $borrowernumber;
             $borrower_changes{extended_attributes} = to_json($extended_attributes_changes);
 
-            # FIXME update the following with
-            # Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
-            # when bug 17091 will be pushed
-            my $patron_modifications = Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber });
-            while ( my $patron_modification = $patron_modifications->next ) {
-                $patron_modification->delete;
-            }
+            Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
 
             my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
 
-            $template->param(
-                borrower => GetMember( borrowernumber => $borrowernumber ),
-            );
+            my $patron = Koha::Patrons->find( $borrowernumber );
+            $template->param( borrower => $patron->unblessed );
         }
         else {
+            my $patron = Koha::Patrons->find( $borrowernumber );
             $template->param(
                 action => 'edit',
                 nochanges => 1,
-                borrower => GetMember( borrowernumber => $borrowernumber ),
+                borrower => $patron->unblessed,
                 patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ),
                 csrf_token => Koha::Token->new->generate_csrf({
-                    id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
-                    secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
+                    session_id => scalar $cgi->cookie('CGISESSID'),
                 }),
             );
         }
     }
 }
 elsif ( $action eq 'edit' ) {    #Display logged in borrower's data
-    my $borrower = GetMember( borrowernumber => $borrowernumber );
+    my $patron = Koha::Patrons->find( $borrowernumber );
+    my $borrower = $patron->unblessed;
 
     $template->param(
         borrower  => $borrower,
         guarantor => scalar Koha::Patrons->find($borrowernumber)->guarantor(),
         hidden => GetHiddenFields( $mandatory, 'modification' ),
         csrf_token => Koha::Token->new->generate_csrf({
-            id     => Encode::encode( 'UTF-8', $borrower->{userid} ),
-            secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
+            session_id => scalar $cgi->cookie('CGISESSID'),
         }),
     );
 
     if (C4::Context->preference('OPACpatronimages')) {
-        my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
-        $template->param( display_patron_image => 1 ) if $patron_image;
+        $template->param( display_patron_image => 1 ) if $patron->image;
     }
 
     $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) );
 } else {
+    # Render self-registration page
     $template->param( patron_attribute_classes => GeneratePatronAttributesForm() );
 }
 
@@ -357,6 +369,7 @@ sub GetMandatoryFields {
       C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField");
 
     my @fields = split( /\|/, $BorrowerMandatoryField );
+    push @fields, 'gdpr_proc_consent' if C4::Context->preference('GDPR_Policy');
 
     foreach (@fields) {
         $mandatory_fields{$_} = 1;
@@ -388,14 +401,23 @@ sub CheckMandatoryFields {
 }
 
 sub CheckForInvalidFields {
-    my $minpw = C4::Context->preference('minPasswordLength');
     my $borrower = shift;
     my @invalidFields;
     if ($borrower->{'email'}) {
         unless ( Email::Valid->address($borrower->{'email'}) ) {
             push(@invalidFields, "email");
         } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) {
-            my $patrons_with_same_email = Koha::Patrons->search( { email => $borrower->{email} })->count;
+            my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited?
+                {
+                    email => $borrower->{email},
+                    (
+                        exists $borrower->{borrowernumber}
+                        ? ( borrowernumber =>
+                              { '!=' => $borrower->{borrowernumber} } )
+                        : ()
+                    )
+                }
+            )->count;
             if ( $patrons_with_same_email ) {
                 push @invalidFields, "duplicate_email";
             }
@@ -412,11 +434,13 @@ sub CheckForInvalidFields {
     {
         push( @invalidFields, "password_match" );
     }
-    if ( $borrower->{'password'}  && $minpw && (length($borrower->{'password'}) < $minpw) ) {
-       push(@invalidFields, "password_invalid");
-    }
     if ( $borrower->{'password'} ) {
-       push(@invalidFields, "password_spaces") if ($borrower->{'password'} =~ /^\s/ or $borrower->{'password'} =~ /\s$/);
+        my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
+          unless ( $is_valid ) {
+              push @invalidFields, 'password_too_short' if $error eq 'too_short';
+              push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
+              push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces';
+          }
     }
 
     return \@invalidFields;
@@ -428,10 +452,15 @@ sub ParseCgiForBorrower {
     my $scrubber = C4::Scrubber->new();
     my %borrower;
 
-    foreach ( $cgi->param ) {
-        if ( $_ =~ '^borrower_' ) {
-            my ($key) = substr( $_, 9 );
-            $borrower{$key} = $scrubber->scrub( scalar $cgi->param($_) );
+    foreach my $field ( $cgi->param ) {
+        if ( $field =~ '^borrower_' ) {
+            my ($key) = substr( $field, 9 );
+            if ( $field !~ '^borrower_password' ) {
+                $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) );
+            } else {
+                # Allow html characters for passwords
+                $borrower{$key} = $cgi->param($field);
+            }
         }
     }
 
@@ -447,13 +476,17 @@ sub ParseCgiForBorrower {
         $borrower{'dateofbirth'} = undef;
     }
 
+    # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
+    $borrower{gdpr_proc_consent} = dt_from_string if  $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed';
+
     return %borrower;
 }
 
 sub DelUnchangedFields {
     my ( $borrowernumber, %new_data ) = @_;
 
-    my $current_data = GetMember( borrowernumber => $borrowernumber );
+    my $patron = Koha::Patrons->find( $borrowernumber );
+    my $current_data = $patron->unblessed;
 
     foreach my $key ( keys %new_data ) {
         if ( $current_data->{$key} eq $new_data{$key} ) {
@@ -474,7 +507,7 @@ sub DelEmptyFields {
     return %borrower;
 }
 
-sub FilterUnchagedAttributes {
+sub FilterUnchangedAttributes {
     my ( $borrowernumber, $entered_attributes ) = @_;
 
     my @patron_attributes = grep {$_->opac_editable} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list;
@@ -574,7 +607,9 @@ sub GeneratePatronAttributesForm {
             # If editable, make sure there's at least one empty entry,
             # to make the template's job easier
             values => $attr_values{ $attr_type->code() } || ['']
-        };
+        }
+            unless !defined $attr_values{ $attr_type->code() }
+                    and !$attr_type->opac_editable;
     }
 
     # Finally, build a list of containing classes
@@ -604,30 +639,35 @@ sub ParsePatronAttributes {
     my @codes  = $cgi->multi_param('patron_attribute_code');
     my @values = $cgi->multi_param('patron_attribute_value');
 
+    my @editable_attribute_types
+        = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 });
+
     my $ea = each_array( @codes, @values );
     my @attributes;
 
     my $delete_candidates = {};
 
     while ( my ( $code, $value ) = $ea->() ) {
-        if ( !defined($value) or $value eq '' ) {
-            $delete_candidates->{$code} = 1
-                unless $delete_candidates->{$code};
-        }
-        else {
-            # we've got a value
-            push @attributes, { code => $code, value => $value };
+        if ( any { $_ eq $code } @editable_attribute_types ) {
+            # It is an editable attribute
+            if ( !defined($value) or $value eq '' ) {
+                $delete_candidates->{$code} = 1
+                    unless $delete_candidates->{$code};
+            }
+            else {
+                # we've got a value
+                push @attributes, { code => $code, value => $value };
 
-            # 'code' is no longer a delete candidate
-            delete $delete_candidates->{$code};
+                # 'code' is no longer a delete candidate
+                delete $delete_candidates->{$code}
+                    if defined $delete_candidates->{$code};
+            }
         }
     }
 
     foreach my $code ( keys %{$delete_candidates} ) {
-        if (Koha::Patron::Attributes->search(
-                { borrowernumber => $borrowernumber, code => $code }
-            )->count > 0
-            )
+        if ( Koha::Patron::Attributes->search({
+                borrowernumber => $borrowernumber, code => $code })->count > 0 )
         {
             push @attributes, { code => $code, value => '' }
                 unless any { $_->{code} eq $code } @attributes;