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