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