Bug 30874: Reduce number of category fetches
[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         my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
434         $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
435     }
436 }
437
438 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
439 my $sms = $input->param('SMSnumber');
440 if ( defined $sms ) {
441     $newdata{smsalertnumber} = $sms;
442 }
443
444 ###  Error checks should happen before this line.
445 $nok = $nok || scalar(@errors);
446 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
447     my $success;
448         if ($op eq 'insert'){
449                 # we know it's not a duplicate borrowernumber or there would already be an error
450         delete $newdata{password2};
451         $patron = eval { Koha::Patron->new(\%newdata)->store };
452         if ( $@ ) {
453             # FIXME Urgent error handling here, we cannot fail without relevant feedback
454             # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
455             warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
456             push @messages, {error => 'error_on_insert_patron'};
457             $op = "add";
458         } else {
459             $success = 1;
460             add_guarantors( $patron, $input );
461             $borrowernumber = $patron->borrowernumber;
462             $newdata{'borrowernumber'} = $borrowernumber;
463             delete $newdata{password};
464         }
465
466         # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
467         if ( C4::Context->preference("AutoEmailNewUser") ) {
468             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
469             my $emailaddr = $patron->notice_email_address;
470             # if we manage to find a valid email address, send notice 
471             if ($emailaddr) {
472                 eval {
473                     my $letter = GetPreparedLetter(
474                         module      => 'members',
475                         letter_code => 'WELCOME',
476                         branchcode  => $patron->branchcode,,
477                         lang        => $patron->lang || 'default',
478                         tables      => {
479                             'branches'  => $patron->branchcode,
480                             'borrowers' => $patron->borrowernumber,
481                         },
482                         want_librarian => 1,
483                     ) or return;
484
485                     my $message_id = EnqueueLetter(
486                         {
487                             letter                 => $letter,
488                             borrowernumber         => $patron->id,
489                             to_address             => $emailaddr,
490                             message_transport_type => 'email'
491                         }
492                     );
493                     SendQueuedMessages({ message_id => $message_id });
494                 };
495                 if ($@) {
496                     $template->param( error_alert => $@ );
497                 }
498             }
499         }
500
501         if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
502             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
503         }
504
505         # Create HouseboundRole if necessary.
506         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
507         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
508         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
509         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
510         # Only create a HouseboundRole if patron has a role.
511         if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
512             Koha::Patron::HouseboundRole->new({
513                 borrowernumber_id    => $borrowernumber,
514                 housebound_chooser   => $hsbnd_chooser,
515                 housebound_deliverer => $hsbnd_deliverer,
516             })->store;
517         }
518
519     } elsif ($op eq 'save') {
520
521         if ($NoUpdateLogin) {
522             delete $newdata{'password'};
523             delete $newdata{'userid'};
524         }
525
526         $patron = Koha::Patrons->find( $borrowernumber );
527
528         if ($NoUpdateEmail) {
529             delete $newdata{'email'};
530             delete $newdata{'emailpro'};
531             delete $newdata{'B_email'};
532         }
533
534         delete $newdata{password2};
535
536         eval {
537             $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
538                                                                     # updating any columns in the borrowers table,
539                                                                     # which can happen if we're only editing the
540                                                                     # patron attributes or messaging preferences sections
541         };
542         if ( $@ ) {
543             warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
544             push @messages, {error => 'error_on_update_patron'};
545             $op = "modify";
546         } else {
547
548             $success = 1;
549             # Update or create our HouseboundRole if necessary.
550             my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
551             my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
552             $hsbnd_chooser = 1 if $input->param('housebound_chooser');
553             $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
554             if ( $housebound_role ) {
555                 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
556                     # Update our HouseboundRole.
557                     $housebound_role
558                         ->housebound_chooser($hsbnd_chooser)
559                         ->housebound_deliverer($hsbnd_deliverer)
560                         ->store;
561                 } else {
562                     $housebound_role->delete; # No longer needed.
563                 }
564             } else {
565                 # Only create a HouseboundRole if patron has a role.
566                 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
567                     $housebound_role = Koha::Patron::HouseboundRole->new({
568                         borrowernumber_id    => $borrowernumber,
569                         housebound_chooser   => $hsbnd_chooser,
570                         housebound_deliverer => $hsbnd_deliverer,
571                     })->store;
572                 }
573             }
574
575             # should never raise an exception as password validity is checked above
576             my $password = $newdata{password};
577             if ( $password and $password ne '****' ) {
578                 $patron->set_password({ password => $password });
579             }
580
581             add_guarantors( $patron, $input );
582             if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
583                 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
584             }
585         }
586     }
587
588     if ( $success ) {
589         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
590             $patron->extended_attributes->filter_by_branch_limitations->delete;
591             $patron->extended_attributes($extended_patron_attributes);
592         }
593
594         if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
595             # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
596             $destination = 'not_circ';
597         }
598         print scalar( $destination eq "circ" )
599           ? $input->redirect(
600             "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
601           : $input->redirect(
602             "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
603           );
604         exit; # You can only send 1 redirect!  After that, content or other headers don't matter.
605     }
606 }
607
608 if ($delete){
609         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
610         exit;           # same as above
611 }
612
613 if ($nok or !$nodouble){
614     $op="add" if ($op eq "insert");
615     $op="modify" if ($op eq "save");
616     %data=%newdata; 
617     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
618     unless ($step){  
619         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
620     }  
621
622 if (C4::Context->preference("IndependentBranches")) {
623     my $userenv = C4::Context->userenv;
624     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
625         unless ($userenv->{branch} eq $data{'branchcode'}){
626             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
627             exit;
628         }
629     }
630 }
631
632 # Define the fields to be pre-filled in guarantee records
633 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
634 my @prefill_fields=split(/\,/,$prefillguarantorfields);
635
636 if ($op eq 'add'){
637     if ($guarantor_id) {
638         foreach (@prefill_fields) {
639             $newdata{$_} = $guarantor->$_;
640         }
641     }
642     $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);
643 }
644 if ($op eq "modify")  {
645     $template->param( updtype => 'M',modify => 1 );
646     $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;
647     if ( $step == 4 ) {
648         $template->param( categorycode => $borrower_data->{'categorycode'} );
649     }
650 }
651 if ( $op eq "duplicate" ) {
652     $template->param( updtype => 'I' );
653     $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;
654     $data{'cardnumber'} = "";
655 }
656
657 if(!defined($data{'sex'})){
658     $template->param( none => 1);
659 } elsif($data{'sex'} eq 'F'){
660     $template->param( female => 1);
661 } elsif ($data{'sex'} eq 'M'){
662     $template->param(  male => 1);
663 } elsif ($data{'sex'} eq 'O') {
664     $template->param( other => 1);
665 } else {
666     $template->param(  none => 1);
667 }
668
669 ##Now all the data to modify a member.
670
671 my @typeloop;
672 my $no_categories = 1;
673 my $no_add;
674 foreach my $category_type (qw(C A S P I X)) {
675     my $categories_limits = { category_type => $category_type };
676     $categories_limits->{can_be_guarantee} = 1 if ($guarantor_id);
677     my $patron_categories = Koha::Patron::Categories->search_with_library_limits( $categories_limits, {order_by => ['categorycode']} );
678     $no_categories = 0 if $patron_categories->count > 0;
679
680     my @categoryloop;
681     while ( my $patron_category = $patron_categories->next ) {
682         $categorycode = $patron_category->categorycode unless defined($categorycode); #If none passed in, select the first
683         push @categoryloop,
684           { 'categorycode' => $patron_category->categorycode,
685             'categoryname' => $patron_category->description,
686             'effective_min_password_length' => $patron_category->effective_min_password_length,
687             'effective_require_strong_password' => $patron_category->effective_require_strong_password,
688             'categorycodeselected' =>
689               ( $patron_category->categorycode eq $categorycode ),
690           };
691     }
692     my %typehash;
693     $typehash{'typename'} = $category_type;
694     my $typedescription = "typename_" . $typehash{'typename'};
695     $typehash{'categoryloop'} = \@categoryloop;
696     push @typeloop,
697       { 'typename'       => $category_type,
698         $typedescription => 1,
699         'categoryloop'   => \@categoryloop
700       };
701 }
702 $template->param(
703     typeloop      => \@typeloop,
704     no_categories => $no_categories,
705 );
706
707 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
708 $template->param(
709     cities    => $cities,
710 );
711
712 my $default_borrowertitle = '';
713 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
714
715 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
716 my @relshipdata;
717 while (@relationships) {
718   my $relship = shift @relationships || '';
719   my %row = ('relationship' => $relship);
720   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
721     $row{'selected'}=' selected';
722   } else {
723     $row{'selected'}='';
724   }
725   push(@relshipdata, \%row);
726 }
727
728 my %flags = (
729     'gonenoaddress' => ['gonenoaddress'],
730     'lost'          => ['lost']
731 );
732
733 my @flagdata;
734 foreach ( keys(%flags) ) {
735     my $key = $_;
736     my %row = (
737         'key'  => $key,
738         'name' => $flags{$key}[0]
739     );
740     if ( $data{$key} ) {
741         $row{'yes'} = ' checked';
742         $row{'no'}  = '';
743     }
744     else {
745         $row{'yes'} = '';
746         $row{'no'}  = ' checked';
747     }
748     push @flagdata, \%row;
749 }
750
751 # get Branch Loop
752 # in modify mod: userbranch value comes from borrowers table
753 # in add    mod: userbranch value comes from branches table (ip correspondence)
754
755 my $userbranch = '';
756 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
757     $userbranch = C4::Context->userenv->{'branch'};
758 }
759
760 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
761     $userbranch = $data{'branchcode'};
762 }
763 $template->param( userbranch => $userbranch );
764
765 if ( Koha::Libraries->search->count < 1 ){
766     $no_add = 1;
767     $template->param(no_branches => 1);
768 }
769 if($no_categories){
770     $no_add = 1;
771     $template->param(no_categories => 1);
772 }
773 $template->param(no_add => $no_add);
774 # --------------------------------------------------------------------------------------------------------
775
776 $template->param( sort1 => $data{'sort1'});
777 $template->param( sort2 => $data{'sort2'});
778 $template->param( autorenew => $data{'autorenew'});
779
780 if ($nok) {
781     foreach my $error (@errors) {
782         $template->param($error) || $template->param( $error => 1);
783     }
784     $template->param(nok => 1);
785 }
786   
787   #Formatting data for display    
788   
789 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
790   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
791 }
792 if ( $op eq 'duplicate' ) {
793     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
794     my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
795     $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
796 }
797 if (C4::Context->preference('uppercasesurnames')) {
798     $data{'surname'} &&= uc( $data{'surname'} );
799     $data{'contactname'} &&= uc( $data{'contactname'} );
800 }
801
802 foreach (qw(dateenrolled dateexpiry dateofbirth password_expiration_date)) {
803     if ( $data{$_} ) {
804        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
805     }
806     $template->param( $_ => $data{$_});
807 }
808
809 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
810     patron_attributes_form( $template, $extended_patron_attributes, $op );
811 }
812
813 if (C4::Context->preference('EnhancedMessagingPreferences')) {
814     if ($op eq 'add') {
815         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
816     } else {
817         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
818     }
819     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
820     $template->param(SMSnumber     => $data{'smsalertnumber'} );
821     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
822 }
823
824 $template->param( borrower_data => \%data );
825 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
826 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
827 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
828
829 $template->param(
830   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
831   category_type => $category_type,#to know the category type of the borrower
832   "$category_type"  => 1,# associate with step to know where u are
833   destination   => $destination,#to know where u come from and where u must go in redirect
834   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
835   "op$op"   => 1);
836
837 $template->param(
838   patron => $patron ? $patron : \%newdata, # Used by address include templates now
839   nodouble  => $nodouble,
840   borrowernumber  => $borrowernumber, #register number
841   relshiploop => \@relshipdata,
842   btitle=> $default_borrowertitle,
843   flagloop  => \@flagdata,
844   category_type =>$category_type,
845   modify          => $modify,
846   nok     => $nok,#flag to know if an error
847   NoUpdateLogin =>  $NoUpdateLogin,
848   NoUpdateEmail =>  $NoUpdateEmail,
849   CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
850   );
851
852 # Generate CSRF token
853 $template->param( csrf_token =>
854       Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
855 );
856
857 # HouseboundModule data
858 $template->param(
859     housebound_role  => Koha::Patron::HouseboundRoles->find($borrowernumber),
860 );
861
862 if(defined($data{'flags'})){
863   $template->param(flags=>$data{'flags'});
864 }
865 if(defined($data{'contacttitle'})){
866   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
867 }
868
869
870 my ( $min, $max ) = C4::Members::get_cardnumber_length();
871 if ( defined $min ) {
872     $template->param(
873         minlength_cardnumber => $min,
874         maxlength_cardnumber => $max
875     );
876 }
877
878 if ( C4::Context->preference('TranslateNotices') ) {
879     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
880     $template->param( languages => $translated_languages );
881 }
882
883 $template->param( messages => \@messages );
884 output_html_with_http_headers $input, $cookie, $template->output;
885
886 sub parse_extended_patron_attributes {
887     my ($input) = @_;
888     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
889
890     my @attr = ();
891     my %dups = ();
892     foreach my $key (@patron_attr) {
893         my $value = $input->param($key);
894         next unless defined($value) and $value ne '';
895         my $code     = $input->param("${key}_code");
896         next if exists $dups{$code}->{$value};
897         $dups{$code}->{$value} = 1;
898         push @attr, { code => $code, attribute => $value };
899     }
900     return \@attr;
901 }
902
903 sub patron_attributes_form {
904     my $template = shift;
905     my $attributes = shift;
906     my $op = shift;
907
908     my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
909     my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
910     if ( $attribute_types->count == 0 ) {
911         $template->param(no_patron_attribute_types => 1);
912         return;
913     }
914
915     # map patron's attributes into a more convenient structure
916     my %attr_hash = ();
917     foreach my $attr (@$attributes) {
918         push @{ $attr_hash{$attr->{code}} }, $attr;
919     }
920
921     my @attribute_loop = ();
922     my $i = 0;
923     my %items_by_class;
924     while ( my ( $attr_type ) = $attribute_types->next ) {
925         my $entry = {
926             class             => $attr_type->class(),
927             code              => $attr_type->code(),
928             description       => $attr_type->description(),
929             repeatable        => $attr_type->repeatable(),
930             category          => $attr_type->authorised_value_category(),
931             category_code     => $attr_type->category_code(),
932             mandatory         => $attr_type->mandatory(),
933         };
934         if (exists $attr_hash{$attr_type->code()}) {
935             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
936                 my $newentry = { %$entry };
937                 $newentry->{value} = $attr->{attribute};
938                 $newentry->{use_dropdown} = 0;
939                 if ($attr_type->authorised_value_category()) {
940                     $newentry->{use_dropdown} = 1;
941                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
942                 }
943                 $i++;
944                 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
945                 $newentry->{form_id} = "patron_attr_$i";
946                 push @{$items_by_class{$attr_type->class()}}, $newentry;
947             }
948         } else {
949             $i++;
950             my $newentry = { %$entry };
951             if ($attr_type->authorised_value_category()) {
952                 $newentry->{use_dropdown} = 1;
953                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
954             }
955             $newentry->{form_id} = "patron_attr_$i";
956             push @{$items_by_class{$attr_type->class()}}, $newentry;
957         }
958     }
959     for my $class ( sort keys %items_by_class ) {
960         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
961         my $lib = $av->count ? $av->next->lib : $class;
962         push @attribute_loop, {
963             class => $class,
964             items => $items_by_class{$class},
965             lib   => $lib,
966         }
967     }
968
969     $template->param(patron_attributes => \@attribute_loop);
970
971 }
972
973 sub add_guarantors {
974     my ( $patron, $input ) = @_;
975
976     my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
977     my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
978
979     for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
980         my $guarantor_id = $new_guarantor_id[$i];
981         my $relationship = $new_guarantor_relationship[$i];
982
983         next unless $guarantor_id;
984
985         $patron->add_guarantor(
986             {
987                 guarantor_id => $guarantor_id,
988                 relationship => $relationship,
989             }
990         );
991     }
992 }
993
994 # Local Variables:
995 # tab-width: 8
996 # End: