Bug 18747: Select All in Add Patron Option in Patron Lists only selects the first...
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # pragma
22 use Modern::Perl;
23
24 # external modules
25 use CGI qw ( -utf8 );
26 use List::MoreUtils qw/uniq/;
27
28 # internal modules
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Members;
33 use C4::Koha;
34 use C4::Log;
35 use C4::Letters;
36 use C4::Form::MessagingPreferences;
37 use Koha::AuthUtils;
38 use Koha::AuthorisedValues;
39 use Koha::Patron::Debarments;
40 use Koha::Cities;
41 use Koha::DateUtils;
42 use Koha::Libraries;
43 use Koha::Patrons;
44 use Koha::Patron::Attribute::Types;
45 use Koha::Patron::Categories;
46 use Koha::Patron::HouseboundRole;
47 use Koha::Patron::HouseboundRoles;
48 use Koha::Token;
49 use Email::Valid;
50 use Koha::SMS::Providers;
51
52 use vars qw($debug);
53
54 BEGIN {
55         $debug = $ENV{DEBUG} || 0;
56 }
57         
58 my $input = CGI->new;
59 ($debug) or $debug = $input->param('debug') || 0;
60 my %data;
61
62 my $dbh = C4::Context->dbh;
63
64 my ($template, $loggedinuser, $cookie)
65     = get_template_and_user({template_name => "members/memberentrygen.tt",
66            query => $input,
67            type => "intranet",
68            flagsrequired => {borrowers => 'edit_borrowers'},
69            debug => ($debug) ? 1 : 0,
70        });
71
72 my $borrowernumber = $input->param('borrowernumber');
73 my $patron         = Koha::Patrons->find($borrowernumber);
74
75 if ( $borrowernumber and not $patron ) {
76     output_and_exit( $input, $cookie, $template,  'unknown_patron' );
77 }
78
79 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
80     my @providers = Koha::SMS::Providers->search();
81     $template->param( sms_providers => \@providers );
82 }
83
84 my $actionType     = $input->param('actionType') || '';
85 my $modify         = $input->param('modify');
86 my $delete         = $input->param('delete');
87 my $op             = $input->param('op');
88 my $destination    = $input->param('destination');
89 my $cardnumber     = $input->param('cardnumber');
90 my $check_member   = $input->param('check_member');
91 my $nodouble       = $input->param('nodouble');
92 my $duplicate      = $input->param('duplicate');
93 my $quickadd       = $input->param('quickadd');
94 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
95                                      # modifying an existing patron, it ipso facto
96                                      # isn't a duplicate.  Marking FIXME because this
97                                      # script needs to be refactored.
98 my $nok           = $input->param('nok');
99 my $step          = $input->param('step') || 0;
100 my @errors;
101 my $borrower_data;
102 my $NoUpdateLogin;
103 my $NoUpdateEmail;
104 my $userenv = C4::Context->userenv;
105 my @messages;
106
107 ## Deal with guarantor stuff
108 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
109
110 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
111 @relations = ('') unless @relations;
112 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
113 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
114
115 my $guarantor_id = $input->param('guarantor_id');
116 my $guarantor = undef;
117 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
118 $template->param( guarantor => $guarantor );
119
120 my @delete_guarantor = $input->multi_param('delete_guarantor');
121 foreach my $id ( @delete_guarantor ) {
122     my $r = Koha::Patron::Relationships->find( $id );
123     $r->delete() if $r;
124 }
125
126 ## Deal with debarments
127 $template->param(
128     debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
129 my @debarments_to_remove = $input->multi_param('remove_debarment');
130 foreach my $d ( @debarments_to_remove ) {
131     DelDebarment( $d );
132 }
133 if ( $input->param('add_debarment') ) {
134
135     my $expiration = $input->param('debarred_expiration');
136     $expiration =
137       $expiration
138       ? dt_from_string($expiration)->ymd
139       : undef;
140
141     AddDebarment(
142         {
143             borrowernumber => $borrowernumber,
144             type           => 'MANUAL',
145             comment        => scalar $input->param('debarred_comment'),
146             expiration     => $expiration,
147         }
148     );
149 }
150
151 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
152
153 # function to designate mandatory fields (visually with css)
154 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
155 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
156 foreach (@field_check) {
157     $template->param( "mandatory$_" => 1 );
158 }
159 # function to designate unwanted fields
160 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
161 @field_check=split(/\|/,$check_BorrowerUnwantedField);
162 foreach (@field_check) {
163     next unless m/\w/o;
164     $template->param( "no$_" => 1 );
165 }
166 $template->param( "add" => 1 ) if ( $op eq 'add' );
167 $template->param( "quickadd" => 1 ) if ( $quickadd );
168 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
169 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
170 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
171     my $logged_in_user = Koha::Patrons->find( $loggedinuser );
172     output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
173
174     # check permission to modify email info.
175     if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
176         $NoUpdateEmail = 1;
177     }
178
179     $borrower_data = $patron->unblessed;
180     $borrower_data->{category_type} = $patron->category->category_type;
181 }
182
183 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
184 my $category_type = $input->param('category_type') || '';
185 unless ($category_type or !($categorycode)){
186     my $borrowercategory = Koha::Patron::Categories->find($categorycode);
187     $category_type    = $borrowercategory->category_type;
188     my $category_name = $borrowercategory->description;
189     $template->param("categoryname"=>$category_name);
190 }
191 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
192
193 # if a add or modify is requested => check validity of data.
194 %data = %$borrower_data if ($borrower_data);
195
196 # initialize %newdata
197 my %newdata;                                                                             # comes from $input->param()
198 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
199     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
200     foreach my $key (@names) {
201         if (defined $input->param($key)) {
202             $newdata{$key} = $input->param($key);
203         }
204     }
205
206     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
207         next unless exists $newdata{$_};
208         my $userdate = $newdata{$_} or next;
209
210         my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
211         if ( $formatteddate ) {
212             $newdata{$_} = $formatteddate;
213         } else {
214             $template->param( "ERROR_$_" => 1 );
215             push(@errors,"ERROR_$_");
216         }
217     }
218
219     # check permission to modify login info.
220     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
221         $NoUpdateLogin = 1;
222     }
223 }
224
225 # remove keys from %newdata that is not part of patron's attributes
226 {
227     my @keys_to_delete = (
228         qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|privacy_guarantor_fines|privacy_guarantor_checkouts|checkprevcheckout|updated_on|lastseen|lang|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
229         qr/^BorrowerMandatoryField$/,
230         qr/^category_type$/,
231         qr/^check_member$/,
232         qr/^destination$/,
233         qr/^nodouble$/,
234         qr/^op$/,
235         qr/^save$/,
236         qr/^updtype$/,
237         qr/^SMSnumber$/,
238         qr/^setting_extended_patron_attributes$/,
239         qr/^setting_messaging_prefs$/,
240         qr/^digest$/,
241         qr/^modify$/,
242         qr/^step$/,
243         qr/^\d+$/,
244         qr/^\d+-DAYS/,
245         qr/^patron_attr_/,
246         qr/^csrf_token$/,
247         qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
248         qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
249         qr/^select_city$/,
250         qr/^new_guarantor_/,
251         qr/^guarantor_firstname$/,
252         qr/^guarantor_surname$/,
253         qr/^delete_guarantor$/,
254     );
255     push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
256     for my $regexp (@keys_to_delete) {
257         for (keys %newdata) {
258             delete($newdata{$_}) if /$regexp/;
259         }
260     }
261 }
262
263 # Test uniqueness of surname, firstname and dateofbirth
264 if ( ( $op eq 'insert' ) and !$nodouble ) {
265     my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
266     my $conditions;
267     for my $f ( @dup_fields ) {
268         $conditions->{$f} = $newdata{$f} if $newdata{$f};
269     }
270     $nodouble = 1;
271     my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
272     if ( $patrons->count > 0) {
273         $nodouble = 0;
274         $check_member = $patrons->next->borrowernumber;
275
276
277         my @new_guarantors;
278         my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
279         my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
280         foreach my $gid ( @new_guarantor_id ) {
281             my $patron = Koha::Patrons->find( $gid );
282             my $relationship = shift( @new_guarantor_relationship );
283             next unless $patron;
284             my $g = { patron => $patron, relationship => $relationship };
285             push( @new_guarantors, $g );
286         }
287         $template->param( new_guarantors => \@new_guarantors );
288     }
289 }
290
291 ###############test to take the right zipcode, country and city name ##############
292 # set only if parameter was passed from the form
293 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
294 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
295 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
296
297 $newdata{'lang'}    = $input->param('lang')    if defined($input->param('lang'));
298
299 # builds default userid
300 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
301 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
302     my $fake_patron = Koha::Patron->new;
303     $fake_patron->userid($patron->userid) if $patron; # editing
304     if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
305         # Full page edit, firstname and surname input zones are present
306         $fake_patron->firstname($newdata{firstname});
307         $fake_patron->surname($newdata{surname});
308         $fake_patron->generate_userid;
309         $newdata{'userid'} = $fake_patron->userid;
310     }
311     elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
312         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
313         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
314         # FIXME clean thiscode newdata vs data is very confusing
315         $fake_patron->firstname($data{firstname});
316         $fake_patron->surname($data{surname});
317         $fake_patron->generate_userid;
318         $newdata{'userid'} = $fake_patron->userid;
319     }
320     else {
321         $newdata{'userid'} = $data{'userid'};
322     }
323 }
324   
325 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
326 my $extended_patron_attributes;
327 if ($op eq 'save' || $op eq 'insert'){
328
329     output_and_exit( $input, $cookie, $template,  'wrong_csrf_token' )
330         unless Koha::Token->new->check_csrf({
331             session_id => scalar $input->cookie('CGISESSID'),
332             token  => scalar $input->param('csrf_token'),
333         });
334
335     # If the cardnumber is blank, treat it as null.
336     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
337
338     if (my $error_code = checkcardnumber( $newdata{cardnumber}, $borrowernumber )){
339         push @errors, $error_code == 1
340             ? 'ERROR_cardnumber_already_exists'
341             : $error_code == 2
342                 ? 'ERROR_cardnumber_length'
343                 : ()
344     }
345
346     my $dateofbirth;
347     if ($op eq 'save' && $step == 3) {
348         $dateofbirth = $patron->dateofbirth;
349     }
350     else {
351         $dateofbirth = $newdata{dateofbirth};
352     }
353
354     if ( $dateofbirth ) {
355         my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
356         my $age = $patron->get_age;
357         my $borrowercategory = Koha::Patron::Categories->find($categorycode);
358         my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
359         if (($high && ($age > $high)) or ($age < $low)) {
360             push @errors, 'ERROR_age_limitations';
361             $template->param( age_low => $low);
362             $template->param( age_high => $high);
363         }
364     }
365   
366   if (C4::Context->preference("IndependentBranches")) {
367     unless ( C4::Context->IsSuperLibrarian() ){
368       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
369       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
370         push @errors, "ERROR_branch";
371       }
372     }
373   }
374   # Check if the 'userid' is unique. 'userid' might not always be present in
375   # the edited values list when editing certain sub-forms. Get it straight
376   # from the DB if absent.
377   my $userid = $newdata{ userid } // $borrower_data->{ userid };
378   my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
379   $p->userid( $userid );
380   unless ( $p->has_valid_userid ) {
381     push @errors, "ERROR_login_exist";
382   }
383
384   my $password = $input->param('password');
385   my $password2 = $input->param('password2');
386   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
387
388   if ( $password and $password ne '****' ) {
389       my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, Koha::Patron::Categories->find($categorycode) );
390       unless ( $is_valid ) {
391           push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
392           push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
393           push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
394       }
395   }
396
397   # Validate emails
398   my $emailprimary = $input->param('email');
399   my $emailsecondary = $input->param('emailpro');
400   my $emailalt = $input->param('B_email');
401
402   if ($emailprimary) {
403       push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
404   }
405   if ($emailsecondary) {
406       push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
407   }
408   if ($emailalt) {
409       push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
410   }
411
412   if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
413       $extended_patron_attributes = parse_extended_patron_attributes($input);
414       for my $attr ( @$extended_patron_attributes ) {
415           $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
416           my $attribute = Koha::Patron::Attribute->new($attr);
417           eval {$attribute->check_unique_id};
418           if ( $@ ) {
419               push @errors, "ERROR_extended_unique_id_failed";
420               my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
421               $template->param(
422                   ERROR_extended_unique_id_failed_code => $attr->{code},
423                   ERROR_extended_unique_id_failed_value => $attr->{attribute},
424                   ERROR_extended_unique_id_failed_description => $attr_type->description()
425               );
426           }
427       }
428   }
429 }
430 elsif ( $borrowernumber ) {
431     $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
432 }
433
434 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
435     unless ($newdata{'dateexpiry'}){
436         my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
437         $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
438     }
439 }
440
441 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
442 my $sms = $input->param('SMSnumber');
443 if ( defined $sms ) {
444     $newdata{smsalertnumber} = $sms;
445 }
446
447 ###  Error checks should happen before this line.
448 $nok = $nok || scalar(@errors);
449 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
450         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
451     my $success;
452         if ($op eq 'insert'){
453                 # we know it's not a duplicate borrowernumber or there would already be an error
454         delete $newdata{password2};
455         $patron = eval { Koha::Patron->new(\%newdata)->store };
456         if ( $@ ) {
457             # FIXME Urgent error handling here, we cannot fail without relevant feedback
458             # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
459             warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
460             push @messages, {error => 'error_on_insert_patron'};
461             $op = "add";
462         } else {
463             $success = 1;
464             add_guarantors( $patron, $input );
465             $borrowernumber = $patron->borrowernumber;
466             $newdata{'borrowernumber'} = $borrowernumber;
467         }
468
469         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
470         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
471             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
472             my $emailaddr;
473             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
474                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
475                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
476             } 
477             elsif ($newdata{email} =~ /\w\@\w/) {
478                 $emailaddr = $newdata{email} 
479             }
480             elsif ($newdata{emailpro} =~ /\w\@\w/) {
481                 $emailaddr = $newdata{emailpro} 
482             }
483             elsif ($newdata{B_email} =~ /\w\@\w/) {
484                 $emailaddr = $newdata{B_email} 
485             }
486             # if we manage to find a valid email address, send notice 
487             if ($emailaddr) {
488                 $newdata{emailaddr} = $emailaddr;
489                 my $err;
490                 eval {
491                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
492                 };
493                 if ( $@ ) {
494                     $template->param(error_alert => $@);
495                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
496                     $template->{VARS}->{'error_alert'} = "no_email";
497                 } else {
498                     $template->{VARS}->{'info_alert'} = 1;
499                 }
500             }
501         }
502
503         if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
504             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
505         }
506
507         # Create HouseboundRole if necessary.
508         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
509         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
510         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
511         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
512         # Only create a HouseboundRole if patron has a role.
513         if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
514             Koha::Patron::HouseboundRole->new({
515                 borrowernumber_id    => $borrowernumber,
516                 housebound_chooser   => $hsbnd_chooser,
517                 housebound_deliverer => $hsbnd_deliverer,
518             })->store;
519         }
520
521     } elsif ($op eq 'save') {
522
523         if ($NoUpdateLogin) {
524             delete $newdata{'password'};
525             delete $newdata{'userid'};
526         }
527
528         $patron = Koha::Patrons->find( $borrowernumber );
529
530         if ($NoUpdateEmail) {
531             delete $newdata{'email'};
532             delete $newdata{'emailpro'};
533             delete $newdata{'B_email'};
534         }
535
536         delete $newdata{password2};
537
538         eval {
539             $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
540                                                                     # updating any columns in the borrowers table,
541                                                                     # which can happen if we're only editing the
542                                                                     # patron attributes or messaging preferences sections
543         };
544         if ( $@ ) {
545             warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
546             push @messages, {error => 'error_on_update_patron'};
547             $op = "modify";
548         } else {
549
550             $success = 1;
551             # Update or create our HouseboundRole if necessary.
552             my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
553             my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
554             $hsbnd_chooser = 1 if $input->param('housebound_chooser');
555             $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
556             if ( $housebound_role ) {
557                 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
558                     # Update our HouseboundRole.
559                     $housebound_role
560                         ->housebound_chooser($hsbnd_chooser)
561                         ->housebound_deliverer($hsbnd_deliverer)
562                         ->store;
563                 } else {
564                     $housebound_role->delete; # No longer needed.
565                 }
566             } else {
567                 # Only create a HouseboundRole if patron has a role.
568                 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
569                     $housebound_role = Koha::Patron::HouseboundRole->new({
570                         borrowernumber_id    => $borrowernumber,
571                         housebound_chooser   => $hsbnd_chooser,
572                         housebound_deliverer => $hsbnd_deliverer,
573                     })->store;
574                 }
575             }
576
577             # should never raise an exception as password validity is checked above
578             my $password = $newdata{password};
579             if ( $password and $password ne '****' ) {
580                 $patron->set_password({ password => $password });
581             }
582
583             add_guarantors( $patron, $input );
584             if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
585                 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
586             }
587         }
588     }
589
590     if ( $success ) {
591         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
592             $patron->extended_attributes->filter_by_branch_limitations->delete;
593             $patron->extended_attributes($extended_patron_attributes);
594         }
595
596         if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
597             # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
598             $destination = 'not_circ';
599         }
600         print scalar( $destination eq "circ" )
601           ? $input->redirect(
602             "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
603           : $input->redirect(
604             "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
605           );
606         exit; # You can only send 1 redirect!  After that, content or other headers don't matter.
607     }
608 }
609
610 if ($delete){
611         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
612         exit;           # same as above
613 }
614
615 if ($nok or !$nodouble){
616     $op="add" if ($op eq "insert");
617     $op="modify" if ($op eq "save");
618     %data=%newdata; 
619     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
620     unless ($step){  
621         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
622     }  
623
624 if (C4::Context->preference("IndependentBranches")) {
625     my $userenv = C4::Context->userenv;
626     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
627         unless ($userenv->{branch} eq $data{'branchcode'}){
628             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
629             exit;
630         }
631     }
632 }
633
634 # Define the fields to be pre-filled in guarantee records
635 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
636 my @prefill_fields=split(/\,/,$prefillguarantorfields);
637
638 if ($op eq 'add'){
639     if ($guarantor_id) {
640         foreach (@prefill_fields) {
641             $newdata{$_} = $guarantor->$_;
642         }
643     }
644     $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1);
645 }
646 if ($op eq "modify")  {
647     $template->param( updtype => 'M',modify => 1 );
648     $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1) unless $step;
649     if ( $step == 4 ) {
650         $template->param( categorycode => $borrower_data->{'categorycode'} );
651     }
652 }
653 if ( $op eq "duplicate" ) {
654     $template->param( updtype => 'I' );
655     $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 ) unless $step;
656     $data{'cardnumber'} = "";
657 }
658
659 if(!defined($data{'sex'})){
660     $template->param( none => 1);
661 } elsif($data{'sex'} eq 'F'){
662     $template->param( female => 1);
663 } elsif ($data{'sex'} eq 'M'){
664     $template->param(  male => 1);
665 } elsif ($data{'sex'} eq 'O') {
666     $template->param( other => 1);
667 } else {
668     $template->param(  none => 1);
669 }
670
671 ##Now all the data to modify a member.
672
673 my @typeloop;
674 my $no_categories = 1;
675 my $no_add;
676 foreach my $category_type (qw(C A S P I X)) {
677     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
678     $no_categories = 0 if $patron_categories->count > 0;
679
680     my @categoryloop;
681     while ( my $patron_category = $patron_categories->next ) {
682         push @categoryloop,
683           { 'categorycode' => $patron_category->categorycode,
684             'categoryname' => $patron_category->description,
685             'effective_min_password_length' => $patron_category->effective_min_password_length,
686             'effective_require_strong_password' => $patron_category->effective_require_strong_password,
687             'categorycodeselected' =>
688               ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
689           };
690     }
691     my %typehash;
692     $typehash{'typename'} = $category_type;
693     my $typedescription = "typename_" . $typehash{'typename'};
694     $typehash{'categoryloop'} = \@categoryloop;
695     push @typeloop,
696       { 'typename'       => $category_type,
697         $typedescription => 1,
698         'categoryloop'   => \@categoryloop
699       };
700 }
701 $template->param(
702     typeloop      => \@typeloop,
703     no_categories => $no_categories,
704 );
705
706 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
707 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
708 $template->param(
709     roadtypes => $roadtypes,
710     cities    => $cities,
711 );
712
713 my $default_borrowertitle = '';
714 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
715
716 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
717 my @relshipdata;
718 while (@relationships) {
719   my $relship = shift @relationships || '';
720   my %row = ('relationship' => $relship);
721   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
722     $row{'selected'}=' selected';
723   } else {
724     $row{'selected'}='';
725   }
726   push(@relshipdata, \%row);
727 }
728
729 my %flags = (
730     'gonenoaddress' => ['gonenoaddress'],
731     'lost'          => ['lost']
732 );
733
734 my @flagdata;
735 foreach ( keys(%flags) ) {
736     my $key = $_;
737     my %row = (
738         'key'  => $key,
739         'name' => $flags{$key}[0]
740     );
741     if ( $data{$key} ) {
742         $row{'yes'} = ' checked';
743         $row{'no'}  = '';
744     }
745     else {
746         $row{'yes'} = '';
747         $row{'no'}  = ' checked';
748     }
749     push @flagdata, \%row;
750 }
751
752 # get Branch Loop
753 # in modify mod: userbranch value comes from borrowers table
754 # in add    mod: userbranch value comes from branches table (ip correspondence)
755
756 my $userbranch = '';
757 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
758     $userbranch = C4::Context->userenv->{'branch'};
759 }
760
761 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
762     $userbranch = $data{'branchcode'};
763 }
764 $template->param( userbranch => $userbranch );
765
766 if ( Koha::Libraries->search->count < 1 ){
767     $no_add = 1;
768     $template->param(no_branches => 1);
769 }
770 if($no_categories){
771     $no_add = 1;
772     $template->param(no_categories => 1);
773 }
774 $template->param(no_add => $no_add);
775 # --------------------------------------------------------------------------------------------------------
776
777 $template->param( sort1 => $data{'sort1'});
778 $template->param( sort2 => $data{'sort2'});
779 $template->param( autorenew => $data{'autorenew'});
780
781 if ($nok) {
782     foreach my $error (@errors) {
783         $template->param($error) || $template->param( $error => 1);
784     }
785     $template->param(nok => 1);
786 }
787   
788   #Formatting data for display    
789   
790 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
791   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
792 }
793 if ( $op eq 'duplicate' ) {
794     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
795     my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
796     $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
797 }
798 if (C4::Context->preference('uppercasesurnames')) {
799     $data{'surname'} &&= uc( $data{'surname'} );
800     $data{'contactname'} &&= uc( $data{'contactname'} );
801 }
802
803 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
804     if ( $data{$_} ) {
805        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
806     }
807     $template->param( $_ => $data{$_});
808 }
809
810 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
811     patron_attributes_form( $template, $extended_patron_attributes, $op );
812 }
813
814 if (C4::Context->preference('EnhancedMessagingPreferences')) {
815     if ($op eq 'add') {
816         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
817     } else {
818         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
819     }
820     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
821     $template->param(SMSnumber     => $data{'smsalertnumber'} );
822     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
823 }
824
825 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
826 $debug and warn "memberentry step: $step";
827 $template->param(%data);
828 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
829 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
830
831 $template->param(
832   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
833   category_type => $category_type,#to know the category type of the borrower
834   "$category_type"  => 1,# associate with step to know where u are
835   destination   => $destination,#to know wher u come from and wher u must go in redirect
836   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
837   "op$op"   => 1);
838
839 $template->param(
840   patron => $patron ? $patron : \%newdata, # Used by address include templates now
841   nodouble  => $nodouble,
842   borrowernumber  => $borrowernumber, #register number
843   relshiploop => \@relshipdata,
844   btitle=> $default_borrowertitle,
845   flagloop  => \@flagdata,
846   category_type =>$category_type,
847   modify          => $modify,
848   nok     => $nok,#flag to know if an error
849   NoUpdateLogin =>  $NoUpdateLogin,
850   NoUpdateEmail =>  $NoUpdateEmail,
851   );
852
853 # Generate CSRF token
854 $template->param( csrf_token =>
855       Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
856 );
857
858 # HouseboundModule data
859 $template->param(
860     housebound_role  => Koha::Patron::HouseboundRoles->find($borrowernumber),
861 );
862
863 if(defined($data{'flags'})){
864   $template->param(flags=>$data{'flags'});
865 }
866 if(defined($data{'contacttitle'})){
867   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
868 }
869
870
871 my ( $min, $max ) = C4::Members::get_cardnumber_length();
872 if ( defined $min ) {
873     $template->param(
874         minlength_cardnumber => $min,
875         maxlength_cardnumber => $max
876     );
877 }
878
879 if ( C4::Context->preference('TranslateNotices') ) {
880     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
881     $template->param( languages => $translated_languages );
882 }
883
884 $template->param( messages => \@messages );
885 output_html_with_http_headers $input, $cookie, $template->output;
886
887 sub parse_extended_patron_attributes {
888     my ($input) = @_;
889     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
890
891     my @attr = ();
892     my %dups = ();
893     foreach my $key (@patron_attr) {
894         my $value = $input->param($key);
895         next unless defined($value) and $value ne '';
896         my $code     = $input->param("${key}_code");
897         next if exists $dups{$code}->{$value};
898         $dups{$code}->{$value} = 1;
899         push @attr, { code => $code, attribute => $value };
900     }
901     return \@attr;
902 }
903
904 sub patron_attributes_form {
905     my $template = shift;
906     my $attributes = shift;
907     my $op = shift;
908
909     my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
910     my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
911     if ( $attribute_types->count == 0 ) {
912         $template->param(no_patron_attribute_types => 1);
913         return;
914     }
915
916     # map patron's attributes into a more convenient structure
917     my %attr_hash = ();
918     foreach my $attr (@$attributes) {
919         push @{ $attr_hash{$attr->{code}} }, $attr;
920     }
921
922     my @attribute_loop = ();
923     my $i = 0;
924     my %items_by_class;
925     while ( my ( $attr_type ) = $attribute_types->next ) {
926         my $entry = {
927             class             => $attr_type->class(),
928             code              => $attr_type->code(),
929             description       => $attr_type->description(),
930             repeatable        => $attr_type->repeatable(),
931             category          => $attr_type->authorised_value_category(),
932             category_code     => $attr_type->category_code(),
933             mandatory         => $attr_type->mandatory(),
934         };
935         if (exists $attr_hash{$attr_type->code()}) {
936             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
937                 my $newentry = { %$entry };
938                 $newentry->{value} = $attr->{attribute};
939                 $newentry->{use_dropdown} = 0;
940                 if ($attr_type->authorised_value_category()) {
941                     $newentry->{use_dropdown} = 1;
942                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
943                 }
944                 $i++;
945                 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
946                 $newentry->{form_id} = "patron_attr_$i";
947                 push @{$items_by_class{$attr_type->class()}}, $newentry;
948             }
949         } else {
950             $i++;
951             my $newentry = { %$entry };
952             if ($attr_type->authorised_value_category()) {
953                 $newentry->{use_dropdown} = 1;
954                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
955             }
956             $newentry->{form_id} = "patron_attr_$i";
957             push @{$items_by_class{$attr_type->class()}}, $newentry;
958         }
959     }
960     for my $class ( sort keys %items_by_class ) {
961         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
962         my $lib = $av->count ? $av->next->lib : $class;
963         push @attribute_loop, {
964             class => $class,
965             items => $items_by_class{$class},
966             lib   => $lib,
967         }
968     }
969
970     $template->param(patron_attributes => \@attribute_loop);
971
972 }
973
974 sub add_guarantors {
975     my ( $patron, $input ) = @_;
976
977     my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
978     my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
979
980     for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
981         my $guarantor_id = $new_guarantor_id[$i];
982         my $relationship = $new_guarantor_relationship[$i];
983
984         next unless $guarantor_id;
985
986         $patron->add_guarantor(
987             {
988                 guarantor_id => $guarantor_id,
989                 relationship => $relationship,
990             }
991         );
992     }
993 }
994
995 # Local Variables:
996 # tab-width: 8
997 # End: