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