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