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