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