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