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->guarantor_relationships()->guarantors->as_list unless !$patron;
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 ) {
267 push @errors, 'ERROR_cannot_delete_guarantor';
269 foreach my $id ( @delete_guarantor ) {
270 my $r = Koha::Patron::Relationships->find( $id );
276 #Check if guarantor requirements are met
277 my $valid_guarantor = @guarantors ? @guarantors : $newdata{'contactname'};
278 if ( ( $op eq 'save' || $op eq 'insert' )
279 && C4::Context->preference('ChildNeedsGuarantor')
280 && ( $category->category_type eq 'C' || $category->can_be_guarantee )
281 && !$valid_guarantor )
283 push @errors, 'ERROR_child_no_guarantor';
286 foreach my $guarantor (@guarantors) {
287 if ( ( $op eq 'save' || $op eq 'insert' ) && $guarantor->is_child || $guarantor->category->can_be_guarantee ) {
288 push @errors, 'ERROR_guarantor_is_guarantee';
292 ###############test to take the right zipcode, country and city name ##############
293 # set only if parameter was passed from the form
294 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
295 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
296 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
298 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
300 # Bug 32426 removed the fake_patron code here that filled $newdata{userid}. We should leave it now to patron->store.
302 my $extended_patron_attributes;
303 if ($op eq 'save' || $op eq 'insert'){
305 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
306 unless Koha::Token->new->check_csrf({
307 session_id => scalar $input->cookie('CGISESSID'),
308 token => scalar $input->param('csrf_token'),
311 # If the cardnumber is blank, treat it as null.
312 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
314 my $new_barcode = $newdata{'cardnumber'};
315 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
317 $newdata{'cardnumber'} = $new_barcode;
319 my $is_valid = Koha::Policy::Patrons::Cardnumber->is_valid($newdata{cardnumber}, $patron );
321 for my $m ( @{ $is_valid->messages } ) {
322 my $message = $m->message;
323 if ( $message eq 'already_exists' ) {
324 $template->param( ERROR_cardnumber_already_exists => 1 );
325 } elsif ( $message eq 'invalid_length' ) {
326 $template->param( ERROR_cardnumber_length => 1 );
332 if ($op eq 'save' && $step == 3) {
333 $dateofbirth = $patron->dateofbirth;
336 $dateofbirth = $newdata{dateofbirth};
339 if ( $dateofbirth ) {
340 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
341 my $age = $patron->get_age;
342 my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
343 if (($high && ($age > $high)) or ($age < $low)) {
344 push @errors, 'ERROR_age_limitations';
345 $template->param( age_low => $low);
346 $template->param( age_high => $high);
350 if (C4::Context->preference("IndependentBranches")) {
351 unless ( C4::Context->IsSuperLibrarian() ){
352 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
353 push @errors, "ERROR_branch";
358 # Bug 32426 removed the userid unique-check here. Postpone it to patron->store.
360 my $password = $input->param('password');
361 my $password2 = $input->param('password2');
362 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
364 if ( $password and $password ne '****' ) {
365 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
366 unless ( $is_valid ) {
367 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
368 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
369 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
374 my $emailprimary = $input->param('email');
375 my $emailsecondary = $input->param('emailpro');
376 my $emailalt = $input->param('B_email');
379 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
381 if ($emailsecondary) {
382 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
385 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
388 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
389 $extended_patron_attributes = parse_extended_patron_attributes($input);
390 for my $attr ( @$extended_patron_attributes ) {
391 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
392 my $attribute = Koha::Patron::Attribute->new($attr);
393 if ( !$attribute->unique_ok ) {
394 push @errors, "ERROR_extended_unique_id_failed";
395 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
397 ERROR_extended_unique_id_failed_code => $attr->{code},
398 ERROR_extended_unique_id_failed_value => $attr->{attribute},
399 ERROR_extended_unique_id_failed_description => $attr_type->description()
405 elsif ( $borrowernumber ) {
406 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
409 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
410 unless ($newdata{'dateexpiry'}){
411 $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
415 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
416 my $sms = $input->param('SMSnumber');
417 if ( defined $sms ) {
418 $newdata{smsalertnumber} = $sms;
421 ### Error checks should happen before this line.
422 $nok = $nok || scalar(@errors);
423 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
425 if ($op eq 'insert'){
426 # we know it's not a duplicate borrowernumber or there would already be an error
427 delete $newdata{password2};
430 Koha::Patron->new(\%newdata)->store({ guarantors => \@guarantors });
434 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
435 push @errors, "ERROR_login_exist";
437 # FIXME Urgent error handling here, we cannot fail without relevant feedback
438 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
439 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
440 push @messages, {error => 'error_on_insert_patron'};
447 add_guarantors( $patron, $input );
448 $borrowernumber = $patron->borrowernumber;
449 $newdata{'borrowernumber'} = $borrowernumber;
450 delete $newdata{password};
453 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
454 if ( $patron && C4::Context->preference("AutoEmailNewUser") ) {
455 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
456 my $emailaddr = $patron->notice_email_address;
457 # if we manage to find a valid email address, send notice
460 my $letter = GetPreparedLetter(
462 letter_code => 'WELCOME',
463 branchcode => $patron->branchcode,,
464 lang => $patron->lang || 'default',
466 'branches' => $patron->branchcode,
467 'borrowers' => $patron->borrowernumber,
472 my $message_id = EnqueueLetter(
475 borrowernumber => $patron->id,
476 to_address => $emailaddr,
477 message_transport_type => 'email'
480 SendQueuedMessages( { message_id => $message_id } ) if $message_id;
483 $template->param( error_alert => $@ );
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({ guarantors => \@guarantors }) if scalar(keys %newdata) > 1;
525 # bug 4508 - avoid crash if we're not updating any columns in the borrowers table (editing patron attrs or msg prefs)
530 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
531 push @errors, "ERROR_login_exist";
533 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
534 push @messages, {error => 'error_on_update_patron'};
541 # Update or create our HouseboundRole if necessary.
542 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
543 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
544 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
545 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
546 if ( $housebound_role ) {
547 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
548 # Update our HouseboundRole.
550 ->housebound_chooser($hsbnd_chooser)
551 ->housebound_deliverer($hsbnd_deliverer)
554 $housebound_role->delete; # No longer needed.
557 # Only create a HouseboundRole if patron has a role.
558 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
559 $housebound_role = Koha::Patron::HouseboundRole->new({
560 borrowernumber_id => $borrowernumber,
561 housebound_chooser => $hsbnd_chooser,
562 housebound_deliverer => $hsbnd_deliverer,
567 # should never raise an exception as password validity is checked above
568 my $password = $newdata{password};
569 if ( $password and $password ne '****' ) {
570 $patron->set_password({ password => $password });
573 add_guarantors( $patron, $input );
574 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
575 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
581 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
582 $patron->extended_attributes->filter_by_branch_limitations->delete;
583 $patron->extended_attributes($extended_patron_attributes);
586 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
587 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
588 $destination = 'not_circ';
590 print scalar( $destination eq "circ" )
592 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
594 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
596 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
601 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
602 exit; # same as above
605 if ($nok or !$nodouble){
606 $op="add" if ($op eq "insert");
607 $op="modify" if ($op eq "save");
609 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
611 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
614 if (C4::Context->preference("IndependentBranches")) {
615 my $userenv = C4::Context->userenv;
616 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
617 unless ($userenv->{branch} eq $data{'branchcode'}){
618 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
624 # Define the fields to be pre-filled in guarantee records
625 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
626 my @prefill_fields=split(/\,/,$prefillguarantorfields);
630 foreach (@prefill_fields) {
631 $newdata{$_} = $guarantor->$_;
634 $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);
636 if ($op eq "modify") {
637 $template->param( updtype => 'M',modify => 1 );
638 $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;
640 $template->param( categorycode => $borrower_data->{'categorycode'} );
643 if ( $op eq "duplicate" ) {
644 $template->param( updtype => 'I' );
645 $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;
646 $data{'cardnumber'} = "";
649 if(!defined($data{'sex'})){
650 $template->param( none => 1);
651 } elsif($data{'sex'} eq 'F'){
652 $template->param( female => 1);
653 } elsif ($data{'sex'} eq 'M'){
654 $template->param( male => 1);
655 } elsif ($data{'sex'} eq 'O') {
656 $template->param( other => 1);
658 $template->param( none => 1);
661 ##Now all the data to modify a member.
663 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
665 category_type => [qw(C A S P I X)],
666 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
668 { order_by => ['categorycode'] }
670 my $no_categories = ! $patron_categories->count;
672 my @patron_categories = $patron_categories->as_list;
673 # When adding a guarantor we don't have a category yet, and only want to choose from the eligible categories
674 unless ( !$category || $patron_categories->find( $category->id ) ){
675 $template->param( limited_category => 1 );
676 push @patron_categories, $category;
678 foreach my $patron_category ( @patron_categories ) {
679 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
683 patron_categories => $categories,
684 no_categories => $no_categories,
687 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
692 my $default_borrowertitle = '';
693 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
695 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
697 while (@relationships) {
698 my $relship = shift @relationships || '';
699 my %row = ('relationship' => $relship);
700 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
701 $row{'selected'}=' selected';
705 push(@relshipdata, \%row);
709 # in modify mod: userbranch value comes from borrowers table
710 # in add mod: userbranch value comes from branches table (ip correspondence)
713 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
714 $userbranch = C4::Context->userenv->{'branch'};
717 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category->category_type eq 'C' ) )) {
718 $userbranch = $data{'branchcode'};
720 $template->param( userbranch => $userbranch );
723 if ( Koha::Libraries->search->count < 1 ){
725 $template->param(no_branches => 1);
729 $template->param(no_categories => 1);
731 $template->param(no_add => $no_add);
732 # --------------------------------------------------------------------------------------------------------
734 $template->param( sort1 => $data{'sort1'});
735 $template->param( sort2 => $data{'sort2'});
736 $template->param( autorenew => $data{'autorenew'});
739 foreach my $error (@errors) {
740 $template->param($error) || $template->param( $error => 1);
742 $template->param(nok => 1);
744 #Prevent losing guarantor data if error occurs
746 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
747 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
748 foreach my $gid ( @new_guarantor_id ) {
749 my $patron = Koha::Patrons->find( $gid );
750 my $relationship = shift( @new_guarantor_relationship );
752 my $g = { patron => $patron, relationship => $relationship };
753 push( @new_guarantors, $g );
755 $template->param( new_guarantors => \@new_guarantors );
758 #Formatting data for display
760 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
761 $data{'dateenrolled'} = dt_from_string;
763 if ( $op eq 'duplicate' ) {
764 $data{'dateenrolled'} = dt_from_string;
765 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
767 if (C4::Context->preference('uppercasesurnames')) {
768 $data{'surname'} &&= uc( $data{'surname'} );
769 $data{'contactname'} &&= uc( $data{'contactname'} );
772 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
773 patron_attributes_form( $template, $extended_patron_attributes, $op );
776 if (C4::Context->preference('EnhancedMessagingPreferences')) {
778 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
780 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
782 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
783 $template->param(SMSnumber => $data{'smsalertnumber'} );
784 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
787 $template->param( borrower_data => \%data );
788 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
789 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
790 $template->param( step => $step ) if $step; # associate with step to know where u are
793 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
794 destination => $destination,#to know where u come from and where u must go in redirect
795 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
799 patron => $patron ? $patron : \%newdata, # Used by address include templates now
800 nodouble => $nodouble,
801 borrowernumber => $borrowernumber, #register number
802 relshiploop => \@relshipdata,
803 btitle=> $default_borrowertitle,
805 nok => $nok,#flag to know if an error
806 NoUpdateLogin => $NoUpdateLogin,
807 NoUpdateEmail => $NoUpdateEmail,
808 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
811 # Generate CSRF token
812 $template->param( csrf_token =>
813 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
816 # HouseboundModule data
818 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
821 if(defined($data{'flags'})){
822 $template->param(flags=>$data{'flags'});
824 if(defined($data{'contacttitle'})){
825 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
829 my ( $min, $max ) = Koha::Policy::Patrons::Cardnumber->get_valid_length();
830 if ( defined $min ) {
832 minlength_cardnumber => $min,
833 maxlength_cardnumber => $max
837 if ( C4::Context->preference('TranslateNotices') ) {
838 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
839 $template->param( languages => $translated_languages );
842 $template->param( messages => \@messages );
843 output_html_with_http_headers $input, $cookie, $template->output;
845 sub parse_extended_patron_attributes {
847 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
851 foreach my $key (@patron_attr) {
852 my $value = $input->param($key);
853 next unless defined($value) and $value ne '';
854 my $code = $input->param("${key}_code");
855 next if exists $dups{$code}->{$value};
856 $dups{$code}->{$value} = 1;
857 push @attr, { code => $code, attribute => $value };
862 sub patron_attributes_form {
863 my $template = shift;
864 my $attributes = shift;
867 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
868 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
869 if ( $attribute_types->count == 0 ) {
870 $template->param(no_patron_attribute_types => 1);
874 # map patron's attributes into a more convenient structure
876 foreach my $attr (@$attributes) {
877 push @{ $attr_hash{$attr->{code}} }, $attr;
880 my @attribute_loop = ();
883 while ( my ( $attr_type ) = $attribute_types->next ) {
885 class => $attr_type->class(),
886 code => $attr_type->code(),
887 description => $attr_type->description(),
888 repeatable => $attr_type->repeatable(),
889 category => $attr_type->authorised_value_category(),
890 category_code => $attr_type->category_code(),
891 mandatory => $attr_type->mandatory(),
893 if (exists $attr_hash{$attr_type->code()}) {
894 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
895 my $newentry = { %$entry };
896 $newentry->{value} = $attr->{attribute};
897 $newentry->{use_dropdown} = 0;
898 if ($attr_type->authorised_value_category()) {
899 $newentry->{use_dropdown} = 1;
900 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
903 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
904 $newentry->{form_id} = "patron_attr_$i";
905 push @{$items_by_class{$attr_type->class()}}, $newentry;
909 my $newentry = { %$entry };
910 if ($attr_type->authorised_value_category()) {
911 $newentry->{use_dropdown} = 1;
912 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
914 $newentry->{form_id} = "patron_attr_$i";
915 push @{$items_by_class{$attr_type->class()}}, $newentry;
918 for my $class ( sort keys %items_by_class ) {
919 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
920 my $lib = $av->count ? $av->next->lib : $class;
921 push @attribute_loop, {
923 items => $items_by_class{$class},
928 $template->param(patron_attributes => \@attribute_loop);
933 my ( $patron, $input ) = @_;
935 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
936 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
938 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
939 my $guarantor_id = $new_guarantor_id[$i];
940 my $relationship = $new_guarantor_relationship[$i];
942 next unless $guarantor_id;
944 $patron->add_guarantor(
946 guarantor_id => $guarantor_id,
947 relationship => $relationship,