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