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