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 my $dbh = C4::Context->dbh;
57 my ($template, $loggedinuser, $cookie)
58 = get_template_and_user({template_name => "members/memberentrygen.tt",
61 flagsrequired => {borrowers => 'edit_borrowers'},
64 my $borrowernumber = $input->param('borrowernumber');
65 my $patron = Koha::Patrons->find($borrowernumber);
67 if ( $borrowernumber and not $patron ) {
68 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
71 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
72 my @providers = Koha::SMS::Providers->search();
73 $template->param( sms_providers => \@providers );
76 my $actionType = $input->param('actionType') || '';
77 my $modify = $input->param('modify');
78 my $delete = $input->param('delete');
79 my $op = $input->param('op');
80 my $destination = $input->param('destination');
81 my $cardnumber = $input->param('cardnumber');
82 my $check_member = $input->param('check_member');
83 my $nodouble = $input->param('nodouble');
84 my $duplicate = $input->param('duplicate');
85 my $quickadd = $input->param('quickadd');
86 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
87 # modifying an existing patron, it ipso facto
88 # isn't a duplicate. Marking FIXME because this
89 # script needs to be refactored.
90 my $nok = $input->param('nok');
91 my $step = $input->param('step') || 0;
96 my $userenv = C4::Context->userenv;
99 ## Deal with guarantor stuff
100 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
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 );
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 );
112 my @delete_guarantor = $input->multi_param('delete_guarantor');
113 foreach my $id ( @delete_guarantor ) {
114 my $r = Koha::Patron::Relationships->find( $id );
118 ## Deal with debarments
120 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
121 my @debarments_to_remove = $input->multi_param('remove_debarment');
122 foreach my $d ( @debarments_to_remove ) {
125 if ( $input->param('add_debarment') ) {
127 my $expiration = $input->param('debarred_expiration');
130 ? dt_from_string($expiration)->ymd
135 borrowernumber => $borrowernumber,
137 comment => scalar $input->param('debarred_comment'),
138 expiration => $expiration,
143 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
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 );
151 # function to designate unwanted fields
152 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
153 @field_check=split(/\|/,$check_BorrowerUnwantedField);
154 foreach (@field_check) {
156 $template->param( "no$_" => 1 );
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 } );
166 # check permission to modify email info.
167 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
171 $borrower_data = $patron->unblessed;
172 $borrower_data->{category_type} = $patron->category->category_type;
175 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
176 my $category_type = $input->param('category_type') || '';
177 unless ($category_type or !($categorycode)){
178 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
179 $category_type = $borrowercategory->category_type;
180 my $category_name = $borrowercategory->description;
181 $template->param("categoryname"=>$category_name);
183 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
185 # if a add or modify is requested => check validity of data.
186 %data = %$borrower_data if ($borrower_data);
188 # initialize %newdata
189 my %newdata; # comes from $input->param()
190 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
191 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
192 foreach my $key (@names) {
193 if (defined $input->param($key)) {
194 $newdata{$key} = $input->param($key);
198 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
199 next unless exists $newdata{$_};
200 my $userdate = $newdata{$_} or next;
202 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
203 if ( $formatteddate ) {
204 $newdata{$_} = $formatteddate;
206 $template->param( "ERROR_$_" => 1 );
207 push(@errors,"ERROR_$_");
211 # check permission to modify login info.
212 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
217 # remove keys from %newdata that is not part of patron's attributes
219 my @keys_to_delete = (
220 qr/^BorrowerMandatoryField$/,
229 qr/^setting_extended_patron_attributes$/,
230 qr/^setting_messaging_prefs$/,
238 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
239 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
242 qr/^guarantor_firstname$/,
243 qr/^guarantor_surname$/,
244 qr/^delete_guarantor$/,
246 for my $regexp (@keys_to_delete) {
247 for (keys %newdata) {
248 delete($newdata{$_}) if /$regexp/;
253 # Test uniqueness of surname, firstname and dateofbirth
254 if ( ( $op eq 'insert' ) and !$nodouble ) {
255 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
257 for my $f ( @dup_fields ) {
258 $conditions->{$f} = $newdata{$f} if $newdata{$f};
261 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
262 if ( $patrons->count > 0) {
264 $check_member = $patrons->next->borrowernumber;
268 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
269 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
270 foreach my $gid ( @new_guarantor_id ) {
271 my $patron = Koha::Patrons->find( $gid );
272 my $relationship = shift( @new_guarantor_relationship );
274 my $g = { patron => $patron, relationship => $relationship };
275 push( @new_guarantors, $g );
277 $template->param( new_guarantors => \@new_guarantors );
281 ###############test to take the right zipcode, country and city name ##############
282 # set only if parameter was passed from the form
283 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
284 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
285 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
287 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
289 # builds default userid
290 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
291 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
292 my $fake_patron = Koha::Patron->new;
293 $fake_patron->userid($patron->userid) if $patron; # editing
294 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
295 # Full page edit, firstname and surname input zones are present
296 $fake_patron->firstname($newdata{firstname});
297 $fake_patron->surname($newdata{surname});
298 $fake_patron->generate_userid;
299 $newdata{'userid'} = $fake_patron->userid;
301 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
302 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
303 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
304 # FIXME clean thiscode newdata vs data is very confusing
305 $fake_patron->firstname($data{firstname});
306 $fake_patron->surname($data{surname});
307 $fake_patron->generate_userid;
308 $newdata{'userid'} = $fake_patron->userid;
311 $newdata{'userid'} = $data{'userid'};
315 my $extended_patron_attributes;
316 if ($op eq 'save' || $op eq 'insert'){
318 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
319 unless Koha::Token->new->check_csrf({
320 session_id => scalar $input->cookie('CGISESSID'),
321 token => scalar $input->param('csrf_token'),
324 # If the cardnumber is blank, treat it as null.
325 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
327 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
328 push @errors, $error_code == 1
329 ? 'ERROR_cardnumber_already_exists'
331 ? 'ERROR_cardnumber_length'
336 if ($op eq 'save' && $step == 3) {
337 $dateofbirth = $patron->dateofbirth;
340 $dateofbirth = $newdata{dateofbirth};
343 if ( $dateofbirth ) {
344 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
345 my $age = $patron->get_age;
346 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
347 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
348 if (($high && ($age > $high)) or ($age < $low)) {
349 push @errors, 'ERROR_age_limitations';
350 $template->param( age_low => $low);
351 $template->param( age_high => $high);
355 if (C4::Context->preference("IndependentBranches")) {
356 unless ( C4::Context->IsSuperLibrarian() ){
357 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
358 push @errors, "ERROR_branch";
362 # Check if the 'userid' is unique. 'userid' might not always be present in
363 # the edited values list when editing certain sub-forms. Get it straight
364 # from the DB if absent.
365 my $userid = $newdata{ userid } // $borrower_data->{ userid };
366 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
367 $p->userid( $userid );
368 unless ( $p->has_valid_userid ) {
369 push @errors, "ERROR_login_exist";
372 my $password = $input->param('password');
373 my $password2 = $input->param('password2');
374 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
376 if ( $password and $password ne '****' ) {
377 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, Koha::Patron::Categories->find($categorycode) );
378 unless ( $is_valid ) {
379 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
380 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
381 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
386 my $emailprimary = $input->param('email');
387 my $emailsecondary = $input->param('emailpro');
388 my $emailalt = $input->param('B_email');
391 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
393 if ($emailsecondary) {
394 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
397 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
400 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
401 $extended_patron_attributes = parse_extended_patron_attributes($input);
402 for my $attr ( @$extended_patron_attributes ) {
403 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
404 my $attribute = Koha::Patron::Attribute->new($attr);
405 if ( !$attribute->unique_ok ) {
406 push @errors, "ERROR_extended_unique_id_failed";
407 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
409 ERROR_extended_unique_id_failed_code => $attr->{code},
410 ERROR_extended_unique_id_failed_value => $attr->{attribute},
411 ERROR_extended_unique_id_failed_description => $attr_type->description()
417 elsif ( $borrowernumber ) {
418 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
421 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
422 unless ($newdata{'dateexpiry'}){
423 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
424 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
428 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
429 my $sms = $input->param('SMSnumber');
430 if ( defined $sms ) {
431 $newdata{smsalertnumber} = $sms;
434 ### Error checks should happen before this line.
435 $nok = $nok || scalar(@errors);
436 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
438 if ($op eq 'insert'){
439 # we know it's not a duplicate borrowernumber or there would already be an error
440 delete $newdata{password2};
441 $patron = eval { Koha::Patron->new(\%newdata)->store };
443 # FIXME Urgent error handling here, we cannot fail without relevant feedback
444 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
445 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
446 push @messages, {error => 'error_on_insert_patron'};
450 add_guarantors( $patron, $input );
451 $borrowernumber = $patron->borrowernumber;
452 $newdata{'borrowernumber'} = $borrowernumber;
455 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
456 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
457 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
459 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
460 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
461 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
463 elsif ($newdata{email} =~ /\w\@\w/) {
464 $emailaddr = $newdata{email}
466 elsif ($newdata{emailpro} =~ /\w\@\w/) {
467 $emailaddr = $newdata{emailpro}
469 elsif ($newdata{B_email} =~ /\w\@\w/) {
470 $emailaddr = $newdata{B_email}
472 # if we manage to find a valid email address, send notice
474 $newdata{emailaddr} = $emailaddr;
477 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
480 $template->param(error_alert => $@);
481 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
482 $template->{VARS}->{'error_alert'} = "no_email";
484 $template->{VARS}->{'info_alert'} = 1;
489 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
490 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
493 # Create HouseboundRole if necessary.
494 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
495 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
496 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
497 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
498 # Only create a HouseboundRole if patron has a role.
499 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
500 Koha::Patron::HouseboundRole->new({
501 borrowernumber_id => $borrowernumber,
502 housebound_chooser => $hsbnd_chooser,
503 housebound_deliverer => $hsbnd_deliverer,
507 } elsif ($op eq 'save') {
509 if ($NoUpdateLogin) {
510 delete $newdata{'password'};
511 delete $newdata{'userid'};
514 $patron = Koha::Patrons->find( $borrowernumber );
516 if ($NoUpdateEmail) {
517 delete $newdata{'email'};
518 delete $newdata{'emailpro'};
519 delete $newdata{'B_email'};
522 delete $newdata{password2};
525 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
526 # updating any columns in the borrowers table,
527 # which can happen if we're only editing the
528 # patron attributes or messaging preferences sections
531 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
532 push @messages, {error => 'error_on_update_patron'};
537 # Update or create our HouseboundRole if necessary.
538 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
539 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
540 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
541 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
542 if ( $housebound_role ) {
543 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
544 # Update our HouseboundRole.
546 ->housebound_chooser($hsbnd_chooser)
547 ->housebound_deliverer($hsbnd_deliverer)
550 $housebound_role->delete; # No longer needed.
553 # Only create a HouseboundRole if patron has a role.
554 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
555 $housebound_role = Koha::Patron::HouseboundRole->new({
556 borrowernumber_id => $borrowernumber,
557 housebound_chooser => $hsbnd_chooser,
558 housebound_deliverer => $hsbnd_deliverer,
563 # should never raise an exception as password validity is checked above
564 my $password = $newdata{password};
565 if ( $password and $password ne '****' ) {
566 $patron->set_password({ password => $password });
569 add_guarantors( $patron, $input );
570 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
571 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
577 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
578 $patron->extended_attributes->filter_by_branch_limitations->delete;
579 $patron->extended_attributes($extended_patron_attributes);
582 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
583 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
584 $destination = 'not_circ';
586 print scalar( $destination eq "circ" )
588 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
590 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
592 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
597 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
598 exit; # same as above
601 if ($nok or !$nodouble){
602 $op="add" if ($op eq "insert");
603 $op="modify" if ($op eq "save");
605 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
607 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
610 if (C4::Context->preference("IndependentBranches")) {
611 my $userenv = C4::Context->userenv;
612 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
613 unless ($userenv->{branch} eq $data{'branchcode'}){
614 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
620 # Define the fields to be pre-filled in guarantee records
621 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
622 my @prefill_fields=split(/\,/,$prefillguarantorfields);
626 foreach (@prefill_fields) {
627 $newdata{$_} = $guarantor->$_;
630 $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);
632 if ($op eq "modify") {
633 $template->param( updtype => 'M',modify => 1 );
634 $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;
636 $template->param( categorycode => $borrower_data->{'categorycode'} );
639 if ( $op eq "duplicate" ) {
640 $template->param( updtype => 'I' );
641 $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;
642 $data{'cardnumber'} = "";
645 if(!defined($data{'sex'})){
646 $template->param( none => 1);
647 } elsif($data{'sex'} eq 'F'){
648 $template->param( female => 1);
649 } elsif ($data{'sex'} eq 'M'){
650 $template->param( male => 1);
651 } elsif ($data{'sex'} eq 'O') {
652 $template->param( other => 1);
654 $template->param( none => 1);
657 ##Now all the data to modify a member.
660 my $no_categories = 1;
662 foreach my $category_type (qw(C A S P I X)) {
663 my $patron_categories = Koha::Patron::Categories->search_with_library_limits({ category_type => $category_type }, {order_by => ['categorycode']});
664 $no_categories = 0 if $patron_categories->count > 0;
667 while ( my $patron_category = $patron_categories->next ) {
669 { 'categorycode' => $patron_category->categorycode,
670 'categoryname' => $patron_category->description,
671 'effective_min_password_length' => $patron_category->effective_min_password_length,
672 'effective_require_strong_password' => $patron_category->effective_require_strong_password,
673 'categorycodeselected' =>
674 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
678 $typehash{'typename'} = $category_type;
679 my $typedescription = "typename_" . $typehash{'typename'};
680 $typehash{'categoryloop'} = \@categoryloop;
682 { 'typename' => $category_type,
683 $typedescription => 1,
684 'categoryloop' => \@categoryloop
688 typeloop => \@typeloop,
689 no_categories => $no_categories,
692 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
697 my $default_borrowertitle = '';
698 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
700 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
702 while (@relationships) {
703 my $relship = shift @relationships || '';
704 my %row = ('relationship' => $relship);
705 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
706 $row{'selected'}=' selected';
710 push(@relshipdata, \%row);
714 'gonenoaddress' => ['gonenoaddress'],
719 foreach ( keys(%flags) ) {
723 'name' => $flags{$key}[0]
726 $row{'yes'} = ' checked';
731 $row{'no'} = ' checked';
733 push @flagdata, \%row;
737 # in modify mod: userbranch value comes from borrowers table
738 # in add mod: userbranch value comes from branches table (ip correspondence)
741 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
742 $userbranch = C4::Context->userenv->{'branch'};
745 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
746 $userbranch = $data{'branchcode'};
748 $template->param( userbranch => $userbranch );
750 if ( Koha::Libraries->search->count < 1 ){
752 $template->param(no_branches => 1);
756 $template->param(no_categories => 1);
758 $template->param(no_add => $no_add);
759 # --------------------------------------------------------------------------------------------------------
761 $template->param( sort1 => $data{'sort1'});
762 $template->param( sort2 => $data{'sort2'});
763 $template->param( autorenew => $data{'autorenew'});
766 foreach my $error (@errors) {
767 $template->param($error) || $template->param( $error => 1);
769 $template->param(nok => 1);
772 #Formatting data for display
774 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
775 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
777 if ( $op eq 'duplicate' ) {
778 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
779 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
780 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
782 if (C4::Context->preference('uppercasesurnames')) {
783 $data{'surname'} &&= uc( $data{'surname'} );
784 $data{'contactname'} &&= uc( $data{'contactname'} );
787 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
789 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
791 $template->param( $_ => $data{$_});
794 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
795 patron_attributes_form( $template, $extended_patron_attributes, $op );
798 if (C4::Context->preference('EnhancedMessagingPreferences')) {
800 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
802 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
804 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
805 $template->param(SMSnumber => $data{'smsalertnumber'} );
806 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
809 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
810 $template->param(%data);
811 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
812 $template->param( step => $step ) if $step; # associate with step to know where u are
815 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
816 category_type => $category_type,#to know the category type of the borrower
817 "$category_type" => 1,# associate with step to know where u are
818 destination => $destination,#to know wher u come from and wher u must go in redirect
819 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
823 patron => $patron ? $patron : \%newdata, # Used by address include templates now
824 nodouble => $nodouble,
825 borrowernumber => $borrowernumber, #register number
826 relshiploop => \@relshipdata,
827 btitle=> $default_borrowertitle,
828 flagloop => \@flagdata,
829 category_type =>$category_type,
831 nok => $nok,#flag to know if an error
832 NoUpdateLogin => $NoUpdateLogin,
833 NoUpdateEmail => $NoUpdateEmail,
836 # Generate CSRF token
837 $template->param( csrf_token =>
838 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
841 # HouseboundModule data
843 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
846 if(defined($data{'flags'})){
847 $template->param(flags=>$data{'flags'});
849 if(defined($data{'contacttitle'})){
850 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
854 my ( $min, $max ) = C4::Members::get_cardnumber_length();
855 if ( defined $min ) {
857 minlength_cardnumber => $min,
858 maxlength_cardnumber => $max
862 if ( C4::Context->preference('TranslateNotices') ) {
863 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
864 $template->param( languages => $translated_languages );
867 $template->param( messages => \@messages );
868 output_html_with_http_headers $input, $cookie, $template->output;
870 sub parse_extended_patron_attributes {
872 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
876 foreach my $key (@patron_attr) {
877 my $value = $input->param($key);
878 next unless defined($value) and $value ne '';
879 my $code = $input->param("${key}_code");
880 next if exists $dups{$code}->{$value};
881 $dups{$code}->{$value} = 1;
882 push @attr, { code => $code, attribute => $value };
887 sub patron_attributes_form {
888 my $template = shift;
889 my $attributes = shift;
892 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
893 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
894 if ( $attribute_types->count == 0 ) {
895 $template->param(no_patron_attribute_types => 1);
899 # map patron's attributes into a more convenient structure
901 foreach my $attr (@$attributes) {
902 push @{ $attr_hash{$attr->{code}} }, $attr;
905 my @attribute_loop = ();
908 while ( my ( $attr_type ) = $attribute_types->next ) {
910 class => $attr_type->class(),
911 code => $attr_type->code(),
912 description => $attr_type->description(),
913 repeatable => $attr_type->repeatable(),
914 category => $attr_type->authorised_value_category(),
915 category_code => $attr_type->category_code(),
916 mandatory => $attr_type->mandatory(),
918 if (exists $attr_hash{$attr_type->code()}) {
919 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
920 my $newentry = { %$entry };
921 $newentry->{value} = $attr->{attribute};
922 $newentry->{use_dropdown} = 0;
923 if ($attr_type->authorised_value_category()) {
924 $newentry->{use_dropdown} = 1;
925 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
928 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
929 $newentry->{form_id} = "patron_attr_$i";
930 push @{$items_by_class{$attr_type->class()}}, $newentry;
934 my $newentry = { %$entry };
935 if ($attr_type->authorised_value_category()) {
936 $newentry->{use_dropdown} = 1;
937 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
939 $newentry->{form_id} = "patron_attr_$i";
940 push @{$items_by_class{$attr_type->class()}}, $newentry;
943 for my $class ( sort keys %items_by_class ) {
944 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
945 my $lib = $av->count ? $av->next->lib : $class;
946 push @attribute_loop, {
948 items => $items_by_class{$class},
953 $template->param(patron_attributes => \@attribute_loop);
958 my ( $patron, $input ) = @_;
960 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
961 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
963 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
964 my $guarantor_id = $new_guarantor_id[$i];
965 my $relationship = $new_guarantor_relationship[$i];
967 next unless $guarantor_id;
969 $patron->add_guarantor(
971 guarantor_id => $guarantor_id,
972 relationship => $relationship,