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