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>.
28 use C4::Auth qw( get_template_and_user haspermission );
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( SendAlerts );
34 use C4::Form::MessagingPreferences;
36 use Koha::AuthorisedValues;
38 use Koha::Patron::Debarments qw( AddDebarment DelDebarment GetDebarments );
40 use Koha::DateUtils qw( dt_from_string output_pref );
43 use Koha::Patron::Attribute::Types;
44 use Koha::Patron::Categories;
45 use Koha::Patron::HouseboundRole;
46 use Koha::Patron::HouseboundRoles;
48 use Koha::SMS::Providers;
53 my $dbh = C4::Context->dbh;
55 my ($template, $loggedinuser, $cookie)
56 = get_template_and_user({template_name => "members/memberentrygen.tt",
59 flagsrequired => {borrowers => 'edit_borrowers'},
62 my $borrowernumber = $input->param('borrowernumber');
63 my $patron = Koha::Patrons->find($borrowernumber);
65 if ( $borrowernumber and not $patron ) {
66 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
69 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
70 my @providers = Koha::SMS::Providers->search();
71 $template->param( sms_providers => \@providers );
74 my $actionType = $input->param('actionType') || '';
75 my $modify = $input->param('modify');
76 my $delete = $input->param('delete');
77 my $op = $input->param('op');
78 my $destination = $input->param('destination');
79 my $cardnumber = $input->param('cardnumber');
80 my $check_member = $input->param('check_member');
81 my $nodouble = $input->param('nodouble');
82 my $duplicate = $input->param('duplicate');
83 my $quickadd = $input->param('quickadd');
84 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
85 # modifying an existing patron, it ipso facto
86 # isn't a duplicate. Marking FIXME because this
87 # script needs to be refactored.
88 my $nok = $input->param('nok');
89 my $step = $input->param('step') || 0;
94 my $userenv = C4::Context->userenv;
97 ## Deal with guarantor stuff
98 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
100 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
101 @relations = ('') unless @relations;
102 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
103 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
105 my $guarantor_id = $input->param('guarantor_id');
106 my $guarantor = undef;
107 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
108 $template->param( guarantor => $guarantor );
110 my @delete_guarantor = $input->multi_param('delete_guarantor');
111 foreach my $id ( @delete_guarantor ) {
112 my $r = Koha::Patron::Relationships->find( $id );
116 ## Deal with debarments
118 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
119 my @debarments_to_remove = $input->multi_param('remove_debarment');
120 foreach my $d ( @debarments_to_remove ) {
123 if ( $input->param('add_debarment') ) {
125 my $expiration = $input->param('debarred_expiration');
128 ? dt_from_string($expiration)->ymd
133 borrowernumber => $borrowernumber,
135 comment => scalar $input->param('debarred_comment'),
136 expiration => $expiration,
141 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
143 # function to designate mandatory fields (visually with css)
144 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
145 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
146 foreach (@field_check) {
147 $template->param( "mandatory$_" => 1 );
149 # function to designate unwanted fields
150 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
151 @field_check=split(/\|/,$check_BorrowerUnwantedField);
152 foreach (@field_check) {
154 $template->param( "no$_" => 1 );
156 $template->param( "add" => 1 ) if ( $op eq 'add' );
157 $template->param( "quickadd" => 1 ) if ( $quickadd );
158 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
159 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
160 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
161 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
162 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
164 # check permission to modify email info.
165 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
169 $borrower_data = $patron->unblessed;
170 $borrower_data->{category_type} = $patron->category->category_type;
173 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
174 my $category_type = $input->param('category_type') || '';
175 unless ($category_type or !($categorycode)){
176 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
177 $category_type = $borrowercategory->category_type;
178 my $category_name = $borrowercategory->description;
179 $template->param("categoryname"=>$category_name);
181 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
183 # if a add or modify is requested => check validity of data.
184 %data = %$borrower_data if ($borrower_data);
186 # initialize %newdata
187 my %newdata; # comes from $input->param()
188 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
189 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
190 foreach my $key (@names) {
191 if (defined $input->param($key)) {
192 $newdata{$key} = $input->param($key);
196 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
197 next unless exists $newdata{$_};
198 my $userdate = $newdata{$_} or next;
200 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
201 if ( $formatteddate ) {
202 $newdata{$_} = $formatteddate;
204 $template->param( "ERROR_$_" => 1 );
205 push(@errors,"ERROR_$_");
209 # check permission to modify login info.
210 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
215 # remove keys from %newdata that is not part of patron's attributes
217 my @keys_to_delete = (
219 qr/^BorrowerMandatoryField$/,
228 qr/^setting_extended_patron_attributes$/,
229 qr/^setting_messaging_prefs$/,
237 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
238 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
241 qr/^guarantor_firstname$/,
242 qr/^guarantor_surname$/,
243 qr/^delete_guarantor$/,
245 for my $regexp (@keys_to_delete) {
246 for (keys %newdata) {
247 delete($newdata{$_}) if /$regexp/;
252 # Test uniqueness of surname, firstname and dateofbirth
253 if ( ( $op eq 'insert' ) and !$nodouble ) {
254 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
256 for my $f ( @dup_fields ) {
257 $conditions->{$f} = $newdata{$f} if $newdata{$f};
260 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
261 if ( $patrons->count > 0) {
263 $check_member = $patrons->next->borrowernumber;
267 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
268 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
269 foreach my $gid ( @new_guarantor_id ) {
270 my $patron = Koha::Patrons->find( $gid );
271 my $relationship = shift( @new_guarantor_relationship );
273 my $g = { patron => $patron, relationship => $relationship };
274 push( @new_guarantors, $g );
276 $template->param( new_guarantors => \@new_guarantors );
280 ###############test to take the right zipcode, country and city name ##############
281 # set only if parameter was passed from the form
282 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
283 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
284 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
286 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
288 # builds default userid
289 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
290 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
291 my $fake_patron = Koha::Patron->new;
292 $fake_patron->userid($patron->userid) if $patron; # editing
293 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
294 # Full page edit, firstname and surname input zones are present
295 $fake_patron->firstname($newdata{firstname});
296 $fake_patron->surname($newdata{surname});
297 $fake_patron->generate_userid;
298 $newdata{'userid'} = $fake_patron->userid;
300 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
301 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
302 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
303 # FIXME clean thiscode newdata vs data is very confusing
304 $fake_patron->firstname($data{firstname});
305 $fake_patron->surname($data{surname});
306 $fake_patron->generate_userid;
307 $newdata{'userid'} = $fake_patron->userid;
310 $newdata{'userid'} = $data{'userid'};
314 my $extended_patron_attributes;
315 if ($op eq 'save' || $op eq 'insert'){
317 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
318 unless Koha::Token->new->check_csrf({
319 session_id => scalar $input->cookie('CGISESSID'),
320 token => scalar $input->param('csrf_token'),
323 # If the cardnumber is blank, treat it as null.
324 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
326 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
327 push @errors, $error_code == 1
328 ? 'ERROR_cardnumber_already_exists'
330 ? 'ERROR_cardnumber_length'
335 if ($op eq 'save' && $step == 3) {
336 $dateofbirth = $patron->dateofbirth;
339 $dateofbirth = $newdata{dateofbirth};
342 if ( $dateofbirth ) {
343 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
344 my $age = $patron->get_age;
345 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
346 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
347 if (($high && ($age > $high)) or ($age < $low)) {
348 push @errors, 'ERROR_age_limitations';
349 $template->param( age_low => $low);
350 $template->param( age_high => $high);
354 if (C4::Context->preference("IndependentBranches")) {
355 unless ( C4::Context->IsSuperLibrarian() ){
356 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
357 push @errors, "ERROR_branch";
361 # Check if the 'userid' is unique. 'userid' might not always be present in
362 # the edited values list when editing certain sub-forms. Get it straight
363 # from the DB if absent.
364 my $userid = $newdata{ userid } // $borrower_data->{ userid };
365 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
366 $p->userid( $userid );
367 unless ( $p->has_valid_userid ) {
368 push @errors, "ERROR_login_exist";
371 my $password = $input->param('password');
372 my $password2 = $input->param('password2');
373 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
375 if ( $password and $password ne '****' ) {
376 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, Koha::Patron::Categories->find($categorycode) );
377 unless ( $is_valid ) {
378 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
379 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
380 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
385 my $emailprimary = $input->param('email');
386 my $emailsecondary = $input->param('emailpro');
387 my $emailalt = $input->param('B_email');
390 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
392 if ($emailsecondary) {
393 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
396 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
399 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
400 $extended_patron_attributes = parse_extended_patron_attributes($input);
401 for my $attr ( @$extended_patron_attributes ) {
402 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
403 my $attribute = Koha::Patron::Attribute->new($attr);
404 if ( !$attribute->unique_ok ) {
405 push @errors, "ERROR_extended_unique_id_failed";
406 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
408 ERROR_extended_unique_id_failed_code => $attr->{code},
409 ERROR_extended_unique_id_failed_value => $attr->{attribute},
410 ERROR_extended_unique_id_failed_description => $attr_type->description()
416 elsif ( $borrowernumber ) {
417 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
420 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
421 unless ($newdata{'dateexpiry'}){
422 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
423 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
427 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
428 my $sms = $input->param('SMSnumber');
429 if ( defined $sms ) {
430 $newdata{smsalertnumber} = $sms;
433 ### Error checks should happen before this line.
434 $nok = $nok || scalar(@errors);
435 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
437 if ($op eq 'insert'){
438 # we know it's not a duplicate borrowernumber or there would already be an error
439 delete $newdata{password2};
440 $patron = eval { Koha::Patron->new(\%newdata)->store };
442 # FIXME Urgent error handling here, we cannot fail without relevant feedback
443 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
444 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
445 push @messages, {error => 'error_on_insert_patron'};
449 add_guarantors( $patron, $input );
450 $borrowernumber = $patron->borrowernumber;
451 $newdata{'borrowernumber'} = $borrowernumber;
454 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
455 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
456 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
458 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
459 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
460 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
462 elsif ($newdata{email} =~ /\w\@\w/) {
463 $emailaddr = $newdata{email}
465 elsif ($newdata{emailpro} =~ /\w\@\w/) {
466 $emailaddr = $newdata{emailpro}
468 elsif ($newdata{B_email} =~ /\w\@\w/) {
469 $emailaddr = $newdata{B_email}
471 # if we manage to find a valid email address, send notice
473 $newdata{emailaddr} = $emailaddr;
476 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
479 $template->param(error_alert => $@);
480 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
481 $template->{VARS}->{'error_alert'} = "no_email";
483 $template->{VARS}->{'info_alert'} = 1;
488 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
489 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
492 # Create HouseboundRole if necessary.
493 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
494 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
495 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
496 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
497 # Only create a HouseboundRole if patron has a role.
498 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
499 Koha::Patron::HouseboundRole->new({
500 borrowernumber_id => $borrowernumber,
501 housebound_chooser => $hsbnd_chooser,
502 housebound_deliverer => $hsbnd_deliverer,
506 } elsif ($op eq 'save') {
508 if ($NoUpdateLogin) {
509 delete $newdata{'password'};
510 delete $newdata{'userid'};
513 $patron = Koha::Patrons->find( $borrowernumber );
515 if ($NoUpdateEmail) {
516 delete $newdata{'email'};
517 delete $newdata{'emailpro'};
518 delete $newdata{'B_email'};
521 delete $newdata{password2};
524 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
525 # updating any columns in the borrowers table,
526 # which can happen if we're only editing the
527 # patron attributes or messaging preferences sections
530 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
531 push @messages, {error => 'error_on_update_patron'};
536 # Update or create our HouseboundRole if necessary.
537 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
538 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
539 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
540 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
541 if ( $housebound_role ) {
542 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
543 # Update our HouseboundRole.
545 ->housebound_chooser($hsbnd_chooser)
546 ->housebound_deliverer($hsbnd_deliverer)
549 $housebound_role->delete; # No longer needed.
552 # Only create a HouseboundRole if patron has a role.
553 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
554 $housebound_role = Koha::Patron::HouseboundRole->new({
555 borrowernumber_id => $borrowernumber,
556 housebound_chooser => $hsbnd_chooser,
557 housebound_deliverer => $hsbnd_deliverer,
562 # should never raise an exception as password validity is checked above
563 my $password = $newdata{password};
564 if ( $password and $password ne '****' ) {
565 $patron->set_password({ password => $password });
568 add_guarantors( $patron, $input );
569 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
570 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
576 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
577 $patron->extended_attributes->filter_by_branch_limitations->delete;
578 $patron->extended_attributes($extended_patron_attributes);
581 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
582 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
583 $destination = 'not_circ';
585 print scalar( $destination eq "circ" )
587 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
589 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
591 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
596 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
597 exit; # same as above
600 if ($nok or !$nodouble){
601 $op="add" if ($op eq "insert");
602 $op="modify" if ($op eq "save");
604 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
606 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
609 if (C4::Context->preference("IndependentBranches")) {
610 my $userenv = C4::Context->userenv;
611 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
612 unless ($userenv->{branch} eq $data{'branchcode'}){
613 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
619 # Define the fields to be pre-filled in guarantee records
620 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
621 my @prefill_fields=split(/\,/,$prefillguarantorfields);
625 foreach (@prefill_fields) {
626 $newdata{$_} = $guarantor->$_;
629 $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);
631 if ($op eq "modify") {
632 $template->param( updtype => 'M',modify => 1 );
633 $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;
635 $template->param( categorycode => $borrower_data->{'categorycode'} );
638 if ( $op eq "duplicate" ) {
639 $template->param( updtype => 'I' );
640 $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;
641 $data{'cardnumber'} = "";
644 if(!defined($data{'sex'})){
645 $template->param( none => 1);
646 } elsif($data{'sex'} eq 'F'){
647 $template->param( female => 1);
648 } elsif ($data{'sex'} eq 'M'){
649 $template->param( male => 1);
650 } elsif ($data{'sex'} eq 'O') {
651 $template->param( other => 1);
653 $template->param( none => 1);
656 ##Now all the data to modify a member.
659 my $no_categories = 1;
661 foreach my $category_type (qw(C A S P I X)) {
662 my $patron_categories = Koha::Patron::Categories->search_with_library_limits({ category_type => $category_type }, {order_by => ['categorycode']});
663 $no_categories = 0 if $patron_categories->count > 0;
666 while ( my $patron_category = $patron_categories->next ) {
668 { 'categorycode' => $patron_category->categorycode,
669 'categoryname' => $patron_category->description,
670 'effective_min_password_length' => $patron_category->effective_min_password_length,
671 'effective_require_strong_password' => $patron_category->effective_require_strong_password,
672 'categorycodeselected' =>
673 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
677 $typehash{'typename'} = $category_type;
678 my $typedescription = "typename_" . $typehash{'typename'};
679 $typehash{'categoryloop'} = \@categoryloop;
681 { 'typename' => $category_type,
682 $typedescription => 1,
683 'categoryloop' => \@categoryloop
687 typeloop => \@typeloop,
688 no_categories => $no_categories,
691 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
696 my $default_borrowertitle = '';
697 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
699 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
701 while (@relationships) {
702 my $relship = shift @relationships || '';
703 my %row = ('relationship' => $relship);
704 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
705 $row{'selected'}=' selected';
709 push(@relshipdata, \%row);
713 'gonenoaddress' => ['gonenoaddress'],
718 foreach ( keys(%flags) ) {
722 'name' => $flags{$key}[0]
725 $row{'yes'} = ' checked';
730 $row{'no'} = ' checked';
732 push @flagdata, \%row;
736 # in modify mod: userbranch value comes from borrowers table
737 # in add mod: userbranch value comes from branches table (ip correspondence)
740 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
741 $userbranch = C4::Context->userenv->{'branch'};
744 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
745 $userbranch = $data{'branchcode'};
747 $template->param( userbranch => $userbranch );
749 if ( Koha::Libraries->search->count < 1 ){
751 $template->param(no_branches => 1);
755 $template->param(no_categories => 1);
757 $template->param(no_add => $no_add);
758 # --------------------------------------------------------------------------------------------------------
760 $template->param( sort1 => $data{'sort1'});
761 $template->param( sort2 => $data{'sort2'});
762 $template->param( autorenew => $data{'autorenew'});
765 foreach my $error (@errors) {
766 $template->param($error) || $template->param( $error => 1);
768 $template->param(nok => 1);
771 #Formatting data for display
773 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
774 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
776 if ( $op eq 'duplicate' ) {
777 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
778 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
779 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
781 if (C4::Context->preference('uppercasesurnames')) {
782 $data{'surname'} &&= uc( $data{'surname'} );
783 $data{'contactname'} &&= uc( $data{'contactname'} );
786 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
788 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
790 $template->param( $_ => $data{$_});
793 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
794 patron_attributes_form( $template, $extended_patron_attributes, $op );
797 if (C4::Context->preference('EnhancedMessagingPreferences')) {
799 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
801 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
803 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
804 $template->param(SMSnumber => $data{'smsalertnumber'} );
805 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
808 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
809 $template->param(%data);
810 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
811 $template->param( step => $step ) if $step; # associate with step to know where u are
814 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
815 category_type => $category_type,#to know the category type of the borrower
816 "$category_type" => 1,# associate with step to know where u are
817 destination => $destination,#to know wher u come from and wher u must go in redirect
818 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
822 patron => $patron ? $patron : \%newdata, # Used by address include templates now
823 nodouble => $nodouble,
824 borrowernumber => $borrowernumber, #register number
825 relshiploop => \@relshipdata,
826 btitle=> $default_borrowertitle,
827 flagloop => \@flagdata,
828 category_type =>$category_type,
830 nok => $nok,#flag to know if an error
831 NoUpdateLogin => $NoUpdateLogin,
832 NoUpdateEmail => $NoUpdateEmail,
835 # Generate CSRF token
836 $template->param( csrf_token =>
837 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
840 # HouseboundModule data
842 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
845 if(defined($data{'flags'})){
846 $template->param(flags=>$data{'flags'});
848 if(defined($data{'contacttitle'})){
849 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
853 my ( $min, $max ) = C4::Members::get_cardnumber_length();
854 if ( defined $min ) {
856 minlength_cardnumber => $min,
857 maxlength_cardnumber => $max
861 if ( C4::Context->preference('TranslateNotices') ) {
862 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
863 $template->param( languages => $translated_languages );
866 $template->param( messages => \@messages );
867 output_html_with_http_headers $input, $cookie, $template->output;
869 sub parse_extended_patron_attributes {
871 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
875 foreach my $key (@patron_attr) {
876 my $value = $input->param($key);
877 next unless defined($value) and $value ne '';
878 my $code = $input->param("${key}_code");
879 next if exists $dups{$code}->{$value};
880 $dups{$code}->{$value} = 1;
881 push @attr, { code => $code, attribute => $value };
886 sub patron_attributes_form {
887 my $template = shift;
888 my $attributes = shift;
891 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
892 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
893 if ( $attribute_types->count == 0 ) {
894 $template->param(no_patron_attribute_types => 1);
898 # map patron's attributes into a more convenient structure
900 foreach my $attr (@$attributes) {
901 push @{ $attr_hash{$attr->{code}} }, $attr;
904 my @attribute_loop = ();
907 while ( my ( $attr_type ) = $attribute_types->next ) {
909 class => $attr_type->class(),
910 code => $attr_type->code(),
911 description => $attr_type->description(),
912 repeatable => $attr_type->repeatable(),
913 category => $attr_type->authorised_value_category(),
914 category_code => $attr_type->category_code(),
915 mandatory => $attr_type->mandatory(),
917 if (exists $attr_hash{$attr_type->code()}) {
918 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
919 my $newentry = { %$entry };
920 $newentry->{value} = $attr->{attribute};
921 $newentry->{use_dropdown} = 0;
922 if ($attr_type->authorised_value_category()) {
923 $newentry->{use_dropdown} = 1;
924 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
927 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
928 $newentry->{form_id} = "patron_attr_$i";
929 push @{$items_by_class{$attr_type->class()}}, $newentry;
933 my $newentry = { %$entry };
934 if ($attr_type->authorised_value_category()) {
935 $newentry->{use_dropdown} = 1;
936 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
938 $newentry->{form_id} = "patron_attr_$i";
939 push @{$items_by_class{$attr_type->class()}}, $newentry;
942 for my $class ( sort keys %items_by_class ) {
943 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
944 my $lib = $av->count ? $av->next->lib : $class;
945 push @attribute_loop, {
947 items => $items_by_class{$class},
952 $template->param(patron_attributes => \@attribute_loop);
957 my ( $patron, $input ) = @_;
959 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
960 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
962 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
963 my $guarantor_id = $new_guarantor_id[$i];
964 my $relationship = $new_guarantor_relationship[$i];
966 next unless $guarantor_id;
968 $patron->add_guarantor(
970 guarantor_id => $guarantor_id,
971 relationship => $relationship,