3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
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.
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.
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>.
26 use List::MoreUtils qw/uniq/;
36 use C4::Form::MessagingPreferences;
38 use Koha::AuthorisedValues;
39 use Koha::Patron::Debarments;
44 use Koha::Patron::Attribute::Types;
45 use Koha::Patron::Categories;
46 use Koha::Patron::HouseboundRole;
47 use Koha::Patron::HouseboundRoles;
50 use Koha::SMS::Providers;
55 $debug = $ENV{DEBUG} || 0;
59 ($debug) or $debug = $input->param('debug') || 0;
62 my $dbh = C4::Context->dbh;
64 my ($template, $loggedinuser, $cookie)
65 = get_template_and_user({template_name => "members/memberentrygen.tt",
68 flagsrequired => {borrowers => 'edit_borrowers'},
69 debug => ($debug) ? 1 : 0,
72 my $borrowernumber = $input->param('borrowernumber');
73 my $patron = Koha::Patrons->find($borrowernumber);
75 if ( $borrowernumber and not $patron ) {
76 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
79 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
80 my @providers = Koha::SMS::Providers->search();
81 $template->param( sms_providers => \@providers );
84 my $actionType = $input->param('actionType') || '';
85 my $modify = $input->param('modify');
86 my $delete = $input->param('delete');
87 my $op = $input->param('op');
88 my $destination = $input->param('destination');
89 my $cardnumber = $input->param('cardnumber');
90 my $check_member = $input->param('check_member');
91 my $nodouble = $input->param('nodouble');
92 my $duplicate = $input->param('duplicate');
93 my $quickadd = $input->param('quickadd');
94 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
95 # modifying an existing patron, it ipso facto
96 # isn't a duplicate. Marking FIXME because this
97 # script needs to be refactored.
98 my $nok = $input->param('nok');
99 my $step = $input->param('step') || 0;
104 my $userenv = C4::Context->userenv;
107 ## Deal with guarantor stuff
108 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
110 my @relations = split /,|\|/, C4::Context->preference('borrowerRelationship');
111 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
112 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
114 my $guarantor_id = $input->param('guarantor_id');
115 my $guarantor = undef;
116 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
117 $template->param( guarantor => $guarantor );
119 my @delete_guarantor = $input->multi_param('delete_guarantor');
120 foreach my $id ( @delete_guarantor ) {
121 my $r = Koha::Patron::Relationships->find( $id );
125 ## Deal with debarments
127 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
128 my @debarments_to_remove = $input->multi_param('remove_debarment');
129 foreach my $d ( @debarments_to_remove ) {
132 if ( $input->param('add_debarment') ) {
134 my $expiration = $input->param('debarred_expiration');
137 ? dt_from_string($expiration)->ymd
142 borrowernumber => $borrowernumber,
144 comment => scalar $input->param('debarred_comment'),
145 expiration => $expiration,
150 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
152 # function to designate mandatory fields (visually with css)
153 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
154 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
155 foreach (@field_check) {
156 $template->param( "mandatory$_" => 1 );
158 # function to designate unwanted fields
159 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
160 @field_check=split(/\|/,$check_BorrowerUnwantedField);
161 foreach (@field_check) {
163 $template->param( "no$_" => 1 );
165 $template->param( "add" => 1 ) if ( $op eq 'add' );
166 $template->param( "quickadd" => 1 ) if ( $quickadd );
167 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
168 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
169 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
170 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
171 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
173 # check permission to modify email info.
174 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
178 $borrower_data = $patron->unblessed;
179 $borrower_data->{category_type} = $patron->category->category_type;
182 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
183 my $category_type = $input->param('category_type') || '';
184 unless ($category_type or !($categorycode)){
185 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
186 $category_type = $borrowercategory->category_type;
187 my $category_name = $borrowercategory->description;
188 $template->param("categoryname"=>$category_name);
190 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
192 # if a add or modify is requested => check validity of data.
193 %data = %$borrower_data if ($borrower_data);
195 # initialize %newdata
196 my %newdata; # comes from $input->param()
197 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
198 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
199 foreach my $key (@names) {
200 if (defined $input->param($key)) {
201 $newdata{$key} = $input->param($key);
205 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
206 next unless exists $newdata{$_};
207 my $userdate = $newdata{$_} or next;
209 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
210 if ( $formatteddate ) {
211 $newdata{$_} = $formatteddate;
213 $template->param( "ERROR_$_" => 1 );
214 push(@errors,"ERROR_$_");
218 # check permission to modify login info.
219 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
224 # remove keys from %newdata that is not part of patron's attributes
226 my @keys_to_delete = (
227 qr/^BorrowerMandatoryField$/,
236 qr/^setting_extended_patron_attributes$/,
237 qr/^setting_messaging_prefs$/,
245 qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
246 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
249 qr/^guarantor_firstname$/,
250 qr/^guarantor_surname$/,
251 qr/^delete_guarantor$/,
253 for my $regexp (@keys_to_delete) {
254 for (keys %newdata) {
255 delete($newdata{$_}) if /$regexp/;
260 # Test uniqueness of surname, firstname and dateofbirth
261 if ( ( $op eq 'insert' ) and !$nodouble ) {
262 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
264 for my $f ( @dup_fields ) {
265 $conditions->{$f} = $newdata{$f} if $newdata{$f};
268 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
269 if ( $patrons->count > 0) {
271 $check_member = $patrons->next->borrowernumber;
275 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
276 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
277 foreach my $gid ( @new_guarantor_id ) {
278 my $patron = Koha::Patrons->find( $gid );
279 my $relationship = shift( @new_guarantor_relationship );
281 my $g = { patron => $patron, relationship => $relationship };
282 push( @new_guarantors, $g );
284 $template->param( new_guarantors => \@new_guarantors );
288 ###############test to take the right zipcode, country and city name ##############
289 # set only if parameter was passed from the form
290 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
291 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
292 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
294 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
296 # builds default userid
297 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
298 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
299 my $fake_patron = Koha::Patron->new;
300 $fake_patron->userid($patron->userid) if $patron; # editing
301 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
302 # Full page edit, firstname and surname input zones are present
303 $fake_patron->firstname($newdata{firstname});
304 $fake_patron->surname($newdata{surname});
305 $fake_patron->generate_userid;
306 $newdata{'userid'} = $fake_patron->userid;
308 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
309 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
310 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
311 # FIXME clean thiscode newdata vs data is very confusing
312 $fake_patron->firstname($data{firstname});
313 $fake_patron->surname($data{surname});
314 $fake_patron->generate_userid;
315 $newdata{'userid'} = $fake_patron->userid;
318 $newdata{'userid'} = $data{'userid'};
322 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
323 my $extended_patron_attributes;
324 if ($op eq 'save' || $op eq 'insert'){
326 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
327 unless Koha::Token->new->check_csrf({
328 session_id => scalar $input->cookie('CGISESSID'),
329 token => scalar $input->param('csrf_token'),
332 # If the cardnumber is blank, treat it as null.
333 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
335 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
336 push @errors, $error_code == 1
337 ? 'ERROR_cardnumber_already_exists'
339 ? 'ERROR_cardnumber_length'
344 if ($op eq 'save' && $step == 3) {
345 $dateofbirth = $patron->dateofbirth;
348 $dateofbirth = $newdata{dateofbirth};
351 if ( $dateofbirth ) {
352 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
353 my $age = $patron->get_age;
354 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
355 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
356 if (($high && ($age > $high)) or ($age < $low)) {
357 push @errors, 'ERROR_age_limitations';
358 $template->param( age_low => $low);
359 $template->param( age_high => $high);
363 if (C4::Context->preference("IndependentBranches")) {
364 unless ( C4::Context->IsSuperLibrarian() ){
365 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
366 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
367 push @errors, "ERROR_branch";
371 # Check if the 'userid' is unique. 'userid' might not always be present in
372 # the edited values list when editing certain sub-forms. Get it straight
373 # from the DB if absent.
374 my $userid = $newdata{ userid } // $borrower_data->{ userid };
375 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
376 $p->userid( $userid );
377 unless ( $p->has_valid_userid ) {
378 push @errors, "ERROR_login_exist";
381 my $password = $input->param('password');
382 my $password2 = $input->param('password2');
383 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
385 if ( $password and $password ne '****' ) {
386 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, Koha::Patron::Categories->find($categorycode) );
387 unless ( $is_valid ) {
388 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
389 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
390 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
395 my $emailprimary = $input->param('email');
396 my $emailsecondary = $input->param('emailpro');
397 my $emailalt = $input->param('B_email');
400 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
402 if ($emailsecondary) {
403 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
406 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
409 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
410 $extended_patron_attributes = parse_extended_patron_attributes($input);
411 for my $attr ( @$extended_patron_attributes ) {
412 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
413 my $attribute = Koha::Patron::Attribute->new($attr);
414 eval {$attribute->check_unique_id};
416 push @errors, "ERROR_extended_unique_id_failed";
417 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
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()
427 elsif ( $borrowernumber ) {
428 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
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;
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;
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 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
449 if ($op eq 'insert'){
450 # we know it's not a duplicate borrowernumber or there would already be an error
451 delete $newdata{password2};
452 $patron = eval { Koha::Patron->new(\%newdata)->store };
454 # FIXME Urgent error handling here, we cannot fail without relevant feedback
455 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
456 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
457 push @messages, {error => 'error_on_insert_patron'};
461 add_guarantors( $patron, $input );
462 $borrowernumber = $patron->borrowernumber;
463 $newdata{'borrowernumber'} = $borrowernumber;
466 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
467 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
468 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
470 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
471 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
472 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
474 elsif ($newdata{email} =~ /\w\@\w/) {
475 $emailaddr = $newdata{email}
477 elsif ($newdata{emailpro} =~ /\w\@\w/) {
478 $emailaddr = $newdata{emailpro}
480 elsif ($newdata{B_email} =~ /\w\@\w/) {
481 $emailaddr = $newdata{B_email}
483 # if we manage to find a valid email address, send notice
485 $newdata{emailaddr} = $emailaddr;
488 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
491 $template->param(error_alert => $@);
492 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
493 $template->{VARS}->{'error_alert'} = "no_email";
495 $template->{VARS}->{'info_alert'} = 1;
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'});
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,
518 } elsif ($op eq 'save') {
520 if ($NoUpdateLogin) {
521 delete $newdata{'password'};
522 delete $newdata{'userid'};
525 $patron = Koha::Patrons->find( $borrowernumber );
527 if ($NoUpdateEmail) {
528 delete $newdata{'email'};
529 delete $newdata{'emailpro'};
530 delete $newdata{'B_email'};
533 $newdata{debarredcomment} = $newdata{debarred_comment};
534 delete $newdata{debarred_comment};
535 delete $newdata{password2};
538 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
539 # updating any columns in the borrowers table,
540 # which can happen if we're only editing the
541 # patron attributes or messaging preferences sections
544 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
545 push @messages, {error => 'error_on_update_patron'};
550 # Update or create our HouseboundRole if necessary.
551 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
552 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
553 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
554 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
555 if ( $housebound_role ) {
556 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
557 # Update our HouseboundRole.
559 ->housebound_chooser($hsbnd_chooser)
560 ->housebound_deliverer($hsbnd_deliverer)
563 $housebound_role->delete; # No longer needed.
566 # Only create a HouseboundRole if patron has a role.
567 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
568 $housebound_role = Koha::Patron::HouseboundRole->new({
569 borrowernumber_id => $borrowernumber,
570 housebound_chooser => $hsbnd_chooser,
571 housebound_deliverer => $hsbnd_deliverer,
576 # should never raise an exception as password validity is checked above
577 my $password = $newdata{password};
578 if ( $password and $password ne '****' ) {
579 $patron->set_password({ password => $password });
582 add_guarantors( $patron, $input );
583 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
584 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
590 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
591 $patron->extended_attributes->filter_by_branch_limitations->delete;
592 $patron->extended_attributes($extended_patron_attributes);
595 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
596 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
597 $destination = 'not_circ';
599 print scalar( $destination eq "circ" )
601 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
603 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
605 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
610 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
611 exit; # same as above
614 if ($nok or !$nodouble){
615 $op="add" if ($op eq "insert");
616 $op="modify" if ($op eq "save");
618 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
620 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
623 if (C4::Context->preference("IndependentBranches")) {
624 my $userenv = C4::Context->userenv;
625 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
626 unless ($userenv->{branch} eq $data{'branchcode'}){
627 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
633 # Define the fields to be pre-filled in guarantee records
634 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
635 my @prefill_fields=split(/\,/,$prefillguarantorfields);
639 foreach (@prefill_fields) {
640 $newdata{$_} = $guarantor->$_;
643 $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);
645 if ($op eq "modify") {
646 $template->param( updtype => 'M',modify => 1 );
647 $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;
649 $template->param( categorycode => $borrower_data->{'categorycode'} );
652 if ( $op eq "duplicate" ) {
653 $template->param( updtype => 'I' );
654 $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;
655 $data{'cardnumber'} = "";
658 if(!defined($data{'sex'})){
659 $template->param( none => 1);
660 } elsif($data{'sex'} eq 'F'){
661 $template->param( female => 1);
662 } elsif ($data{'sex'} eq 'M'){
663 $template->param( male => 1);
664 } elsif ($data{'sex'} eq 'O') {
665 $template->param( other => 1);
667 $template->param( none => 1);
670 ##Now all the data to modify a member.
673 my $no_categories = 1;
675 foreach my $category_type (qw(C A S P I X)) {
676 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
677 $no_categories = 0 if $patron_categories->count > 0;
680 while ( my $patron_category = $patron_categories->next ) {
682 { 'categorycode' => $patron_category->categorycode,
683 'categoryname' => $patron_category->description,
684 'effective_min_password_length' => $patron_category->effective_min_password_length,
685 'effective_require_strong_password' => $patron_category->effective_require_strong_password,
686 'categorycodeselected' =>
687 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
691 $typehash{'typename'} = $category_type;
692 my $typedescription = "typename_" . $typehash{'typename'};
693 $typehash{'categoryloop'} = \@categoryloop;
695 { 'typename' => $category_type,
696 $typedescription => 1,
697 'categoryloop' => \@categoryloop
701 typeloop => \@typeloop,
702 no_categories => $no_categories,
705 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
706 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
708 roadtypes => $roadtypes,
712 my $default_borrowertitle = '';
713 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
715 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
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';
725 push(@relshipdata, \%row);
729 'gonenoaddress' => ['gonenoaddress'],
734 foreach ( keys(%flags) ) {
738 'name' => $flags{$key}[0]
741 $row{'yes'} = ' checked';
746 $row{'no'} = ' checked';
748 push @flagdata, \%row;
752 # in modify mod: userbranch value comes from borrowers table
753 # in add mod: userbranch value comes from branches table (ip correspondence)
756 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
757 $userbranch = C4::Context->userenv->{'branch'};
760 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
761 $userbranch = $data{'branchcode'};
763 $template->param( userbranch => $userbranch );
765 if ( Koha::Libraries->search->count < 1 ){
767 $template->param(no_branches => 1);
771 $template->param(no_categories => 1);
773 $template->param(no_add => $no_add);
774 # --------------------------------------------------------------------------------------------------------
776 $template->param( sort1 => $data{'sort1'});
777 $template->param( sort2 => $data{'sort2'});
778 $template->param( autorenew => $data{'autorenew'});
781 foreach my $error (@errors) {
782 $template->param($error) || $template->param( $error => 1);
784 $template->param(nok => 1);
787 #Formatting data for display
789 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
790 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
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} );
797 if (C4::Context->preference('uppercasesurnames')) {
798 $data{'surname'} &&= uc( $data{'surname'} );
799 $data{'contactname'} &&= uc( $data{'contactname'} );
802 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
804 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
806 $template->param( $_ => $data{$_});
809 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
810 patron_attributes_form( $template, $extended_patron_attributes, $op );
813 if (C4::Context->preference('EnhancedMessagingPreferences')) {
815 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
817 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
819 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
820 $template->param(SMSnumber => $data{'smsalertnumber'} );
821 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
824 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
825 $debug and warn "memberentry step: $step";
826 $template->param(%data);
827 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
828 $template->param( step => $step ) if $step; # associate with step to know where u are
831 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
832 category_type => $category_type,#to know the category type of the borrower
833 "$category_type" => 1,# associate with step to know where u are
834 destination => $destination,#to know wher u come from and wher u must go in redirect
835 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
839 patron => $patron ? $patron : \%newdata, # Used by address include templates now
840 nodouble => $nodouble,
841 borrowernumber => $borrowernumber, #register number
842 relshiploop => \@relshipdata,
843 btitle=> $default_borrowertitle,
844 flagloop => \@flagdata,
845 category_type =>$category_type,
847 nok => $nok,#flag to know if an error
848 NoUpdateLogin => $NoUpdateLogin,
849 NoUpdateEmail => $NoUpdateEmail,
852 # Generate CSRF token
853 $template->param( csrf_token =>
854 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
857 # HouseboundModule data
859 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
862 if(defined($data{'flags'})){
863 $template->param(flags=>$data{'flags'});
865 if(defined($data{'contacttitle'})){
866 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
870 my ( $min, $max ) = C4::Members::get_cardnumber_length();
871 if ( defined $min ) {
873 minlength_cardnumber => $min,
874 maxlength_cardnumber => $max
878 if ( C4::Context->preference('TranslateNotices') ) {
879 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
880 $template->param( languages => $translated_languages );
883 $template->param( messages => \@messages );
884 output_html_with_http_headers $input, $cookie, $template->output;
886 sub parse_extended_patron_attributes {
888 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
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 };
903 sub patron_attributes_form {
904 my $template = shift;
905 my $attributes = shift;
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);
915 # map patron's attributes into a more convenient structure
917 foreach my $attr (@$attributes) {
918 push @{ $attr_hash{$attr->{code}} }, $attr;
921 my @attribute_loop = ();
924 while ( my ( $attr_type ) = $attribute_types->next ) {
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(),
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});
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;
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());
955 $newentry->{form_id} = "patron_attr_$i";
956 push @{$items_by_class{$attr_type->class()}}, $newentry;
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, {
964 items => $items_by_class{$class},
969 $template->param(patron_attributes => \@attribute_loop);
974 my ( $patron, $input ) = @_;
976 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
977 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
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];
983 next unless $guarantor_id;
985 $patron->add_guarantor(
987 guarantor_id => $guarantor_id,
988 relationship => $relationship,