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