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