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