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