Bug 17829: Move GetMember to Koha::Patron
[koha-equinox.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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # pragma
22 use strict;
23 use warnings;
24
25 # external modules
26 use CGI qw ( -utf8 );
27 use List::MoreUtils qw/uniq/;
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::Log;
38 use C4::Letters;
39 use C4::Form::MessagingPreferences;
40 use Koha::AuthorisedValues;
41 use Koha::Patron::Debarments;
42 use Koha::Cities;
43 use Koha::DateUtils;
44 use Koha::Libraries;
45 use Koha::Patrons;
46 use Koha::Patron::Categories;
47 use Koha::Patron::HouseboundRole;
48 use Koha::Patron::HouseboundRoles;
49 use Koha::Token;
50 use Email::Valid;
51 use Module::Load;
52 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
53     load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
54 }
55 use Koha::SMS::Providers;
56
57 use vars qw($debug);
58
59 BEGIN {
60         $debug = $ENV{DEBUG} || 0;
61 }
62         
63 my $input = new CGI;
64 ($debug) or $debug = $input->param('debug') || 0;
65 my %data;
66
67 my $dbh = C4::Context->dbh;
68
69 my ($template, $loggedinuser, $cookie)
70     = get_template_and_user({template_name => "members/memberentrygen.tt",
71            query => $input,
72            type => "intranet",
73            authnotrequired => 0,
74            flagsrequired => {borrowers => 1},
75            debug => ($debug) ? 1 : 0,
76        });
77
78 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
79     my @providers = Koha::SMS::Providers->search();
80     $template->param( sms_providers => \@providers );
81 }
82
83 my $guarantorid    = $input->param('guarantorid');
84 my $borrowernumber = $input->param('borrowernumber');
85 my $actionType     = $input->param('actionType') || '';
86 my $modify         = $input->param('modify');
87 my $delete         = $input->param('delete');
88 my $op             = $input->param('op');
89 my $destination    = $input->param('destination');
90 my $cardnumber     = $input->param('cardnumber');
91 my $check_member   = $input->param('check_member');
92 my $nodouble       = $input->param('nodouble');
93 my $duplicate      = $input->param('duplicate');
94 my $quickadd       = $input->param('quickadd');
95 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
96                                      # modifying an existing patron, it ipso facto
97                                      # isn't a duplicate.  Marking FIXME because this
98                                      # script needs to be refactored.
99 my $nok           = $input->param('nok');
100 my $guarantorinfo = $input->param('guarantorinfo');
101 my $step          = $input->param('step') || 0;
102 my @errors;
103 my $borrower_data;
104 my $NoUpdateLogin;
105 my $userenv = C4::Context->userenv;
106
107
108 ## Deal with debarments
109 $template->param(
110     debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
111 my @debarments_to_remove = $input->multi_param('remove_debarment');
112 foreach my $d ( @debarments_to_remove ) {
113     DelDebarment( $d );
114 }
115 if ( $input->param('add_debarment') ) {
116
117     my $expiration = $input->param('debarred_expiration');
118     $expiration =
119       $expiration
120       ? output_pref(
121         { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
122       : undef;
123
124     AddDebarment(
125         {
126             borrowernumber => $borrowernumber,
127             type           => 'MANUAL',
128             comment        => scalar $input->param('debarred_comment'),
129             expiration     => $expiration,
130         }
131     );
132 }
133
134 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
135
136 my $minpw = C4::Context->preference('minPasswordLength');
137 $template->param("minPasswordLength" => $minpw);
138
139 # function to designate mandatory fields (visually with css)
140 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
141 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
142 foreach (@field_check) {
143         $template->param( "mandatory$_" => 1);    
144 }
145 # function to designate unwanted fields
146 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
147 @field_check=split(/\|/,$check_BorrowerUnwantedField);
148 foreach (@field_check) {
149     next unless m/\w/o;
150         $template->param( "no$_" => 1);
151 }
152 $template->param( "add" => 1 ) if ( $op eq 'add' );
153 $template->param( "quickadd" => 1 ) if ( $quickadd );
154 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
155 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
156 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
157     my $patron = Koha::Patrons->find( $borrowernumber );
158     $borrower_data = $patron->unblessed;
159     $borrower_data->{category_type} = $patron->category->category_type;
160 }
161 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
162 my $category_type = $input->param('category_type') || '';
163 unless ($category_type or !($categorycode)){
164     my $borrowercategory = Koha::Patron::Categories->find($categorycode);
165     $category_type    = $borrowercategory->category_type;
166     my $category_name = $borrowercategory->description;
167     $template->param("categoryname"=>$category_name);
168 }
169 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
170
171 # if a add or modify is requested => check validity of data.
172 %data = %$borrower_data if ($borrower_data);
173
174 # initialize %newdata
175 my %newdata;                                                                             # comes from $input->param()
176 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
177     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
178     foreach my $key (@names) {
179         if (defined $input->param($key)) {
180             $newdata{$key} = $input->param($key);
181             $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
182         }
183     }
184
185     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
186         next unless exists $newdata{$_};
187         my $userdate = $newdata{$_} or next;
188
189         my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
190         if ( $formatteddate ) {
191             $newdata{$_} = $formatteddate;
192         } else {
193             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
194             $template->param( "ERROR_$_" => 1 );
195             push(@errors,"ERROR_$_");
196         }
197     }
198   # check permission to modify login info.
199     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
200         $NoUpdateLogin = 1;
201     }
202 }
203
204 # remove keys from %newdata that ModMember() doesn't like
205 {
206     my @keys_to_delete = (
207         qr/^BorrowerMandatoryField$/,
208         qr/^category_type$/,
209         qr/^check_member$/,
210         qr/^destination$/,
211         qr/^nodouble$/,
212         qr/^op$/,
213         qr/^save$/,
214         qr/^updtype$/,
215         qr/^SMSnumber$/,
216         qr/^setting_extended_patron_attributes$/,
217         qr/^setting_messaging_prefs$/,
218         qr/^digest$/,
219         qr/^modify$/,
220         qr/^step$/,
221         qr/^\d+$/,
222         qr/^\d+-DAYS/,
223         qr/^patron_attr_/,
224     );
225     for my $regexp (@keys_to_delete) {
226         for (keys %newdata) {
227             delete($newdata{$_}) if /$regexp/;
228         }
229     }
230 }
231
232 # Test uniqueness of surname, firstname and dateofbirth
233 if ( ( $op eq 'insert' ) and !$nodouble ) {
234     my $conditions;
235     $conditions->{surname} = $newdata{surname} if $newdata{surname};
236     if ( $category_type ne 'I' ) {
237         $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
238         $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
239     }
240     $nodouble = 1;
241     my $patrons = Koha::Patrons->search($conditions);
242     if ( $patrons->count > 0) {
243         $nodouble = 0;
244         $check_member = $patrons->next->borrowernumber;
245     }
246 }
247
248   #recover all data from guarantor address phone ,fax... 
249 if ( $guarantorid ) {
250     if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
251         my $guarantordata = $guarantor->unblessed;
252         $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
253         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
254         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
255         $newdata{'contactname'}     = $guarantordata->{'surname'};
256         $newdata{'contacttitle'}    = $guarantordata->{'title'};
257         if ( $op eq 'add' ) {
258                 foreach (qw(streetnumber address streettype address2
259                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
260                         B_streetnumber B_streettype B_address B_address2
261                         B_city B_state B_zipcode B_country B_email B_phone)) {
262                         $newdata{$_} = $guarantordata->{$_};
263                 }
264         }
265     }
266 }
267
268 ###############test to take the right zipcode, country and city name ##############
269 # set only if parameter was passed from the form
270 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
271 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
272 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
273
274 $newdata{'lang'}    = $input->param('lang')    if defined($input->param('lang'));
275
276 # builds default userid
277 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
278 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
279     if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
280         # Full page edit, firstname and surname input zones are present
281         $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
282     }
283     elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
284         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
285         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
286         $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
287     }
288     else {
289         $newdata{'userid'} = $data{'userid'};
290     }
291 }
292   
293 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
294 my $extended_patron_attributes = ();
295 if ($op eq 'save' || $op eq 'insert'){
296
297     die "Wrong CSRF token"
298         unless Koha::Token->new->check_csrf({
299             session_id => scalar $input->cookie('CGISESSID'),
300             token  => scalar $input->param('csrf_token'),
301         });
302
303     # If the cardnumber is blank, treat it as null.
304     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
305
306     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
307         push @errors, $error_code == 1
308             ? 'ERROR_cardnumber_already_exists'
309             : $error_code == 2
310                 ? 'ERROR_cardnumber_length'
311                 : ()
312     }
313
314     my $dateofbirth;
315     if ($op eq 'save' && $step == 3) {
316         my $patron = Koha::Patrons->find( $borrowernumber );
317         $dateofbirth = $patron->dateofbirth;
318     }
319     else {
320         $dateofbirth = $newdata{dateofbirth};
321     }
322
323     if ( $dateofbirth ) {
324         my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
325         my $age = $patron->get_age;
326         my $borrowercategory = Koha::Patron::Categories->find($categorycode);
327         my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
328         if (($high && ($age > $high)) or ($age < $low)) {
329             push @errors, 'ERROR_age_limitations';
330             $template->param( age_low => $low);
331             $template->param( age_high => $high);
332         }
333     }
334   
335     if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
336         $newdata{'surname'} = uc($newdata{'surname'});
337     }
338
339   if (C4::Context->preference("IndependentBranches")) {
340     unless ( C4::Context->IsSuperLibrarian() ){
341       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
342       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
343         push @errors, "ERROR_branch";
344       }
345     }
346   }
347   # Check if the 'userid' is unique. 'userid' might not always be present in
348   # the edited values list when editing certain sub-forms. Get it straight
349   # from the DB if absent.
350   my $userid = $newdata{ userid } // $borrower_data->{ userid };
351   unless (Check_Userid($userid,$borrowernumber)) {
352     push @errors, "ERROR_login_exist";
353   }
354   
355   my $password = $input->param('password');
356   my $password2 = $input->param('password2');
357   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
358   push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
359
360   # Validate emails
361   my $emailprimary = $input->param('email');
362   my $emailsecondary = $input->param('emailpro');
363   my $emailalt = $input->param('B_email');
364
365   if ($emailprimary) {
366       push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
367   }
368   if ($emailsecondary) {
369       push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
370   }
371   if ($emailalt) {
372       push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
373   }
374
375   if (C4::Context->preference('ExtendedPatronAttributes')) {
376     $extended_patron_attributes = parse_extended_patron_attributes($input);
377     foreach my $attr (@$extended_patron_attributes) {
378         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
379             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
380             push @errors, "ERROR_extended_unique_id_failed";
381             $template->param(
382                 ERROR_extended_unique_id_failed_code => $attr->{code},
383                 ERROR_extended_unique_id_failed_value => $attr->{value},
384                 ERROR_extended_unique_id_failed_description => $attr_info->description()
385             );
386         }
387     }
388   }
389 }
390
391 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
392     unless ($newdata{'dateexpiry'}){
393         my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
394         $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
395     }
396 }
397
398 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
399 my $sms = $input->param('SMSnumber');
400 if ( defined $sms ) {
401     $newdata{smsalertnumber} = $sms;
402 }
403
404 ###  Error checks should happen before this line.
405 $nok = $nok || scalar(@errors);
406 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
407         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
408         if ($op eq 'insert'){
409                 # we know it's not a duplicate borrowernumber or there would already be an error
410         $borrowernumber = &AddMember(%newdata);
411         $newdata{'borrowernumber'} = $borrowernumber;
412
413         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
414         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
415             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
416             my $emailaddr;
417             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
418                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
419                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
420             } 
421             elsif ($newdata{email} =~ /\w\@\w/) {
422                 $emailaddr = $newdata{email} 
423             }
424             elsif ($newdata{emailpro} =~ /\w\@\w/) {
425                 $emailaddr = $newdata{emailpro} 
426             }
427             elsif ($newdata{B_email} =~ /\w\@\w/) {
428                 $emailaddr = $newdata{B_email} 
429             }
430             # if we manage to find a valid email address, send notice 
431             if ($emailaddr) {
432                 $newdata{emailaddr} = $emailaddr;
433                 my $err;
434                 eval {
435                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
436                 };
437                 if ( $@ ) {
438                     $template->param(error_alert => $@);
439                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
440                     $template->{VARS}->{'error_alert'} = "no_email";
441                 } else {
442                     $template->{VARS}->{'info_alert'} = 1;
443                 }
444             }
445         }
446
447         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
448             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
449         }
450         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
451             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
452         }
453         # Try to do the live sync with the Norwegian national patron database, if it is enabled
454         if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
455             NLSync({ 'borrowernumber' => $borrowernumber });
456         }
457
458         # Create HouseboundRole if necessary.
459         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
460         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
461         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
462         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
463         # Only create a HouseboundRole if patron has a role.
464         if ( $hsbnd_chooser || $hsbnd_deliverer ) {
465             Koha::Patron::HouseboundRole->new({
466                 borrowernumber_id    => $borrowernumber,
467                 housebound_chooser   => $hsbnd_chooser,
468                 housebound_deliverer => $hsbnd_deliverer,
469             })->store;
470         }
471
472     } elsif ($op eq 'save') {
473
474         # Update or create our HouseboundRole if necessary.
475         my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
476         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
477         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
478         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
479         if ( $housebound_role ) {
480             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
481                 # Update our HouseboundRole.
482                 $housebound_role
483                     ->housebound_chooser($hsbnd_chooser)
484                     ->housebound_deliverer($hsbnd_deliverer)
485                     ->store;
486             } else {
487                 $housebound_role->delete; # No longer needed.
488             }
489         } else {
490             # Only create a HouseboundRole if patron has a role.
491             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
492                 $housebound_role = Koha::Patron::HouseboundRole->new({
493                     borrowernumber_id    => $borrowernumber,
494                     housebound_chooser   => $hsbnd_chooser,
495                     housebound_deliverer => $hsbnd_deliverer,
496                 })->store;
497             }
498         }
499
500         if ($NoUpdateLogin) {
501             delete $newdata{'password'};
502             delete $newdata{'userid'};
503         }
504         &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
505                                                                 # updating any columns in the borrowers table,
506                                                                 # which can happen if we're only editing the
507                                                                 # patron attributes or messaging preferences sections
508         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
509             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
510         }
511         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
512             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
513         }
514         }
515         print scalar ($destination eq "circ") ? 
516                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
517                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
518         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
519 }
520
521 if ($delete){
522         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
523         exit;           # same as above
524 }
525
526 if ($nok or !$nodouble){
527     $op="add" if ($op eq "insert");
528     $op="modify" if ($op eq "save");
529     %data=%newdata; 
530     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
531     unless ($step){  
532         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
533     }  
534
535 if (C4::Context->preference("IndependentBranches")) {
536     my $userenv = C4::Context->userenv;
537     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
538         unless ($userenv->{branch} eq $data{'branchcode'}){
539             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
540             exit;
541         }
542     }
543 }
544 if ($op eq 'add'){
545     $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
546 }
547 if ($op eq "modify")  {
548     $template->param( updtype => 'M',modify => 1 );
549     $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
550     if ( $step == 4 ) {
551         $template->param( categorycode => $borrower_data->{'categorycode'} );
552     }
553     # Add sync data to the user data
554     if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
555         my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
556         if ( $sync ) {
557             $template->param(
558                 sync => $sync->sync,
559             );
560         }
561     }
562 }
563 if ( $op eq "duplicate" ) {
564     $template->param( updtype => 'I' );
565     $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
566     $data{'cardnumber'} = "";
567 }
568
569 if(!defined($data{'sex'})){
570     $template->param( none => 1);
571 } elsif($data{'sex'} eq 'F'){
572     $template->param( female => 1);
573 } elsif ($data{'sex'} eq 'M'){
574     $template->param(  male => 1);
575 } else {
576     $template->param(  none => 1);
577 }
578
579 ##Now all the data to modify a member.
580
581 my @typeloop;
582 my $no_categories = 1;
583 my $no_add;
584 foreach my $category_type (qw(C A S P I X)) {
585     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
586     $no_categories = 0 if $patron_categories->count > 0;
587
588     my @categoryloop;
589     while ( my $patron_category = $patron_categories->next ) {
590         push @categoryloop,
591           { 'categorycode' => $patron_category->categorycode,
592             'categoryname' => $patron_category->description,
593             'categorycodeselected' =>
594               ( ( defined( $borrower_data->{'categorycode'} ) && $patron_category->categorycode eq $borrower_data->{'categorycode'} ) || ( defined($categorycode) && $patron_category->categorycode eq $categorycode ) ),
595           };
596     }
597     my %typehash;
598     $typehash{'typename'} = $category_type;
599     my $typedescription = "typename_" . $typehash{'typename'};
600     $typehash{'categoryloop'} = \@categoryloop;
601     push @typeloop,
602       { 'typename'       => $category_type,
603         $typedescription => 1,
604         'categoryloop'   => \@categoryloop
605       };
606 }
607
608 $template->param('typeloop' => \@typeloop,
609         no_categories => $no_categories);
610 if($no_categories){ $no_add = 1; }
611
612
613 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
614 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
615 $template->param(
616     roadtypes => $roadtypes,
617     cities    => $cities,
618 );
619
620 my $default_borrowertitle = '';
621 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
622
623 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
624 my @relshipdata;
625 while (@relationships) {
626   my $relship = shift @relationships || '';
627   my %row = ('relationship' => $relship);
628   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
629     $row{'selected'}=' selected';
630   } else {
631     $row{'selected'}='';
632   }
633   push(@relshipdata, \%row);
634 }
635
636 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
637         'lost'          => ['lost']);
638
639  
640 my @flagdata;
641 foreach (keys(%flags)) {
642         my $key = $_;
643         my %row =  ('key'   => $key,
644                     'name'  => $flags{$key}[0]);
645         if ($data{$key}) {
646                 $row{'yes'}=' checked';
647                 $row{'no'}='';
648     }
649         else {
650                 $row{'yes'}='';
651                 $row{'no'}=' checked';
652         }
653         push @flagdata,\%row;
654 }
655
656 # get Branch Loop
657 # in modify mod: userbranch value comes from borrowers table
658 # in add    mod: userbranch value comes from branches table (ip correspondence)
659
660 my $userbranch = '';
661 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
662     $userbranch = C4::Context->userenv->{'branch'};
663 }
664
665 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
666     $userbranch = $data{'branchcode'};
667 }
668 $template->param( userbranch => $userbranch );
669
670 if ( Koha::Libraries->search->count < 1 ){
671     $no_add = 1;
672     $template->param(no_branches => 1);
673 }
674 if($no_categories){
675     $no_add = 1;
676     $template->param(no_categories => 1);
677 }
678 $template->param(no_add => $no_add);
679 # --------------------------------------------------------------------------------------------------------
680
681 $template->param( sort1 => $data{'sort1'});
682 $template->param( sort2 => $data{'sort2'});
683
684 if ($nok) {
685     foreach my $error (@errors) {
686         $template->param($error) || $template->param( $error => 1);
687     }
688     $template->param(nok => 1);
689 }
690   
691   #Formatting data for display    
692   
693 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
694   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
695 }
696 if ( $op eq 'duplicate' ) {
697     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
698     my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
699     $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
700 }
701 if (C4::Context->preference('uppercasesurnames')) {
702     $data{'surname'} &&= uc( $data{'surname'} );
703     $data{'contactname'} &&= uc( $data{'contactname'} );
704 }
705
706 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
707     if ( $data{$_} ) {
708        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
709     }
710     $template->param( $_ => $data{$_});
711 }
712
713 if (C4::Context->preference('ExtendedPatronAttributes')) {
714     $template->param(ExtendedPatronAttributes => 1);
715     patron_attributes_form($template, $borrowernumber);
716 }
717
718 if (C4::Context->preference('EnhancedMessagingPreferences')) {
719     if ($op eq 'add') {
720         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
721     } else {
722         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
723     }
724     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
725     $template->param(SMSnumber     => $data{'smsalertnumber'} );
726     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
727 }
728
729 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
730 $debug and warn "memberentry step: $step";
731 $template->param(%data);
732 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
733 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
734
735 $template->param(
736   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
737   category_type => $category_type,#to know the category type of the borrower
738   "$category_type"  => 1,# associate with step to know where u are
739   destination   => $destination,#to know wher u come from and wher u must go in redirect
740   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
741   "op$op"   => 1);
742
743 $template->param(
744   nodouble  => $nodouble,
745   borrowernumber  => $borrowernumber, #register number
746   guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
747   relshiploop => \@relshipdata,
748   btitle=> $default_borrowertitle,
749   guarantorinfo   => $guarantorinfo,
750   flagloop  => \@flagdata,
751   category_type =>$category_type,
752   modify          => $modify,
753   nok     => $nok,#flag to know if an error
754   NoUpdateLogin =>  $NoUpdateLogin,
755   );
756
757 # Generate CSRF token
758 $template->param( csrf_token =>
759       Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
760 );
761
762 # HouseboundModule data
763 $template->param(
764     housebound_role  => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
765 );
766
767 if(defined($data{'flags'})){
768   $template->param(flags=>$data{'flags'});
769 }
770 if(defined($data{'contacttitle'})){
771   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
772 }
773
774
775 my ( $min, $max ) = C4::Members::get_cardnumber_length();
776 if ( defined $min ) {
777     $template->param(
778         minlength_cardnumber => $min,
779         maxlength_cardnumber => $max
780     );
781 }
782
783 if ( C4::Context->preference('TranslateNotices') ) {
784     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
785     $template->param( languages => $translated_languages );
786 }
787
788 output_html_with_http_headers $input, $cookie, $template->output;
789
790 sub  parse_extended_patron_attributes {
791     my ($input) = @_;
792     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
793
794     my @attr = ();
795     my %dups = ();
796     foreach my $key (@patron_attr) {
797         my $value = $input->param($key);
798         next unless defined($value) and $value ne '';
799         my $code     = $input->param("${key}_code");
800         next if exists $dups{$code}->{$value};
801         $dups{$code}->{$value} = 1;
802         push @attr, { code => $code, value => $value };
803     }
804     return \@attr;
805 }
806
807 sub patron_attributes_form {
808     my $template = shift;
809     my $borrowernumber = shift;
810
811     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
812     if (scalar(@types) == 0) {
813         $template->param(no_patron_attribute_types => 1);
814         return;
815     }
816     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
817     my @classes = uniq( map {$_->{class}} @$attributes );
818     @classes = sort @classes;
819
820     # map patron's attributes into a more convenient structure
821     my %attr_hash = ();
822     foreach my $attr (@$attributes) {
823         push @{ $attr_hash{$attr->{code}} }, $attr;
824     }
825
826     my @attribute_loop = ();
827     my $i = 0;
828     my %items_by_class;
829     foreach my $type_code (map { $_->{code} } @types) {
830         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
831         my $entry = {
832             class             => $attr_type->class(),
833             code              => $attr_type->code(),
834             description       => $attr_type->description(),
835             repeatable        => $attr_type->repeatable(),
836             category          => $attr_type->authorised_value_category(),
837             category_code     => $attr_type->category_code(),
838         };
839         if (exists $attr_hash{$attr_type->code()}) {
840             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
841                 my $newentry = { %$entry };
842                 $newentry->{value} = $attr->{value};
843                 $newentry->{use_dropdown} = 0;
844                 if ($attr_type->authorised_value_category()) {
845                     $newentry->{use_dropdown} = 1;
846                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
847                 }
848                 $i++;
849                 $newentry->{form_id} = "patron_attr_$i";
850                 push @{$items_by_class{$attr_type->class()}}, $newentry;
851             }
852         } else {
853             $i++;
854             my $newentry = { %$entry };
855             if ($attr_type->authorised_value_category()) {
856                 $newentry->{use_dropdown} = 1;
857                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
858             }
859             $newentry->{form_id} = "patron_attr_$i";
860             push @{$items_by_class{$attr_type->class()}}, $newentry;
861         }
862     }
863     while ( my ($class, @items) = each %items_by_class ) {
864         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
865         my $lib = $av->count ? $av->next->lib : $class;
866         push @attribute_loop, {
867             class => $class,
868             items => @items,
869             lib   => $lib,
870         }
871     }
872
873     $template->param(patron_attributes => \@attribute_loop);
874
875 }
876
877 # Local Variables:
878 # tab-width: 8
879 # End: