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