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>.
29 use C4::Auth qw( get_template_and_user haspermission );
31 use C4::Output qw( output_and_exit output_and_exit_if_error output_html_with_http_headers );
32 use C4::Koha qw( GetAuthorisedValues );
33 use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages );
34 use C4::Form::MessagingPreferences;
36 use Koha::AuthorisedValues;
38 use Koha::Patron::Debarments qw( AddDebarment DelDebarment );
39 use Koha::Patron::Restriction::Types;
41 use Koha::DateUtils qw( dt_from_string );
44 use Koha::Patron::Attribute::Types;
45 use Koha::Patron::Categories;
46 use Koha::Patron::HouseboundRole;
47 use Koha::Patron::HouseboundRoles;
48 use Koha::Policy::Patrons::Cardnumber;
51 use Koha::SMS::Providers;
56 my $dbh = C4::Context->dbh;
58 my ($template, $loggedinuser, $cookie)
59 = get_template_and_user({template_name => "members/memberentrygen.tt",
62 flagsrequired => {borrowers => 'edit_borrowers'},
65 my $borrowernumber = $input->param('borrowernumber');
66 my $patron = Koha::Patrons->find($borrowernumber);
68 if ( $borrowernumber and not $patron ) {
69 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
72 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
73 my @providers = Koha::SMS::Providers->search( {}, { order_by => 'name' } )->as_list;
74 $template->param( sms_providers => \@providers );
77 my $actionType = $input->param('actionType') || '';
78 my $modify = $input->param('modify');
79 my $delete = $input->param('delete');
80 my $op = $input->param('op');
81 my $destination = $input->param('destination');
82 my $cardnumber = $input->param('cardnumber');
83 my $check_member = $input->param('check_member');
84 my $nodouble = $input->param('nodouble');
85 my $duplicate = $input->param('duplicate');
86 my $quickadd = $input->param('quickadd');
87 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
88 # modifying an existing patron, it ipso facto
89 # isn't a duplicate. Marking FIXME because this
90 # script needs to be refactored.
91 my $nok = $input->param('nok');
92 my $step = $input->param('step') || 0;
97 my $CanUpdatePasswordExpiration;
98 my $userenv = C4::Context->userenv;
101 ## Deal with guarantor stuff
102 $template->param( relationships => $patron->guarantor_relationships ) if $patron;
104 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
105 @relations = ('') unless @relations;
106 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
107 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
109 my $guarantor_id = $input->param('guarantor_id');
110 my $guarantor = undef;
111 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
112 $template->param( guarantor => $guarantor );
114 #Search existing guarantor id(s) and new ones from params
116 my @new_guarantor_ids = grep { $_ ne '' } $input->multi_param('new_guarantor_id');
118 foreach my $new_guarantor_id (@new_guarantor_ids) {
119 my $new_guarantor = Koha::Patrons->find( { borrowernumber => $new_guarantor_id } );
120 push @guarantors, $new_guarantor;
123 my @existing_guarantors = $patron ? $patron->guarantor_relationships()->guarantors->as_list : ();
124 push @guarantors, @existing_guarantors;
126 ## Deal with debarments
128 restriction_types => scalar Koha::Patron::Restriction::Types->search()
130 my @debarments_to_remove = $input->multi_param('remove_debarment');
131 foreach my $d ( @debarments_to_remove ) {
134 if ( $input->param('add_debarment') ) {
136 my $expiration = $input->param('debarred_expiration');
139 ? dt_from_string($expiration)->ymd
144 borrowernumber => $borrowernumber,
145 type => scalar $input->param('debarred_type') // 'MANUAL',
146 comment => scalar $input->param('debarred_comment'),
147 expiration => $expiration,
152 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
154 # function to designate mandatory fields (visually with css)
155 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
156 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
157 foreach (@field_check) {
158 $template->param( "mandatory$_" => 1 );
160 # function to designate unwanted fields
161 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
162 @field_check=split(/\|/,$check_BorrowerUnwantedField);
163 foreach (@field_check) {
165 $template->param( "no$_" => 1 );
167 $template->param( "add" => 1 ) if ( $op eq 'add' );
168 $template->param( "quickadd" => 1 ) if ( $quickadd );
169 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
170 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
171 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
172 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
173 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
175 # check permission to modify email info.
176 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
179 if ($logged_in_user->is_superlibrarian) {
180 $CanUpdatePasswordExpiration = 1;
183 $borrower_data = $patron->unblessed;
186 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
187 my $category = Koha::Patron::Categories->find($categorycode);
188 $template->param( patron_category => $category );
190 # if a add or modify is requested => check validity of data.
191 %data = %$borrower_data if ($borrower_data);
193 # initialize %newdata
194 my %newdata; # comes from $input->param()
195 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
196 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
197 foreach my $key (@names) {
198 if (defined $input->param($key)) {
199 $newdata{$key} = $input->param($key);
203 # check permission to modify login info.
204 if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
209 # remove keys from %newdata that is not part of patron's attributes
211 my @keys_to_delete = (
212 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
213 qr/^BorrowerMandatoryField$/,
221 qr/^setting_extended_patron_attributes$/,
222 qr/^setting_messaging_prefs$/,
230 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^debarred_type$/, qr/^remove_debarment$/, # We already dealt with debarments previously
231 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
234 qr/^guarantor_firstname$/,
235 qr/^guarantor_surname$/,
236 qr/^delete_guarantor$/,
238 push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
239 push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
240 for my $regexp (@keys_to_delete) {
241 for (keys %newdata) {
242 delete($newdata{$_}) if /$regexp/;
247 # Test uniqueness of surname, firstname and dateofbirth
248 if ( ( $op eq 'insert' ) and !$nodouble ) {
249 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
251 for my $f ( @dup_fields ) {
252 $conditions->{$f} = $newdata{$f} if $newdata{$f};
255 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
256 if ( $patrons->count > 0) {
258 $check_member = $patrons->next->borrowernumber;
262 #Attempt to delete guarantors
263 my @delete_guarantor = $input->multi_param('delete_guarantor');
264 if (@delete_guarantor) {
265 if ( C4::Context->preference('ChildNeedsGuarantor')
266 && scalar @guarantors - scalar @delete_guarantor == 0 )
268 push @errors, 'ERROR_cannot_delete_guarantor';
270 foreach my $id (@delete_guarantor) {
271 my $r = Koha::Patron::Relationships->find($id);
277 #Check if guarantor requirements are met
278 my $valid_guarantor = @guarantors ? @guarantors : $newdata{'contactname'};
279 if ( ( $op eq 'save' || $op eq 'insert' )
280 && C4::Context->preference('ChildNeedsGuarantor')
281 && ( $category->category_type eq 'C' || $category->can_be_guarantee )
282 && !$valid_guarantor )
284 push @errors, 'ERROR_child_no_guarantor';
287 foreach my $guarantor (@guarantors) {
288 if ( ( $op eq 'save' || $op eq 'insert' ) && $guarantor->is_child || $guarantor->category->can_be_guarantee ) {
289 push @errors, 'ERROR_guarantor_is_guarantee';
293 ###############test to take the right zipcode, country and city name ##############
294 # set only if parameter was passed from the form
295 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
296 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
297 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
299 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
301 # Bug 32426 removed the fake_patron code here that filled $newdata{userid}. We should leave it now to patron->store.
303 my $extended_patron_attributes;
304 if ($op eq 'save' || $op eq 'insert'){
306 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
307 unless Koha::Token->new->check_csrf({
308 session_id => scalar $input->cookie('CGISESSID'),
309 token => scalar $input->param('csrf_token'),
312 # If the cardnumber is blank, treat it as null.
313 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
315 my $new_barcode = $newdata{'cardnumber'};
316 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
318 $newdata{'cardnumber'} = $new_barcode;
320 my $is_valid = Koha::Policy::Patrons::Cardnumber->is_valid($newdata{cardnumber}, $patron );
322 for my $m ( @{ $is_valid->messages } ) {
323 my $message = $m->message;
324 if ( $message eq 'already_exists' ) {
325 $template->param( ERROR_cardnumber_already_exists => 1 );
326 } elsif ( $message eq 'invalid_length' ) {
327 $template->param( ERROR_cardnumber_length => 1 );
333 if ($op eq 'save' && $step == 3) {
334 $dateofbirth = $patron->dateofbirth;
337 $dateofbirth = $newdata{dateofbirth};
340 if ( $dateofbirth ) {
341 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
342 my $age = $patron->get_age;
343 my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
344 if (($high && ($age > $high)) or ($age < $low)) {
345 push @errors, 'ERROR_age_limitations';
346 $template->param( age_low => $low);
347 $template->param( age_high => $high);
351 if (C4::Context->preference("IndependentBranches")) {
352 unless ( C4::Context->IsSuperLibrarian() ){
353 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
354 push @errors, "ERROR_branch";
359 # Bug 32426 removed the userid unique-check here. Postpone it to patron->store.
361 my $password = $input->param('password');
362 my $password2 = $input->param('password2');
363 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
365 if ( $password and $password ne '****' ) {
366 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
367 unless ( $is_valid ) {
368 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
369 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
370 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
375 my $emailprimary = $input->param('email');
376 my $emailsecondary = $input->param('emailpro');
377 my $emailalt = $input->param('B_email');
380 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
382 if ($emailsecondary) {
383 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
386 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
389 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
390 $extended_patron_attributes = parse_extended_patron_attributes($input);
391 for my $attr ( @$extended_patron_attributes ) {
392 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
393 my $attribute = Koha::Patron::Attribute->new($attr);
394 if ( !$attribute->unique_ok ) {
395 push @errors, "ERROR_extended_unique_id_failed";
396 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
398 ERROR_extended_unique_id_failed_code => $attr->{code},
399 ERROR_extended_unique_id_failed_value => $attr->{attribute},
400 ERROR_extended_unique_id_failed_description => $attr_type->description()
406 elsif ( $borrowernumber ) {
407 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
410 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
411 unless ($newdata{'dateexpiry'}){
412 $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
416 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
417 my $sms = $input->param('SMSnumber');
418 if ( defined $sms ) {
419 $newdata{smsalertnumber} = $sms;
422 ### Error checks should happen before this line.
423 $nok = $nok || scalar(@errors);
424 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
426 if ($op eq 'insert'){
427 # we know it's not a duplicate borrowernumber or there would already be an error
428 delete $newdata{password2};
431 Koha::Patron->new( \%newdata )->store( { guarantors => \@guarantors } );
435 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
436 push @errors, "ERROR_login_exist";
438 # FIXME Urgent error handling here, we cannot fail without relevant feedback
439 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
440 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
441 push @messages, {error => 'error_on_insert_patron'};
448 add_guarantors( $patron, $input );
449 $borrowernumber = $patron->borrowernumber;
450 $newdata{'borrowernumber'} = $borrowernumber;
451 delete $newdata{password};
454 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
455 if ( $patron && C4::Context->preference("AutoEmailNewUser") ) {
456 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
457 my $emailaddr = $patron->notice_email_address;
458 # if we manage to find a valid email address, send notice
461 my $letter = GetPreparedLetter(
463 letter_code => 'WELCOME',
464 branchcode => $patron->branchcode,,
465 lang => $patron->lang || 'default',
467 'branches' => $patron->branchcode,
468 'borrowers' => $patron->borrowernumber,
473 my $message_id = EnqueueLetter(
476 borrowernumber => $patron->id,
477 to_address => $emailaddr,
478 message_transport_type => 'email'
481 SendQueuedMessages( { message_id => $message_id } ) if $message_id;
484 $template->param( error_alert => $@ );
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( { guarantors => \@guarantors } ) if scalar( keys %newdata ) > 1;
526 # bug 4508 - avoid crash if we're not updating any columns in the borrowers table (editing patron attrs or msg prefs)
531 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
532 push @errors, "ERROR_login_exist";
534 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
535 push @messages, {error => 'error_on_update_patron'};
542 # Update or create our HouseboundRole if necessary.
543 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
544 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
545 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
546 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
547 if ( $housebound_role ) {
548 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
549 # Update our HouseboundRole.
551 ->housebound_chooser($hsbnd_chooser)
552 ->housebound_deliverer($hsbnd_deliverer)
555 $housebound_role->delete; # No longer needed.
558 # Only create a HouseboundRole if patron has a role.
559 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
560 $housebound_role = Koha::Patron::HouseboundRole->new({
561 borrowernumber_id => $borrowernumber,
562 housebound_chooser => $hsbnd_chooser,
563 housebound_deliverer => $hsbnd_deliverer,
568 # should never raise an exception as password validity is checked above
569 my $password = $newdata{password};
570 if ( $password and $password ne '****' ) {
571 $patron->set_password({ password => $password });
574 add_guarantors( $patron, $input );
575 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
576 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
582 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
583 $patron->extended_attributes->filter_by_branch_limitations->delete;
584 $patron->extended_attributes($extended_patron_attributes);
587 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
588 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
589 $destination = 'not_circ';
591 print scalar( $destination eq "circ" )
593 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
595 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
597 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
602 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
603 exit; # same as above
606 if ($nok or !$nodouble){
607 $op="add" if ($op eq "insert");
608 $op="modify" if ($op eq "save");
610 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
612 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
615 if (C4::Context->preference("IndependentBranches")) {
616 my $userenv = C4::Context->userenv;
617 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
618 unless ($userenv->{branch} eq $data{'branchcode'}){
619 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
625 # Define the fields to be pre-filled in guarantee records
626 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
627 my @prefill_fields=split(/\,/,$prefillguarantorfields);
631 foreach (@prefill_fields) {
632 $newdata{$_} = $guarantor->$_;
635 $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);
637 if ($op eq "modify") {
638 $template->param( updtype => 'M',modify => 1 );
639 $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 $template->param( categorycode => $borrower_data->{'categorycode'} );
644 if ( $op eq "duplicate" ) {
645 $template->param( updtype => 'I' );
646 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 ) unless $step;
647 $data{'cardnumber'} = "";
650 if(!defined($data{'sex'})){
651 $template->param( none => 1);
652 } elsif($data{'sex'} eq 'F'){
653 $template->param( female => 1);
654 } elsif ($data{'sex'} eq 'M'){
655 $template->param( male => 1);
656 } elsif ($data{'sex'} eq 'O') {
657 $template->param( other => 1);
659 $template->param( none => 1);
662 ##Now all the data to modify a member.
664 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
666 category_type => [qw(C A S P I X)],
667 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
669 { order_by => ['categorycode'] }
671 my $no_categories = ! $patron_categories->count;
673 my @patron_categories = $patron_categories->as_list;
674 # When adding a guarantor we don't have a category yet, and only want to choose from the eligible categories
675 unless ( !$category || $patron_categories->find( $category->id ) ){
676 $template->param( limited_category => 1 );
677 push @patron_categories, $category;
679 foreach my $patron_category ( @patron_categories ) {
680 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
684 patron_categories => $categories,
685 no_categories => $no_categories,
688 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
693 my $default_borrowertitle = '';
694 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
696 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
698 while (@relationships) {
699 my $relship = shift @relationships || '';
700 my %row = ('relationship' => $relship);
701 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
702 $row{'selected'}=' selected';
706 push(@relshipdata, \%row);
710 # in modify mod: userbranch value comes from borrowers table
711 # in add mod: userbranch value comes from branches table (ip correspondence)
714 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
715 $userbranch = C4::Context->userenv->{'branch'};
718 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category->category_type eq 'C' ) )) {
719 $userbranch = $data{'branchcode'};
721 $template->param( userbranch => $userbranch );
724 if ( Koha::Libraries->search->count < 1 ){
726 $template->param(no_branches => 1);
730 $template->param(no_categories => 1);
732 $template->param(no_add => $no_add);
733 # --------------------------------------------------------------------------------------------------------
735 $template->param( sort1 => $data{'sort1'});
736 $template->param( sort2 => $data{'sort2'});
737 $template->param( autorenew => $data{'autorenew'});
740 foreach my $error (@errors) {
741 $template->param($error) || $template->param( $error => 1);
743 $template->param(nok => 1);
745 #Prevent losing guarantor data if error occurs
747 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
748 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
749 foreach my $gid ( @new_guarantor_id ) {
750 my $patron = Koha::Patrons->find( $gid );
751 my $relationship = shift( @new_guarantor_relationship );
753 my $g = { patron => $patron, relationship => $relationship };
754 push( @new_guarantors, $g );
756 $template->param( new_guarantors => \@new_guarantors );
759 #Formatting data for display
761 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
762 $data{'dateenrolled'} = dt_from_string;
764 if ( $op eq 'duplicate' ) {
765 $data{'dateenrolled'} = dt_from_string;
766 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
768 if (C4::Context->preference('uppercasesurnames')) {
769 $data{'surname'} &&= uc( $data{'surname'} );
770 $data{'contactname'} &&= uc( $data{'contactname'} );
773 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
774 patron_attributes_form( $template, $extended_patron_attributes, $op );
777 if (C4::Context->preference('EnhancedMessagingPreferences')) {
779 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
781 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
783 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
784 $template->param(SMSnumber => $data{'smsalertnumber'} );
785 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
788 $template->param( borrower_data => \%data );
789 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
790 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
791 $template->param( step => $step ) if $step; # associate with step to know where u are
794 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
795 destination => $destination,#to know where u come from and where u must go in redirect
796 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
800 patron => $patron ? $patron : \%newdata, # Used by address include templates now
801 nodouble => $nodouble,
802 borrowernumber => $borrowernumber, #register number
803 relshiploop => \@relshipdata,
804 btitle=> $default_borrowertitle,
806 nok => $nok,#flag to know if an error
807 NoUpdateLogin => $NoUpdateLogin,
808 NoUpdateEmail => $NoUpdateEmail,
809 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
812 # Generate CSRF token
813 $template->param( csrf_token =>
814 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
817 # HouseboundModule data
819 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
822 if(defined($data{'flags'})){
823 $template->param(flags=>$data{'flags'});
825 if(defined($data{'contacttitle'})){
826 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
830 my ( $min, $max ) = Koha::Policy::Patrons::Cardnumber->get_valid_length();
831 if ( defined $min ) {
833 minlength_cardnumber => $min,
834 maxlength_cardnumber => $max
838 if ( C4::Context->preference('TranslateNotices') ) {
839 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
840 $template->param( languages => $translated_languages );
843 $template->param( messages => \@messages );
844 output_html_with_http_headers $input, $cookie, $template->output;
846 sub parse_extended_patron_attributes {
848 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
852 foreach my $key (@patron_attr) {
853 my $value = $input->param($key);
854 next unless defined($value) and $value ne '';
855 my $code = $input->param("${key}_code");
856 next if exists $dups{$code}->{$value};
857 $dups{$code}->{$value} = 1;
858 push @attr, { code => $code, attribute => $value };
863 sub patron_attributes_form {
864 my $template = shift;
865 my $attributes = shift;
868 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
869 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
870 if ( $attribute_types->count == 0 ) {
871 $template->param(no_patron_attribute_types => 1);
875 # map patron's attributes into a more convenient structure
877 foreach my $attr (@$attributes) {
878 push @{ $attr_hash{$attr->{code}} }, $attr;
881 my @attribute_loop = ();
884 while ( my ( $attr_type ) = $attribute_types->next ) {
886 class => $attr_type->class(),
887 code => $attr_type->code(),
888 description => $attr_type->description(),
889 repeatable => $attr_type->repeatable(),
890 category => $attr_type->authorised_value_category(),
891 category_code => $attr_type->category_code(),
892 mandatory => $attr_type->mandatory(),
894 if (exists $attr_hash{$attr_type->code()}) {
895 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
896 my $newentry = { %$entry };
897 $newentry->{value} = $attr->{attribute};
898 $newentry->{use_dropdown} = 0;
899 if ($attr_type->authorised_value_category()) {
900 $newentry->{use_dropdown} = 1;
901 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
904 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
905 $newentry->{form_id} = "patron_attr_$i";
906 push @{$items_by_class{$attr_type->class()}}, $newentry;
910 my $newentry = { %$entry };
911 if ($attr_type->authorised_value_category()) {
912 $newentry->{use_dropdown} = 1;
913 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
915 $newentry->{form_id} = "patron_attr_$i";
916 push @{$items_by_class{$attr_type->class()}}, $newentry;
919 for my $class ( sort keys %items_by_class ) {
920 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
921 my $lib = $av->count ? $av->next->lib : $class;
922 push @attribute_loop, {
924 items => $items_by_class{$class},
929 $template->param(patron_attributes => \@attribute_loop);
934 my ( $patron, $input ) = @_;
936 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
937 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
939 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
940 my $guarantor_id = $new_guarantor_id[$i];
941 my $relationship = $new_guarantor_relationship[$i];
943 next unless $guarantor_id;
945 $patron->add_guarantor(
947 guarantor_id => $guarantor_id,
948 relationship => $relationship,