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