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