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