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