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