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