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