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