1e8241d985355c63eccfb618e4fd61626e44e0c2
[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 Koha::SMS::Providers;
52
53 use vars qw($debug);
54
55 BEGIN {
56         $debug = $ENV{DEBUG} || 0;
57 }
58         
59 my $input = new CGI;
60 ($debug) or $debug = $input->param('debug') || 0;
61 my %data;
62
63 my $dbh = C4::Context->dbh;
64
65 my ($template, $loggedinuser, $cookie)
66     = get_template_and_user({template_name => "members/memberentrygen.tt",
67            query => $input,
68            type => "intranet",
69            authnotrequired => 0,
70            flagsrequired => {borrowers => 'edit_borrowers'},
71            debug => ($debug) ? 1 : 0,
72        });
73
74 my $borrowernumber = $input->param('borrowernumber');
75 my $patron         = Koha::Patrons->find($borrowernumber);
76
77 if ( $borrowernumber and not $patron ) {
78     output_and_exit( $input, $cookie, $template,  'unknown_patron' );
79 }
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 $actionType     = $input->param('actionType') || '';
87 my $modify         = $input->param('modify');
88 my $delete         = $input->param('delete');
89 my $op             = $input->param('op');
90 my $destination    = $input->param('destination');
91 my $cardnumber     = $input->param('cardnumber');
92 my $check_member   = $input->param('check_member');
93 my $nodouble       = $input->param('nodouble');
94 my $duplicate      = $input->param('duplicate');
95 my $quickadd       = $input->param('quickadd');
96 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
97                                      # modifying an existing patron, it ipso facto
98                                      # isn't a duplicate.  Marking FIXME because this
99                                      # script needs to be refactored.
100 my $nok           = $input->param('nok');
101 my $step          = $input->param('step') || 0;
102 my @errors;
103 my $borrower_data;
104 my $NoUpdateLogin;
105 my $userenv = C4::Context->userenv;
106
107 ## Deal with guarantor stuff
108 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
109
110 my $guarantor_id = $input->param('guarantor_id');
111 my $guarantor = undef;
112 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
113 $template->param( guarantor => $guarantor );
114
115 my @delete_guarantor = $input->multi_param('delete_guarantor');
116 foreach my $id ( @delete_guarantor ) {
117     my $r = Koha::Patron::Relationships->find( $id );
118     $r->delete() if $r;
119 }
120
121 ## Deal with debarments
122 $template->param(
123     debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
124 my @debarments_to_remove = $input->multi_param('remove_debarment');
125 foreach my $d ( @debarments_to_remove ) {
126     DelDebarment( $d );
127 }
128 if ( $input->param('add_debarment') ) {
129
130     my $expiration = $input->param('debarred_expiration');
131     $expiration =
132       $expiration
133       ? dt_from_string($expiration)->ymd
134       : undef;
135
136     AddDebarment(
137         {
138             borrowernumber => $borrowernumber,
139             type           => 'MANUAL',
140             comment        => scalar $input->param('debarred_comment'),
141             expiration     => $expiration,
142         }
143     );
144 }
145
146 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
147
148 # function to designate mandatory fields (visually with css)
149 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
150 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
151 foreach (@field_check) {
152     $template->param( "mandatory$_" => 1 );
153 }
154 # function to designate unwanted fields
155 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
156 @field_check=split(/\|/,$check_BorrowerUnwantedField);
157 foreach (@field_check) {
158     next unless m/\w/o;
159     $template->param( "no$_" => 1 );
160 }
161 $template->param( "add" => 1 ) if ( $op eq 'add' );
162 $template->param( "quickadd" => 1 ) if ( $quickadd );
163 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
164 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
165 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
166     my $logged_in_user = Koha::Patrons->find( $loggedinuser );
167     output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
168
169     $borrower_data = $patron->unblessed;
170     $borrower_data->{category_type} = $patron->category->category_type;
171 }
172
173 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
174 my $category_type = $input->param('category_type') || '';
175 unless ($category_type or !($categorycode)){
176     my $borrowercategory = Koha::Patron::Categories->find($categorycode);
177     $category_type    = $borrowercategory->category_type;
178     my $category_name = $borrowercategory->description;
179     $template->param("categoryname"=>$category_name);
180 }
181 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
182
183 # if a add or modify is requested => check validity of data.
184 %data = %$borrower_data if ($borrower_data);
185
186 # initialize %newdata
187 my %newdata;                                                                             # comes from $input->param()
188 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
189     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
190     foreach my $key (@names) {
191         if (defined $input->param($key)) {
192             $newdata{$key} = $input->param($key);
193         }
194     }
195
196     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
197         next unless exists $newdata{$_};
198         my $userdate = $newdata{$_} or next;
199
200         my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
201         if ( $formatteddate ) {
202             $newdata{$_} = $formatteddate;
203         } else {
204             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
205             $template->param( "ERROR_$_" => 1 );
206             push(@errors,"ERROR_$_");
207         }
208     }
209   # check permission to modify login info.
210     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
211         $NoUpdateLogin = 1;
212     }
213 }
214
215 # remove keys from %newdata that is not part of patron's attributes
216 {
217     my @keys_to_delete = (
218         qr/^BorrowerMandatoryField$/,
219         qr/^category_type$/,
220         qr/^check_member$/,
221         qr/^destination$/,
222         qr/^nodouble$/,
223         qr/^op$/,
224         qr/^save$/,
225         qr/^updtype$/,
226         qr/^SMSnumber$/,
227         qr/^setting_extended_patron_attributes$/,
228         qr/^setting_messaging_prefs$/,
229         qr/^digest$/,
230         qr/^modify$/,
231         qr/^step$/,
232         qr/^\d+$/,
233         qr/^\d+-DAYS/,
234         qr/^patron_attr_/,
235         qr/^csrf_token$/,
236         qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
237         qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
238         qr/^select_city$/,
239         qr/^new_guarantor_/,
240         qr/^guarantor_firstname$/,
241         qr/^guarantor_surname$/,
242         qr/^delete_guarantor$/,
243     );
244     for my $regexp (@keys_to_delete) {
245         for (keys %newdata) {
246             delete($newdata{$_}) if /$regexp/;
247         }
248     }
249 }
250
251 # Test uniqueness of surname, firstname and dateofbirth
252 if ( ( $op eq 'insert' ) and !$nodouble ) {
253     my $conditions;
254     $conditions->{surname} = $newdata{surname} if $newdata{surname};
255     if ( $category_type ne 'I' ) {
256         $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
257         $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
258     }
259     $nodouble = 1;
260     my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
261     if ( $patrons->count > 0) {
262         $nodouble = 0;
263         $check_member = $patrons->next->borrowernumber;
264
265
266         my @new_guarantors;
267         my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
268         my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
269         foreach my $gid ( @new_guarantor_id ) {
270             my $patron = Koha::Patrons->find( $gid );
271             my $relationship = shift( @new_guarantor_relationship );
272             next unless $patron;
273             my $g = { patron => $patron, relationship => $relationship };
274             push( @new_guarantors, $g );
275         }
276         $template->param( new_guarantors => \@new_guarantors );
277     }
278 }
279
280 ###############test to take the right zipcode, country and city name ##############
281 # set only if parameter was passed from the form
282 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
283 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
284 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
285
286 $newdata{'lang'}    = $input->param('lang')    if defined($input->param('lang'));
287
288 # builds default userid
289 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
290 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
291     my $fake_patron = Koha::Patron->new;
292     $fake_patron->userid($patron->userid) if $patron; # editing
293     if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
294         # Full page edit, firstname and surname input zones are present
295         $fake_patron->firstname($newdata{firstname});
296         $fake_patron->surname($newdata{surname});
297         $fake_patron->generate_userid;
298         $newdata{'userid'} = $fake_patron->userid;
299     }
300     elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
301         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
302         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
303         # FIXME clean thiscode newdata vs data is very confusing
304         $fake_patron->firstname($data{firstname});
305         $fake_patron->surname($data{surname});
306         $fake_patron->generate_userid;
307         $newdata{'userid'} = $fake_patron->userid;
308     }
309     else {
310         $newdata{'userid'} = $data{'userid'};
311     }
312 }
313   
314 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
315 my $extended_patron_attributes = ();
316 if ($op eq 'save' || $op eq 'insert'){
317
318     output_and_exit( $input, $cookie, $template,  'wrong_csrf_token' )
319         unless Koha::Token->new->check_csrf({
320             session_id => scalar $input->cookie('CGISESSID'),
321             token  => scalar $input->param('csrf_token'),
322         });
323
324     # If the cardnumber is blank, treat it as null.
325     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
326
327     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
328         push @errors, $error_code == 1
329             ? 'ERROR_cardnumber_already_exists'
330             : $error_code == 2
331                 ? 'ERROR_cardnumber_length'
332                 : ()
333     }
334
335     my $dateofbirth;
336     if ($op eq 'save' && $step == 3) {
337         $dateofbirth = $patron->dateofbirth;
338     }
339     else {
340         $dateofbirth = $newdata{dateofbirth};
341     }
342
343     if ( $dateofbirth ) {
344         my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
345         my $age = $patron->get_age;
346         my $borrowercategory = Koha::Patron::Categories->find($categorycode);
347         my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
348         if (($high && ($age > $high)) or ($age < $low)) {
349             push @errors, 'ERROR_age_limitations';
350             $template->param( age_low => $low);
351             $template->param( age_high => $high);
352         }
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             add_guarantors( $patron, $input );
444             $borrowernumber = $patron->borrowernumber;
445             $newdata{'borrowernumber'} = $borrowernumber;
446         }
447
448         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
449         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
450             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
451             my $emailaddr;
452             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
453                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
454                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
455             } 
456             elsif ($newdata{email} =~ /\w\@\w/) {
457                 $emailaddr = $newdata{email} 
458             }
459             elsif ($newdata{emailpro} =~ /\w\@\w/) {
460                 $emailaddr = $newdata{emailpro} 
461             }
462             elsif ($newdata{B_email} =~ /\w\@\w/) {
463                 $emailaddr = $newdata{B_email} 
464             }
465             # if we manage to find a valid email address, send notice 
466             if ($emailaddr) {
467                 $newdata{emailaddr} = $emailaddr;
468                 my $err;
469                 eval {
470                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
471                 };
472                 if ( $@ ) {
473                     $template->param(error_alert => $@);
474                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
475                     $template->{VARS}->{'error_alert'} = "no_email";
476                 } else {
477                     $template->{VARS}->{'info_alert'} = 1;
478                 }
479             }
480         }
481
482         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
483             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
484         }
485         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
486             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
487         }
488
489         # Create HouseboundRole if necessary.
490         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
491         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
492         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
493         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
494         # Only create a HouseboundRole if patron has a role.
495         if ( $hsbnd_chooser || $hsbnd_deliverer ) {
496             Koha::Patron::HouseboundRole->new({
497                 borrowernumber_id    => $borrowernumber,
498                 housebound_chooser   => $hsbnd_chooser,
499                 housebound_deliverer => $hsbnd_deliverer,
500             })->store;
501         }
502
503     } elsif ($op eq 'save') {
504
505         # Update or create our HouseboundRole if necessary.
506         my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
507         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
508         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
509         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
510         if ( $housebound_role ) {
511             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
512                 # Update our HouseboundRole.
513                 $housebound_role
514                     ->housebound_chooser($hsbnd_chooser)
515                     ->housebound_deliverer($hsbnd_deliverer)
516                     ->store;
517             } else {
518                 $housebound_role->delete; # No longer needed.
519             }
520         } else {
521             # Only create a HouseboundRole if patron has a role.
522             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
523                 $housebound_role = Koha::Patron::HouseboundRole->new({
524                     borrowernumber_id    => $borrowernumber,
525                     housebound_chooser   => $hsbnd_chooser,
526                     housebound_deliverer => $hsbnd_deliverer,
527                 })->store;
528             }
529         }
530
531         if ($NoUpdateLogin) {
532             delete $newdata{'password'};
533             delete $newdata{'userid'};
534         }
535
536         my $patron = Koha::Patrons->find( $borrowernumber );
537         $newdata{debarredcomment} = $newdata{debarred_comment};
538         delete $newdata{debarred_comment};
539         delete $newdata{password2};
540         $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
541                                                                 # updating any columns in the borrowers table,
542                                                                 # which can happen if we're only editing the
543                                                                 # patron attributes or messaging preferences sections
544
545         # should never raise an exception as password validity is checked above
546         my $password = $newdata{password};
547         if ( $password and $password ne '****' ) {
548             $patron->set_password({ password => $password });
549         }
550
551         add_guarantors( $patron, $input );
552         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
553             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
554         }
555         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
556             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
557         }
558         }
559
560     if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
561         # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
562         $destination = 'not_circ';
563     }
564     print scalar( $destination eq "circ" )
565       ? $input->redirect(
566         "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
567       : $input->redirect(
568         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
569       );
570     exit; # You can only send 1 redirect!  After that, content or other headers don't matter.
571 }
572
573 if ($delete){
574         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
575         exit;           # same as above
576 }
577
578 if ($nok or !$nodouble){
579     $op="add" if ($op eq "insert");
580     $op="modify" if ($op eq "save");
581     %data=%newdata; 
582     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
583     unless ($step){  
584         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
585     }  
586
587 if (C4::Context->preference("IndependentBranches")) {
588     my $userenv = C4::Context->userenv;
589     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
590         unless ($userenv->{branch} eq $data{'branchcode'}){
591             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
592             exit;
593         }
594     }
595 }
596 if ($op eq 'add'){
597     if ( $guarantor_id ) {
598         my $guarantordata = $guarantor->unblessed;
599         foreach (qw(streetnumber address streettype address2
600           zipcode country city state phone phonepro mobile fax email emailpro branchcode
601           B_streetnumber B_streettype B_address B_address2
602           B_city B_state B_zipcode B_country B_email B_phone)) {
603               $newdata{$_} = $guarantordata->{$_};
604         }
605     }
606     $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);
607 }
608 if ($op eq "modify")  {
609     $template->param( updtype => 'M',modify => 1 );
610     $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;
611     if ( $step == 4 ) {
612         $template->param( categorycode => $borrower_data->{'categorycode'} );
613     }
614 }
615 if ( $op eq "duplicate" ) {
616     $template->param( updtype => 'I' );
617     $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;
618     $data{'cardnumber'} = "";
619 }
620
621 if(!defined($data{'sex'})){
622     $template->param( none => 1);
623 } elsif($data{'sex'} eq 'F'){
624     $template->param( female => 1);
625 } elsif ($data{'sex'} eq 'M'){
626     $template->param(  male => 1);
627 } else {
628     $template->param(  none => 1);
629 }
630
631 ##Now all the data to modify a member.
632
633 my @typeloop;
634 my $no_categories = 1;
635 my $no_add;
636 foreach my $category_type (qw(C A S P I X)) {
637     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
638     $no_categories = 0 if $patron_categories->count > 0;
639
640     my @categoryloop;
641     while ( my $patron_category = $patron_categories->next ) {
642         push @categoryloop,
643           { 'categorycode' => $patron_category->categorycode,
644             'categoryname' => $patron_category->description,
645             'categorycodeselected' =>
646               ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
647           };
648     }
649     my %typehash;
650     $typehash{'typename'} = $category_type;
651     my $typedescription = "typename_" . $typehash{'typename'};
652     $typehash{'categoryloop'} = \@categoryloop;
653     push @typeloop,
654       { 'typename'       => $category_type,
655         $typedescription => 1,
656         'categoryloop'   => \@categoryloop
657       };
658 }
659 $template->param(
660     typeloop      => \@typeloop,
661     no_categories => $no_categories,
662 );
663
664 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
665 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
666 $template->param(
667     roadtypes => $roadtypes,
668     cities    => $cities,
669 );
670
671 my $default_borrowertitle = '';
672 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
673
674 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
675 my @relshipdata;
676 while (@relationships) {
677   my $relship = shift @relationships || '';
678   my %row = ('relationship' => $relship);
679   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
680     $row{'selected'}=' selected';
681   } else {
682     $row{'selected'}='';
683   }
684   push(@relshipdata, \%row);
685 }
686
687 my %flags = (
688     'gonenoaddress' => ['gonenoaddress'],
689     'lost'          => ['lost']
690 );
691
692 my @flagdata;
693 foreach ( keys(%flags) ) {
694     my $key = $_;
695     my %row = (
696         'key'  => $key,
697         'name' => $flags{$key}[0]
698     );
699     if ( $data{$key} ) {
700         $row{'yes'} = ' checked';
701         $row{'no'}  = '';
702     }
703     else {
704         $row{'yes'} = '';
705         $row{'no'}  = ' checked';
706     }
707     push @flagdata, \%row;
708 }
709
710 # get Branch Loop
711 # in modify mod: userbranch value comes from borrowers table
712 # in add    mod: userbranch value comes from branches table (ip correspondence)
713
714 my $userbranch = '';
715 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
716     $userbranch = C4::Context->userenv->{'branch'};
717 }
718
719 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
720     $userbranch = $data{'branchcode'};
721 }
722 $template->param( userbranch => $userbranch );
723
724 if ( Koha::Libraries->search->count < 1 ){
725     $no_add = 1;
726     $template->param(no_branches => 1);
727 }
728 if($no_categories){
729     $no_add = 1;
730     $template->param(no_categories => 1);
731 }
732 $template->param(no_add => $no_add);
733 # --------------------------------------------------------------------------------------------------------
734
735 $template->param( sort1 => $data{'sort1'});
736 $template->param( sort2 => $data{'sort2'});
737
738 if ($nok) {
739     foreach my $error (@errors) {
740         $template->param($error) || $template->param( $error => 1);
741     }
742     $template->param(nok => 1);
743 }
744   
745   #Formatting data for display    
746   
747 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
748   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
749 }
750 if ( $op eq 'duplicate' ) {
751     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
752     my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
753     $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
754 }
755 if (C4::Context->preference('uppercasesurnames')) {
756     $data{'surname'} &&= uc( $data{'surname'} );
757     $data{'contactname'} &&= uc( $data{'contactname'} );
758 }
759
760 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
761     if ( $data{$_} ) {
762        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
763     }
764     $template->param( $_ => $data{$_});
765 }
766
767 if (C4::Context->preference('ExtendedPatronAttributes')) {
768     patron_attributes_form($template, $borrowernumber, $op);
769 }
770
771 if (C4::Context->preference('EnhancedMessagingPreferences')) {
772     if ($op eq 'add') {
773         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
774     } else {
775         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
776     }
777     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
778     $template->param(SMSnumber     => $data{'smsalertnumber'} );
779     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
780 }
781
782 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
783 $debug and warn "memberentry step: $step";
784 $template->param(%data);
785 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
786 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
787
788 $template->param(
789   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
790   category_type => $category_type,#to know the category type of the borrower
791   "$category_type"  => 1,# associate with step to know where u are
792   destination   => $destination,#to know wher u come from and wher u must go in redirect
793   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
794   "op$op"   => 1);
795
796 $template->param(
797   patron => $patron ? $patron : \%newdata, # Used by address include templates now
798   nodouble  => $nodouble,
799   borrowernumber  => $borrowernumber, #register number
800   relshiploop => \@relshipdata,
801   btitle=> $default_borrowertitle,
802   flagloop  => \@flagdata,
803   category_type =>$category_type,
804   modify          => $modify,
805   nok     => $nok,#flag to know if an error
806   NoUpdateLogin =>  $NoUpdateLogin,
807   );
808
809 # Generate CSRF token
810 $template->param( csrf_token =>
811       Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
812 );
813
814 # HouseboundModule data
815 $template->param(
816     housebound_role  => Koha::Patron::HouseboundRoles->find($borrowernumber),
817 );
818
819 if(defined($data{'flags'})){
820   $template->param(flags=>$data{'flags'});
821 }
822 if(defined($data{'contacttitle'})){
823   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
824 }
825
826
827 my ( $min, $max ) = C4::Members::get_cardnumber_length();
828 if ( defined $min ) {
829     $template->param(
830         minlength_cardnumber => $min,
831         maxlength_cardnumber => $max
832     );
833 }
834
835 if ( C4::Context->preference('TranslateNotices') ) {
836     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
837     $template->param( languages => $translated_languages );
838 }
839
840 output_html_with_http_headers $input, $cookie, $template->output;
841
842 sub  parse_extended_patron_attributes {
843     my ($input) = @_;
844     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
845
846     my @attr = ();
847     my %dups = ();
848     foreach my $key (@patron_attr) {
849         my $value = $input->param($key);
850         next unless defined($value) and $value ne '';
851         my $code     = $input->param("${key}_code");
852         next if exists $dups{$code}->{$value};
853         $dups{$code}->{$value} = 1;
854         push @attr, { code => $code, value => $value };
855     }
856     return \@attr;
857 }
858
859 sub patron_attributes_form {
860     my $template = shift;
861     my $borrowernumber = shift;
862     my $op = 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                 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
903                 $newentry->{form_id} = "patron_attr_$i";
904                 push @{$items_by_class{$attr_type->class()}}, $newentry;
905             }
906         } else {
907             $i++;
908             my $newentry = { %$entry };
909             if ($attr_type->authorised_value_category()) {
910                 $newentry->{use_dropdown} = 1;
911                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
912             }
913             $newentry->{form_id} = "patron_attr_$i";
914             push @{$items_by_class{$attr_type->class()}}, $newentry;
915         }
916     }
917     while ( my ($class, @items) = each %items_by_class ) {
918         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
919         my $lib = $av->count ? $av->next->lib : $class;
920         push @attribute_loop, {
921             class => $class,
922             items => @items,
923             lib   => $lib,
924         }
925     }
926
927     $template->param(patron_attributes => \@attribute_loop);
928
929 }
930
931 sub add_guarantors {
932     my ( $patron, $input ) = @_;
933
934     my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
935     my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
936
937     for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
938         my $guarantor_id = $new_guarantor_id[$i];
939         my $relationship = $new_guarantor_relationship[$i];
940
941         next unless $guarantor_id;
942
943         $patron->add_guarantor(
944             {
945                 guarantor_id => $guarantor_id,
946                 relationship => $relationship,
947             }
948         );
949     }
950 }
951
952 # Local Variables:
953 # tab-width: 8
954 # End: