Bug 28870: Remove traces of Email::Valid
[koha-ffzg.git] / members / memberentry.pl
index cfdc060..eda147c 100755 (executable)
@@ -23,22 +23,20 @@ use Modern::Perl;
 
 # external modules
 use CGI qw ( -utf8 );
-use List::MoreUtils qw/uniq/;
 
 # internal modules
-use C4::Auth;
+use C4::Auth qw( get_template_and_user haspermission );
 use C4::Context;
-use C4::Output;
-use C4::Members;
-use C4::Koha;
-use C4::Log;
-use C4::Letters;
+use C4::Output qw( output_and_exit output_and_exit_if_error output_html_with_http_headers );
+use C4::Members qw( checkcardnumber get_cardnumber_length );
+use C4::Koha qw( GetAuthorisedValues );
+use C4::Letters qw( SendAlerts );
 use C4::Form::MessagingPreferences;
 use Koha::AuthUtils;
 use Koha::AuthorisedValues;
-use Koha::Patron::Debarments;
+use Koha::Patron::Debarments qw( AddDebarment DelDebarment GetDebarments );
 use Koha::Cities;
-use Koha::DateUtils;
+use Koha::DateUtils qw( dt_from_string output_pref );
 use Koha::Libraries;
 use Koha::Patrons;
 use Koha::Patron::Attribute::Types;
@@ -46,17 +44,10 @@ use Koha::Patron::Categories;
 use Koha::Patron::HouseboundRole;
 use Koha::Patron::HouseboundRoles;
 use Koha::Token;
-use Email::Valid;
+use Email::Address;
 use Koha::SMS::Providers;
 
-use vars qw($debug);
-
-BEGIN {
-       $debug = $ENV{DEBUG} || 0;
-}
-       
-my $input = new CGI;
-($debug) or $debug = $input->param('debug') || 0;
+my $input = CGI->new;
 my %data;
 
 my $dbh = C4::Context->dbh;
@@ -65,9 +56,7 @@ my ($template, $loggedinuser, $cookie)
     = get_template_and_user({template_name => "members/memberentrygen.tt",
            query => $input,
            type => "intranet",
-           authnotrequired => 0,
            flagsrequired => {borrowers => 'edit_borrowers'},
-           debug => ($debug) ? 1 : 0,
        });
 
 my $borrowernumber = $input->param('borrowernumber');
@@ -101,12 +90,18 @@ my $step          = $input->param('step') || 0;
 my @errors;
 my $borrower_data;
 my $NoUpdateLogin;
+my $NoUpdateEmail;
 my $userenv = C4::Context->userenv;
 my @messages;
 
 ## Deal with guarantor stuff
 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
 
+my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
+@relations = ('') unless @relations;
+my $empty_relationship_allowed = grep {$_ eq ""} @relations;
+$template->param( empty_relationship_allowed => $empty_relationship_allowed );
+
 my $guarantor_id = $input->param('guarantor_id');
 my $guarantor = undef;
 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
@@ -166,6 +161,11 @@ if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
     my $logged_in_user = Koha::Patrons->find( $loggedinuser );
     output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
 
+    # check permission to modify email info.
+    if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
+        $NoUpdateEmail = 1;
+    }
+
     $borrower_data = $patron->unblessed;
     $borrower_data->{category_type} = $patron->category->category_type;
 }
@@ -201,12 +201,12 @@ if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' )
         if ( $formatteddate ) {
             $newdata{$_} = $formatteddate;
         } else {
-            ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
             $template->param( "ERROR_$_" => 1 );
             push(@errors,"ERROR_$_");
         }
     }
-  # check permission to modify login info.
+
+    # check permission to modify login info.
     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
         $NoUpdateLogin = 1;
     }
@@ -233,7 +233,7 @@ if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' )
         qr/^\d+-DAYS/,
         qr/^patron_attr_/,
         qr/^csrf_token$/,
-        qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
+        qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
         qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
         qr/^select_city$/,
         qr/^new_guarantor_/,
@@ -250,11 +250,10 @@ if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' )
 
 # Test uniqueness of surname, firstname and dateofbirth
 if ( ( $op eq 'insert' ) and !$nodouble ) {
+    my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
     my $conditions;
-    $conditions->{surname} = $newdata{surname} if $newdata{surname};
-    if ( $category_type ne 'I' ) {
-        $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
-        $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
+    for my $f ( @dup_fields ) {
+        $conditions->{$f} = $newdata{$f} if $newdata{$f};
     }
     $nodouble = 1;
     my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
@@ -310,8 +309,7 @@ if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_Borrow
         $newdata{'userid'} = $data{'userid'};
     }
 }
-  
-$debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
+
 my $extended_patron_attributes;
 if ($op eq 'save' || $op eq 'insert'){
 
@@ -354,7 +352,6 @@ if ($op eq 'save' || $op eq 'insert'){
   
   if (C4::Context->preference("IndependentBranches")) {
     unless ( C4::Context->IsSuperLibrarian() ){
-      $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
         push @errors, "ERROR_branch";
       }
@@ -364,7 +361,7 @@ if ($op eq 'save' || $op eq 'insert'){
   # the edited values list when editing certain sub-forms. Get it straight
   # from the DB if absent.
   my $userid = $newdata{ userid } // $borrower_data->{ userid };
-  my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
+  my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
   $p->userid( $userid );
   unless ( $p->has_valid_userid ) {
     push @errors, "ERROR_login_exist";
@@ -375,7 +372,7 @@ if ($op eq 'save' || $op eq 'insert'){
   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
 
   if ( $password and $password ne '****' ) {
-      my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
+      my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, Koha::Patron::Categories->find($categorycode) );
       unless ( $is_valid ) {
           push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
           push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
@@ -389,13 +386,13 @@ if ($op eq 'save' || $op eq 'insert'){
   my $emailalt = $input->param('B_email');
 
   if ($emailprimary) {
-      push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
+      push (@errors, "ERROR_bad_email") if ($emailprimary !~ m/$Email::Address::mailbox/);
   }
   if ($emailsecondary) {
-      push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
+      push (@errors, "ERROR_bad_email_secondary") if ($emailsecondary !~ m/$Email::Address::mailbox/);
   }
   if ($emailalt) {
-      push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
+      push (@errors, "ERROR_bad_email_alternative") if ($emailalt !~ m/$Email::Address::mailbox/);
   }
 
   if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
@@ -403,8 +400,7 @@ if ($op eq 'save' || $op eq 'insert'){
       for my $attr ( @$extended_patron_attributes ) {
           $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
           my $attribute = Koha::Patron::Attribute->new($attr);
-          eval {$attribute->check_unique_id};
-          if ( $@ ) {
+          if ( !$attribute->unique_ok ) {
               push @errors, "ERROR_extended_unique_id_failed";
               my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
               $template->param(
@@ -436,7 +432,6 @@ if ( defined $sms ) {
 ###  Error checks should happen before this line.
 $nok = $nok || scalar(@errors);
 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
-       $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
     my $success;
        if ($op eq 'insert'){
                # we know it's not a duplicate borrowernumber or there would already be an error
@@ -515,8 +510,13 @@ if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
         }
 
         $patron = Koha::Patrons->find( $borrowernumber );
-        $newdata{debarredcomment} = $newdata{debarred_comment};
-        delete $newdata{debarred_comment};
+
+        if ($NoUpdateEmail) {
+            delete $newdata{'email'};
+            delete $newdata{'emailpro'};
+            delete $newdata{'B_email'};
+        }
+
         delete $newdata{password2};
 
         eval {
@@ -646,6 +646,8 @@ if(!defined($data{'sex'})){
     $template->param( female => 1);
 } elsif ($data{'sex'} eq 'M'){
     $template->param(  male => 1);
+} elsif ($data{'sex'} eq 'O') {
+    $template->param( other => 1);
 } else {
     $template->param(  none => 1);
 }
@@ -656,7 +658,7 @@ my @typeloop;
 my $no_categories = 1;
 my $no_add;
 foreach my $category_type (qw(C A S P I X)) {
-    my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
+    my $patron_categories = Koha::Patron::Categories->search_with_library_limits({ category_type => $category_type }, {order_by => ['categorycode']});
     $no_categories = 0 if $patron_categories->count > 0;
 
     my @categoryloop;
@@ -664,6 +666,8 @@ foreach my $category_type (qw(C A S P I X)) {
         push @categoryloop,
           { 'categorycode' => $patron_category->categorycode,
             'categoryname' => $patron_category->description,
+            'effective_min_password_length' => $patron_category->effective_min_password_length,
+            'effective_require_strong_password' => $patron_category->effective_require_strong_password,
             'categorycodeselected' =>
               ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
           };
@@ -684,9 +688,7 @@ $template->param(
 );
 
 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
-my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
 $template->param(
-    roadtypes => $roadtypes,
     cities    => $cities,
 );
 
@@ -803,7 +805,6 @@ if (C4::Context->preference('EnhancedMessagingPreferences')) {
 }
 
 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
-$debug and warn "memberentry step: $step";
 $template->param(%data);
 $template->param( "step_$step"  => 1) if $step;        # associate with step to know where u are
 $template->param(  step  => $step   ) if $step;        # associate with step to know where u are
@@ -827,6 +828,7 @@ $template->param(
   modify          => $modify,
   nok     => $nok,#flag to know if an error
   NoUpdateLogin =>  $NoUpdateLogin,
+  NoUpdateEmail =>  $NoUpdateEmail,
   );
 
 # Generate CSRF token
@@ -909,6 +911,7 @@ sub patron_attributes_form {
             repeatable        => $attr_type->repeatable(),
             category          => $attr_type->authorised_value_category(),
             category_code     => $attr_type->category_code(),
+            mandatory         => $attr_type->mandatory(),
         };
         if (exists $attr_hash{$attr_type->code()}) {
             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
@@ -922,7 +925,7 @@ sub patron_attributes_form {
                 $i++;
                 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
                 $newentry->{form_id} = "patron_attr_$i";
-                push @{$items_by_class{$attr_type->{class}}}, $newentry;
+                push @{$items_by_class{$attr_type->class()}}, $newentry;
             }
         } else {
             $i++;
@@ -935,12 +938,12 @@ sub patron_attributes_form {
             push @{$items_by_class{$attr_type->class()}}, $newentry;
         }
     }
-    while ( my ($class, @items) = each %items_by_class ) {
+    for my $class ( sort keys %items_by_class ) {
         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
         my $lib = $av->count ? $av->next->lib : $class;
         push @attribute_loop, {
             class => $class,
-            items => @items,
+            items => $items_by_class{$class},
             lib   => $lib,
         }
     }