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