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