Bug 36170: Wrong error variable in memberentry
[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::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 $modify       = $input->param('modify');
77 my $delete       = $input->param('cud-delete');
78 my $op           = $input->param('op') || q{};
79 my $destination  = $input->param('destination');
80 my $cardnumber   = $input->param('cardnumber');
81 my $check_member = $input->param('check_member');
82 my $nodouble     = $input->param('nodouble');
83 my $duplicate    = $input->param('duplicate');
84 my $quickadd     = $input->param('quickadd');
85
86 $nodouble = 1 if ($op eq 'edit_form' 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 #Search existing guarantor id(s) and new ones from params
114 my @guarantors;
115 my @new_guarantor_ids = grep { $_ ne '' } $input->multi_param('new_guarantor_id');
116
117 foreach my $new_guarantor_id (@new_guarantor_ids) {
118     my $new_guarantor = Koha::Patrons->find( { borrowernumber => $new_guarantor_id } );
119     push @guarantors, $new_guarantor;
120 }
121
122 my @existing_guarantors = $patron ? $patron->guarantor_relationships()->guarantors->as_list : ();
123 push @guarantors, @existing_guarantors;
124
125 ## Deal with debarments
126 $template->param(
127     restriction_types => scalar Koha::Patron::Restriction::Types->search()
128 );
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           => scalar $input->param('debarred_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( "op" => $op );
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 'edit_form' or $op eq 'cud-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     if ($logged_in_user->is_superlibrarian) {
179         $CanUpdatePasswordExpiration = 1;
180     }
181
182     $borrower_data = $patron->unblessed;
183 }
184
185 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
186 my $category = Koha::Patron::Categories->find($categorycode);
187 $template->param( patron_category => $category );
188
189 # if a add or modify is requested => check validity of data.
190 %data = %$borrower_data if ($borrower_data);
191
192 # initialize %newdata
193 my %newdata;                                                                             # comes from $input->param()
194 if ( $op eq 'cud-insert' || $op eq 'edit_form' || $op eq 'cud-save' || $op eq 'duplicate' ) {
195     my @names = ( $borrower_data && $op ne 'cud-save' ) ? keys %$borrower_data : $input->param();
196     foreach my $key (@names) {
197         if (defined $input->param($key)) {
198             $newdata{$key} = $input->param($key);
199         }
200     }
201
202     # check permission to modify login info.
203     if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
204         $NoUpdateLogin = 1;
205     }
206 }
207
208 # remove keys from %newdata that is not part of patron's attributes
209 {
210     my @keys_to_delete = (
211         qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
212         qr/^BorrowerMandatoryField$/,
213         qr/^check_member$/,
214         qr/^destination$/,
215         qr/^nodouble$/,
216         qr/^op$/,
217         qr/^save$/,
218         qr/^updtype$/,
219         qr/^SMSnumber$/,
220         qr/^setting_extended_patron_attributes$/,
221         qr/^setting_messaging_prefs$/,
222         qr/^digest$/,
223         qr/^modify$/,
224         qr/^step$/,
225         qr/^\d+$/,
226         qr/^\d+-DAYS/,
227         qr/^patron_attr_/,
228         qr/^csrf_token$/,
229         qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^debarred_type$/, qr/^remove_debarment$/, # We already dealt with debarments previously
230         qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
231         qr/^select_city$/,
232         qr/^new_guarantor_/,
233         qr/^guarantor_firstname$/,
234         qr/^guarantor_surname$/,
235         qr/^delete_guarantor$/,
236     );
237     push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
238     push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
239     for my $regexp (@keys_to_delete) {
240         for (keys %newdata) {
241             delete($newdata{$_}) if /$regexp/;
242         }
243     }
244 }
245
246 # Test uniqueness of surname, firstname and dateofbirth
247 if ( ( $op eq 'cud-insert' ) and !$nodouble ) {
248     my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
249     my $conditions;
250     for my $f ( @dup_fields ) {
251         $conditions->{$f} = $newdata{$f} if $newdata{$f};
252     }
253     $nodouble = 1;
254     my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
255     if ( $patrons->count > 0) {
256         $nodouble = 0;
257         $check_member = $patrons->next->borrowernumber;
258     }
259 }
260
261 #Attempt to delete guarantors
262 my @delete_guarantor = $input->multi_param('delete_guarantor');
263 if (@delete_guarantor) {
264     if ( C4::Context->preference('ChildNeedsGuarantor')
265         && scalar @guarantors - scalar @delete_guarantor == 0 )
266     {
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 'cud-save' || $op eq 'cud-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 'cud-save' || $op eq 'cud-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 'cud-save' || $op eq 'cud-insert'){
304
305     # If the cardnumber is blank, treat it as null.
306     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
307
308     my $new_barcode = $newdata{'cardnumber'};
309     Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
310
311     $newdata{'cardnumber'} = $new_barcode;
312
313     my $is_valid = Koha::Policy::Patrons::Cardnumber->is_valid($newdata{cardnumber}, $patron );
314     unless ($is_valid) {
315         for my $m ( @{ $is_valid->messages } ) {
316             my $message = $m->message;
317             if ( $message eq 'already_exists' ) {
318                 $template->param( ERROR_cardnumber_already_exists => 1 );
319             } elsif ( $message eq 'invalid_length' ) {
320                 $template->param( ERROR_cardnumber_length => 1 );
321             }
322         }
323     }
324
325     my $dateofbirth;
326     if ($op eq 'cud-save' && $step == 3) {
327         $dateofbirth = $patron->dateofbirth;
328     }
329     else {
330         $dateofbirth = $newdata{dateofbirth};
331     }
332
333     if ( $dateofbirth ) {
334         my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
335         my $age = $patron->get_age;
336         my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
337         if (($high && ($age > $high)) or ($age < $low)) {
338             push @errors, 'ERROR_age_limitations';
339             $template->param( age_low => $low);
340             $template->param( age_high => $high);
341         }
342     }
343   
344   if (C4::Context->preference("IndependentBranches")) {
345     unless ( C4::Context->IsSuperLibrarian() ){
346       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
347         push @errors, "ERROR_branch";
348       }
349     }
350   }
351
352   # Bug 32426 removed the userid unique-check here. Postpone it to patron->store.
353
354   my $password = $input->param('password');
355   my $password2 = $input->param('password2');
356   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
357
358   if ( $password and $password ne '****' ) {
359       my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
360       unless ( $is_valid ) {
361           push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
362           push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
363           push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
364       }
365   }
366
367   # Validate emails
368   my $emailprimary = $input->param('email');
369   my $emailsecondary = $input->param('emailpro');
370   my $emailalt = $input->param('B_email');
371
372   if ($emailprimary) {
373       push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
374   }
375   if ($emailsecondary) {
376       push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
377   }
378   if ($emailalt) {
379       push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
380   }
381
382   if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
383       $extended_patron_attributes = parse_extended_patron_attributes($input);
384       for my $attr ( @$extended_patron_attributes ) {
385           $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
386           my $attribute = Koha::Patron::Attribute->new($attr);
387           if ( !$attribute->unique_ok ) {
388               push @errors, "ERROR_extended_unique_id_failed";
389               my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
390               $template->param(
391                   ERROR_extended_unique_id_failed_code => $attr->{code},
392                   ERROR_extended_unique_id_failed_value => $attr->{attribute},
393                   ERROR_extended_unique_id_failed_description => $attr_type->description()
394               );
395           }
396       }
397   }
398 }
399 elsif ( $borrowernumber ) {
400     $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
401 }
402
403 if ( ($op eq 'edit_form' || $op eq 'cud-insert' || $op eq 'cud-save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
404     unless ($newdata{'dateexpiry'}){
405         $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
406     }
407 }
408
409 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
410 my $sms = $input->param('SMSnumber');
411 if ( defined $sms ) {
412     $newdata{smsalertnumber} = $sms;
413 }
414
415 ###  Error checks should happen before this line.
416 $nok = $nok || scalar(@errors);
417 if ((!$nok) and $nodouble and ($op eq 'cud-insert' or $op eq 'cud-save')){
418     my $success;
419         if ($op eq 'cud-insert'){
420                 # we know it's not a duplicate borrowernumber or there would already be an error
421         delete $newdata{password2};
422         $success = 1;
423         $patron = try {
424             Koha::Patron->new( \%newdata )->store( { guarantors => \@guarantors } );
425         } catch {
426             $success = 0;
427             $nok = 1;
428             if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
429                 push @errors, "ERROR_login_exist";
430             } else {
431                 # FIXME Urgent error handling here, we cannot fail without relevant feedback
432                 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
433                 warn "Patron creation failed! - $_"; # Maybe we must die instead of just warn
434                 push @messages, {error => 'error_on_insert_patron'};
435             }
436             $op = "add_form";
437             return;
438         };
439
440         if ( $success ) {
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 ( $patron && 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 } ) if $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 'cud-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         try {
518             $patron->set( \%newdata )->store( { guarantors => \@guarantors } ) if scalar( keys %newdata ) > 1;
519                 # bug 4508 - avoid crash if we're not updating any columns in the borrowers table (editing patron attrs or msg prefs)
520             $success = 1;
521         } catch {
522             $success = 0;
523             $nok = 1;
524             if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
525                 push @errors, "ERROR_login_exist";
526             } else {
527                 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
528                 push @messages, {error => 'error_on_update_patron'};
529             }
530             $op = 'edit_form';
531         };
532
533         if ( $success ) {
534
535             # Update or create our HouseboundRole if necessary.
536             my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
537             my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
538             $hsbnd_chooser = 1 if $input->param('housebound_chooser');
539             $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
540             if ( $housebound_role ) {
541                 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
542                     # Update our HouseboundRole.
543                     $housebound_role
544                         ->housebound_chooser($hsbnd_chooser)
545                         ->housebound_deliverer($hsbnd_deliverer)
546                         ->store;
547                 } else {
548                     $housebound_role->delete; # No longer needed.
549                 }
550             } else {
551                 # Only create a HouseboundRole if patron has a role.
552                 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
553                     $housebound_role = Koha::Patron::HouseboundRole->new({
554                         borrowernumber_id    => $borrowernumber,
555                         housebound_chooser   => $hsbnd_chooser,
556                         housebound_deliverer => $hsbnd_deliverer,
557                     })->store;
558                 }
559             }
560
561             # should never raise an exception as password validity is checked above
562             my $password = $newdata{password};
563             if ( $password and $password ne '****' ) {
564                 $patron->set_password({ password => $password });
565             }
566
567             add_guarantors( $patron, $input );
568             if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
569                 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
570             }
571         }
572     }
573
574     if ( $success ) {
575         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
576             $patron->extended_attributes->filter_by_branch_limitations->delete;
577             $patron->extended_attributes($extended_patron_attributes);
578         }
579
580         if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
581             # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
582             $destination = 'not_circ';
583         }
584         print scalar( $destination eq "circ" )
585           ? $input->redirect(
586             "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
587           : $input->redirect(
588             "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
589           );
590         exit; # You can only send 1 redirect!  After that, content or other headers don't matter.
591     }
592 }
593
594 if ($delete){
595         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
596         exit;           # same as above
597 }
598
599 if ($nok or !$nodouble){
600     $op = 'add_form'  if ( $op eq 'cud-insert' );
601     $op = 'edit_form' if ( $op eq 'cud-save' );
602     %data=%newdata; 
603     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "cud-insert"... but we just changed $op!
604     unless ($step){  
605         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
606     }  
607
608 if (C4::Context->preference("IndependentBranches")) {
609     my $userenv = C4::Context->userenv;
610     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
611         unless ($userenv->{branch} eq $data{'branchcode'}){
612             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
613             exit;
614         }
615     }
616 }
617
618 # Define the fields to be pre-filled in guarantee records
619 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
620 my @prefill_fields=split(/\,/,$prefillguarantorfields);
621
622 if ($op eq 'add_form'){
623     if ($guarantor_id) {
624         foreach (@prefill_fields) {
625             $newdata{$_} = $guarantor->$_;
626         }
627     }
628     $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);
629 }
630 if ($op eq 'edit_form')  {
631     $template->param( updtype => 'M',modify => 1 );
632     $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;
633     if ( $step == 4 ) {
634         $template->param( categorycode => $borrower_data->{'categorycode'} );
635     }
636 }
637 if ( $op eq "duplicate" ) {
638     $template->param( updtype => 'I' );
639     $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;
640     $data{'cardnumber'} = "";
641 }
642
643 if(!defined($data{'sex'})){
644     $template->param( none => 1);
645 } elsif($data{'sex'} eq 'F'){
646     $template->param( female => 1);
647 } elsif ($data{'sex'} eq 'M'){
648     $template->param(  male => 1);
649 } elsif ($data{'sex'} eq 'O') {
650     $template->param( other => 1);
651 } else {
652     $template->param(  none => 1);
653 }
654
655 ##Now all the data to modify a member.
656
657 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
658     {
659         category_type => [qw(C A S P I X)],
660         ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
661     },
662     { order_by => ['categorycode'] }
663 );
664 my $no_categories = ! $patron_categories->count;
665 my $categories = {};
666 my @patron_categories = $patron_categories->as_list;
667 # When adding a guarantor we don't have a category yet, and only want to choose from the eligible categories
668 unless ( !$category || $patron_categories->find( $category->id ) ){
669     $template->param( limited_category => 1 );
670     push @patron_categories, $category;
671 }
672 foreach my $patron_category ( @patron_categories ) {
673     push @{ $categories->{ $patron_category->category_type } }, $patron_category;
674 }
675
676 $template->param(
677     patron_categories => $categories,
678     no_categories => $no_categories,
679 );
680
681 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
682 $template->param(
683     cities    => $cities,
684 );
685
686 my $default_borrowertitle = '';
687 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
688
689 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
690 my @relshipdata;
691 while (@relationships) {
692   my $relship = shift @relationships || '';
693   my %row = ('relationship' => $relship);
694   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
695     $row{'selected'}=' selected';
696   } else {
697     $row{'selected'}='';
698   }
699   push(@relshipdata, \%row);
700 }
701
702 # get Branch Loop
703 # in modify mod: userbranch value comes from borrowers table
704 # in add    mod: userbranch value comes from branches table (ip correspondence)
705
706 my $userbranch = '';
707 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
708     $userbranch = C4::Context->userenv->{'branch'};
709 }
710
711 if (defined ($data{'branchcode'}) and ( $op eq 'edit_form' || $op eq 'duplicate' || ( $op eq 'add_form' && $category->category_type eq 'C' ) )) {
712     $userbranch = $data{'branchcode'};
713 }
714 $template->param( userbranch => $userbranch );
715
716 my $no_add;
717 if ( Koha::Libraries->search->count < 1 ){
718     $no_add = 1;
719     $template->param(no_branches => 1);
720 }
721 if($no_categories){
722     $no_add = 1;
723     $template->param(no_categories => 1);
724 }
725 $template->param(no_add => $no_add);
726 # --------------------------------------------------------------------------------------------------------
727
728 $template->param( sort1 => $data{'sort1'});
729 $template->param( sort2 => $data{'sort2'});
730 $template->param( autorenew => $data{'autorenew'});
731
732 if ($nok) {
733     foreach my $error (@errors) {
734         $template->param($error) || $template->param( $error => 1);
735     }
736     $template->param(nok => 1);
737
738     #Prevent losing guarantor data if error occurs
739     my @new_guarantors;
740     my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
741     my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
742     foreach my $gid ( @new_guarantor_id ) {
743         my $patron = Koha::Patrons->find( $gid );
744         my $relationship = shift( @new_guarantor_relationship );
745         next unless $patron;
746         my $g = { patron => $patron, relationship => $relationship };
747         push( @new_guarantors, $g );
748     }
749     $template->param( new_guarantors => \@new_guarantors );
750 }
751   
752   #Formatting data for display    
753   
754 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
755   $data{'dateenrolled'} = dt_from_string;
756 }
757 if ( $op eq 'duplicate' ) {
758     $data{'dateenrolled'} = dt_from_string;
759     $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
760 }
761 if (C4::Context->preference('uppercasesurnames')) {
762     $data{'surname'} &&= uc( $data{'surname'} );
763     $data{'contactname'} &&= uc( $data{'contactname'} );
764 }
765
766 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
767     patron_attributes_form( $template, $extended_patron_attributes, $op );
768 }
769
770 if (C4::Context->preference('EnhancedMessagingPreferences')) {
771     if ($op eq 'add_form') {
772         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
773     } else {
774         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
775     }
776     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
777     $template->param(SMSnumber     => $data{'smsalertnumber'} );
778     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
779 }
780
781 $template->param( borrower_data => \%data );
782 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
783 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
784 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
785
786 $template->param(
787   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
788   destination   => $destination,#to know where u come from and where u must go in redirect
789   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
790 );
791
792 $template->param(
793   patron => $patron ? $patron : \%newdata, # Used by address include templates now
794   nodouble  => $nodouble,
795   borrowernumber  => $borrowernumber, #register number
796   relshiploop => \@relshipdata,
797   btitle=> $default_borrowertitle,
798   modify          => $modify,
799   nok     => $nok,#flag to know if an error
800   NoUpdateLogin =>  $NoUpdateLogin,
801   NoUpdateEmail =>  $NoUpdateEmail,
802   CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
803   );
804
805 # HouseboundModule data
806 $template->param(
807     housebound_role  => Koha::Patron::HouseboundRoles->find($borrowernumber),
808 );
809
810 if(defined($data{'flags'})){
811   $template->param(flags=>$data{'flags'});
812 }
813 if(defined($data{'contacttitle'})){
814   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
815 }
816
817
818 my ( $min, $max ) = Koha::Policy::Patrons::Cardnumber->get_valid_length();
819 if ( defined $min ) {
820     $template->param(
821         minlength_cardnumber => $min,
822         maxlength_cardnumber => $max
823     );
824 }
825
826 if ( C4::Context->preference('TranslateNotices') ) {
827     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
828     $template->param( languages => $translated_languages );
829 }
830
831 $template->param( messages => \@messages );
832 output_html_with_http_headers $input, $cookie, $template->output;
833
834 sub parse_extended_patron_attributes {
835     my ($input) = @_;
836     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
837
838     my @attr = ();
839     my %dups = ();
840     foreach my $key (@patron_attr) {
841         my $value = $input->param($key);
842         next unless defined($value) and $value ne '';
843         my $code     = $input->param("${key}_code");
844         next if exists $dups{$code}->{$value};
845         $dups{$code}->{$value} = 1;
846         push @attr, { code => $code, attribute => $value };
847     }
848     return \@attr;
849 }
850
851 sub patron_attributes_form {
852     my $template = shift;
853     my $attributes = shift;
854     my $op = shift;
855
856     my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
857     my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
858     if ( $attribute_types->count == 0 ) {
859         $template->param(no_patron_attribute_types => 1);
860         return;
861     }
862
863     # map patron's attributes into a more convenient structure
864     my %attr_hash = ();
865     foreach my $attr (@$attributes) {
866         push @{ $attr_hash{$attr->{code}} }, $attr;
867     }
868
869     my @attribute_loop = ();
870     my $i = 0;
871     my %items_by_class;
872     while ( my ( $attr_type ) = $attribute_types->next ) {
873         my $entry = {
874             class             => $attr_type->class(),
875             code              => $attr_type->code(),
876             description       => $attr_type->description(),
877             repeatable        => $attr_type->repeatable(),
878             category          => $attr_type->authorised_value_category(),
879             category_code     => $attr_type->category_code(),
880             mandatory         => $attr_type->mandatory(),
881         };
882         if (exists $attr_hash{$attr_type->code()}) {
883             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
884                 my $newentry = { %$entry };
885                 $newentry->{value} = $attr->{attribute};
886                 $newentry->{use_dropdown} = 0;
887                 if ($attr_type->authorised_value_category()) {
888                     $newentry->{use_dropdown} = 1;
889                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
890                 }
891                 $i++;
892                 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
893                 $newentry->{form_id} = "patron_attr_$i";
894                 push @{$items_by_class{$attr_type->class()}}, $newentry;
895             }
896         } else {
897             $i++;
898             my $newentry = { %$entry };
899             if ($attr_type->authorised_value_category()) {
900                 $newentry->{use_dropdown} = 1;
901                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
902             }
903             $newentry->{form_id} = "patron_attr_$i";
904             push @{$items_by_class{$attr_type->class()}}, $newentry;
905         }
906     }
907     for my $class ( sort keys %items_by_class ) {
908         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
909         my $lib = $av->count ? $av->next->lib : $class;
910         push @attribute_loop, {
911             class => $class,
912             items => $items_by_class{$class},
913             lib   => $lib,
914         }
915     }
916
917     $template->param(patron_attributes => \@attribute_loop);
918
919 }
920
921 sub add_guarantors {
922     my ( $patron, $input ) = @_;
923
924     my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
925     my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
926
927     for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
928         my $guarantor_id = $new_guarantor_id[$i];
929         my $relationship = $new_guarantor_relationship[$i];
930
931         next unless $guarantor_id;
932
933         $patron->add_guarantor(
934             {
935                 guarantor_id => $guarantor_id,
936                 relationship => $relationship,
937             }
938         );
939     }
940 }