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