Bug 22544: Move get_opac_new to Koha namespace
[srvgit] / opac / opac-memberentry.pl
index e954587..c9a4790 100755 (executable)
@@ -25,6 +25,7 @@ use String::Random qw( random_string );
 
 use C4::Auth;
 use C4::Output;
+use C4::Context;
 use C4::Members;
 use C4::Form::MessagingPreferences;
 use Koha::AuthUtils;
@@ -41,10 +42,10 @@ use Koha::Patron::Attributes;
 use Koha::Patron::Images;
 use Koha::Patron::Modification;
 use Koha::Patron::Modifications;
-use Koha::Patrons;
+use Koha::Patron::Categories;
 use Koha::Token;
-
-my $cgi = new CGI;
+use Koha::AuthorisedValues;
+my $cgi = CGI->new;
 my $dbh = C4::Context->dbh;
 
 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
@@ -74,14 +75,14 @@ if ( $action eq q{} ) {
 
 my $mandatory = GetMandatoryFields($action);
 
-my @libraries = Koha::Libraries->search;
-if ( my @libraries_to_display = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList') ) {
-    @libraries = map {
-        my $b          = $_;
-        my $branchcode = $_->branchcode;
-        ( grep { $_ eq $branchcode } @libraries_to_display ) ? $b : ()
-    } @libraries;
+my $params = {};
+if ( $action eq 'create' || $action eq 'new' ) {
+    my @PatronSelfRegistrationLibraryList = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList');
+    $params = { branchcode => { -in => \@PatronSelfRegistrationLibraryList } }
+      if @PatronSelfRegistrationLibraryList;
 }
+my @libraries = Koha::Libraries->search($params);
+
 my ( $min, $max ) = C4::Members::get_cardnumber_length();
 if ( defined $min ) {
      $template->param(
@@ -90,12 +91,15 @@ if ( defined $min ) {
      );
  }
 
+my $defaultCategory = Koha::Patron::Categories->find(C4::Context->preference('PatronSelfRegistrationDefaultCategory'));
+
 $template->param(
     action            => $action,
     hidden            => GetHiddenFields( $mandatory, $action ),
     mandatory         => $mandatory,
     libraries         => \@libraries,
     OPACPatronDetails => C4::Context->preference('OPACPatronDetails'),
+    defaultCategory  => $defaultCategory,
 );
 
 my $attributes = ParsePatronAttributes($borrowernumber,$cgi);
@@ -103,8 +107,7 @@ my $conflicting_attribute = 0;
 
 foreach my $attr (@$attributes) {
     my $attribute = Koha::Patron::Attribute->new($attr);
-    eval {$attribute->check_unique_id};
-    if ( $@ ) {
+    if ( !$attribute->unique_ok ) {
         my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
         $template->param(
             extended_unique_id_failed_code => $attr->{code},
@@ -120,8 +123,9 @@ if ( $action eq 'create' ) {
     my %borrower = ParseCgiForBorrower($cgi);
 
     %borrower = DelEmptyFields(%borrower);
+    $borrower{categorycode} ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
 
-    my @empty_mandatory_fields = CheckMandatoryFields( \%borrower, $action );
+    my @empty_mandatory_fields = (CheckMandatoryFields( \%borrower, $action ), CheckMandatoryAttributes( \%borrower, $attributes ) );
     my $invalidformfields = CheckForInvalidFields(\%borrower);
     delete $borrower{'password2'};
     my $cardnumber_error_code;
@@ -153,10 +157,12 @@ if ( $action eq 'create' ) {
             borrower       => \%borrower
         );
         $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) );
+    } elsif ( ! grep { $borrower{branchcode} eq $_->branchcode } @libraries ) {
+        die "Branchcode not allowed"; # They hack the form
     }
     else {
         if (
-            C4::Context->boolean_preference(
+            C4::Context->preference(
                 'PatronSelfRegistrationVerifyByEmail')
           )
         {
@@ -175,7 +181,7 @@ if ( $action eq 'create' ) {
                 $verification_token = md5_hex( time().{}.rand().{}.$$ );
             }
 
-            $borrower{password}          = Koha::AuthUtils::generate_password unless $borrower{password};
+            $borrower{password}          = Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode})) unless $borrower{password};
             $borrower{verification_token} = $verification_token;
 
             Koha::Patron::Modification->new( \%borrower )->store();
@@ -190,7 +196,7 @@ if ( $action eq 'create' ) {
                 },
             );
 
-            C4::Letters::EnqueueLetter(
+            my $message_id = C4::Letters::EnqueueLetter(
                 {
                     letter                 => $letter,
                     message_transport_type => 'email',
@@ -199,9 +205,7 @@ if ( $action eq 'create' ) {
                       C4::Context->preference('KohaAdminEmailAddress'),
                 }
             );
-            my $num_letters_attempted = C4::Letters::SendQueuedMessages( {
-                    letter_code => 'OPAC_REG_VERIFY'
-                    } );
+            C4::Letters::SendQueuedMessages({ message_id => $message_id });
         }
         else {
             ( $template, $borrowernumber, $cookie ) = get_template_and_user(
@@ -213,8 +217,7 @@ if ( $action eq 'create' ) {
                 }
             );
 
-            $borrower{categorycode}     ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
-            $borrower{password}         ||= Koha::AuthUtils::generate_password;
+            $borrower{password}         ||= Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode}));
             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;
@@ -256,8 +259,8 @@ elsif ( $action eq 'update' ) {
     my %borrower = ParseCgiForBorrower($cgi);
     $borrower{borrowernumber} = $borrowernumber;
 
-    my @empty_mandatory_fields =
-      CheckMandatoryFields( \%borrower, $action );
+    my @empty_mandatory_fields = grep { $_ ne 'password' } # password is not required when editing personal details
+      ( CheckMandatoryFields( \%borrower, $action ), CheckMandatoryAttributes( \%borrower, $attributes ) );
     my $invalidformfields = CheckForInvalidFields(\%borrower);
 
     # Send back the data to the template
@@ -297,6 +300,14 @@ elsif ( $action eq 'update' ) {
             Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete;
 
             my $m = Koha::Patron::Modification->new( \%borrower_changes )->store();
+            #Automatically approve patron profile changes if set in syspref
+
+            if (C4::Context->preference('AutoApprovePatronProfileSettings')) {
+                # Need to get the object from database, otherwise it is not complete enough to allow deletion
+                # when approval has been performed.
+                my $tmp_m = Koha::Patron::Modifications->find({borrowernumber => $borrowernumber});
+                $tmp_m->approve() if $tmp_m;
+            }
 
             my $patron = Koha::Patrons->find( $borrowernumber );
             $template->param( borrower => $patron->unblessed );
@@ -387,7 +398,7 @@ sub GetMandatoryFields {
 
     if ( $action eq 'create' || $action eq 'new' ) {
         $mandatory_fields{'email'} = 1
-          if C4::Context->boolean_preference(
+          if C4::Context->preference(
             'PatronSelfRegistrationVerifyByEmail');
     }
 
@@ -410,6 +421,20 @@ sub CheckMandatoryFields {
     return @empty_mandatory_fields;
 }
 
+sub CheckMandatoryAttributes{
+    my ( $borrower, $attributes ) = @_;
+
+    my @empty_mandatory_fields;
+
+    for my $attribute (@$attributes ) {
+        my $attr = Koha::Patron::Attribute::Types->find($attribute->{code});
+        push @empty_mandatory_fields, $attribute->{code}
+            if $attr && $attr->mandatory && $attribute->{attribute} =~ m|^\s*$|;
+    }
+
+    return @empty_mandatory_fields;
+}
+
 sub CheckForInvalidFields {
     my $borrower = shift;
     my @invalidFields;
@@ -431,7 +456,13 @@ sub CheckForInvalidFields {
             if ( $patrons_with_same_email ) {
                 push @invalidFields, "duplicate_email";
             }
+        } elsif ( C4::Context->preference("PatronSelfRegistrationConfirmEmail")
+            && $borrower->{'email'} ne $borrower->{'repeat_email'}
+            && !defined $borrower->{borrowernumber} ) {
+            push @invalidFields, "email_match";
         }
+        # email passed all tests, so prevent attempting to store repeat_email
+        delete $borrower->{'repeat_email'};
     }
     if ($borrower->{'emailpro'}) {
         push(@invalidFields, "emailpro") if (!Email::Valid->address($borrower->{'emailpro'}));
@@ -445,7 +476,7 @@ sub CheckForInvalidFields {
         push( @invalidFields, "password_match" );
     }
     if ( $borrower->{'password'} ) {
-        my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password} );
+        my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password}, Koha::Patron::Categories->find($borrower->{categorycode}||C4::Context->preference('PatronSelfRegistrationDefaultCategory')) );
           unless ( $is_valid ) {
               push @invalidFields, 'password_too_short' if $error eq 'too_short';
               push @invalidFields, 'password_too_weak' if $error eq 'too_weak';
@@ -474,16 +505,18 @@ sub ParseCgiForBorrower {
         }
     }
 
-    my $dob_dt;
-    $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
-        if ( $borrower{'dateofbirth'} );
+    if ( defined $borrower{'dateofbirth'} ) {
+        my $dob_dt;
+        $dob_dt = eval { dt_from_string( $borrower{'dateofbirth'} ); }
+            if ( $borrower{'dateofbirth'} );
 
-    if ( $dob_dt ) {
-        $borrower{'dateofbirth'} = output_pref ( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
-    }
-    else {
-        # Trigger validation
-        $borrower{'dateofbirth'} = undef;
+        if ( $dob_dt ) {
+            $borrower{'dateofbirth'} = output_pref( { dt => $dob_dt, dateonly => 1, dateformat => 'iso' } );
+        }
+        else {
+            # Trigger validation
+            $borrower{'dateofbirth'} = undef;
+        }
     }
 
     # Replace checkbox 'agreed' by datetime in gdpr_proc_consent
@@ -681,7 +714,8 @@ sub ParsePatronAttributes {
     }
 
     foreach my $code ( keys %{$delete_candidates} ) {
-        if ( Koha::Patron::Attributes->search({
+        if ( not $borrowernumber # self-registration
+            || Koha::Patron::Attributes->search({
                 borrowernumber => $borrowernumber, code => $code })->count > 0 )
         {
             push @attributes, { code => $code, attribute => '' }