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