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