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