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