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