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;
50 use Koha::SMS::Providers;
55 my $dbh = C4::Context->dbh;
57 my ($template, $loggedinuser, $cookie)
58 = get_template_and_user({template_name => "members/memberentrygen.tt",
61 flagsrequired => {borrowers => 'edit_borrowers'},
64 my $borrowernumber = $input->param('borrowernumber');
65 my $patron = Koha::Patrons->find($borrowernumber);
67 if ( $borrowernumber and not $patron ) {
68 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
71 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
72 my @providers = Koha::SMS::Providers->search( {}, { order_by => 'name' } )->as_list;
73 $template->param( sms_providers => \@providers );
76 my $actionType = $input->param('actionType') || '';
77 my $modify = $input->param('modify');
78 my $delete = $input->param('cud-delete');
79 my $op = $input->param('op');
80 my $destination = $input->param('destination');
81 my $cardnumber = $input->param('cardnumber');
82 my $check_member = $input->param('check_member');
83 my $nodouble = $input->param('nodouble');
84 my $duplicate = $input->param('duplicate');
85 my $quickadd = $input->param('quickadd');
86 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
87 # modifying an existing patron, it ipso facto
88 # isn't a duplicate. Marking FIXME because this
89 # script needs to be refactored.
90 my $nok = $input->param('nok');
91 my $step = $input->param('step') || 0;
96 my $CanUpdatePasswordExpiration;
97 my $userenv = C4::Context->userenv;
100 ## Deal with guarantor stuff
101 $template->param( relationships => $patron->guarantor_relationships ) if $patron;
103 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
104 @relations = ('') unless @relations;
105 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
106 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
108 my $guarantor_id = $input->param('guarantor_id');
109 my $guarantor = undef;
110 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
111 $template->param( guarantor => $guarantor );
113 #Search existing guarantor id(s) and new ones from params
115 my @new_guarantor_ids = grep { $_ ne '' } $input->multi_param('new_guarantor_id');
117 foreach my $new_guarantor_id (@new_guarantor_ids) {
118 my $new_guarantor = Koha::Patrons->find( { borrowernumber => $new_guarantor_id } );
119 push @guarantors, $new_guarantor;
122 my @existing_guarantors = $patron ? $patron->guarantor_relationships()->guarantors->as_list : ();
123 push @guarantors, @existing_guarantors;
125 ## Deal with debarments
127 restriction_types => scalar Koha::Patron::Restriction::Types->search()
129 my @debarments_to_remove = $input->multi_param('remove_debarment');
130 foreach my $d ( @debarments_to_remove ) {
133 if ( $input->param('add_debarment') ) {
135 my $expiration = $input->param('debarred_expiration');
138 ? dt_from_string($expiration)->ymd
143 borrowernumber => $borrowernumber,
144 type => scalar $input->param('debarred_type') // 'MANUAL',
145 comment => scalar $input->param('debarred_comment'),
146 expiration => $expiration,
151 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
153 # function to designate mandatory fields (visually with css)
154 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
155 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
156 foreach (@field_check) {
157 $template->param( "mandatory$_" => 1 );
159 # function to designate unwanted fields
160 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
161 @field_check=split(/\|/,$check_BorrowerUnwantedField);
162 foreach (@field_check) {
164 $template->param( "no$_" => 1 );
166 $template->param( "cud-add" => 1 ) if ( $op eq 'cud-add' );
167 $template->param( "quickadd" => 1 ) if ( $quickadd );
168 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
169 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
170 if ( $op eq 'modify' or $op eq 'cud-save' or $op eq 'duplicate' ) {
171 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
172 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
174 # check permission to modify email info.
175 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
178 if ($logged_in_user->is_superlibrarian) {
179 $CanUpdatePasswordExpiration = 1;
182 $borrower_data = $patron->unblessed;
185 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
186 my $category = Koha::Patron::Categories->find($categorycode);
187 $template->param( patron_category => $category );
189 # if a add or modify is requested => check validity of data.
190 %data = %$borrower_data if ($borrower_data);
192 # initialize %newdata
193 my %newdata; # comes from $input->param()
194 if ( $op eq 'cud-insert' || $op eq 'modify' || $op eq 'cud-save' || $op eq 'duplicate' ) {
195 my @names = ( $borrower_data && $op ne 'cud-save' ) ? keys %$borrower_data : $input->param();
196 foreach my $key (@names) {
197 if (defined $input->param($key)) {
198 $newdata{$key} = $input->param($key);
202 # check permission to modify login info.
203 if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
208 # remove keys from %newdata that is not part of patron's attributes
210 my @keys_to_delete = (
211 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
212 qr/^BorrowerMandatoryField$/,
220 qr/^setting_extended_patron_attributes$/,
221 qr/^setting_messaging_prefs$/,
229 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^debarred_type$/, qr/^remove_debarment$/, # We already dealt with debarments previously
230 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
233 qr/^guarantor_firstname$/,
234 qr/^guarantor_surname$/,
235 qr/^delete_guarantor$/,
237 push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
238 push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
239 for my $regexp (@keys_to_delete) {
240 for (keys %newdata) {
241 delete($newdata{$_}) if /$regexp/;
246 # Test uniqueness of surname, firstname and dateofbirth
247 if ( ( $op eq 'cud-insert' ) and !$nodouble ) {
248 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
250 for my $f ( @dup_fields ) {
251 $conditions->{$f} = $newdata{$f} if $newdata{$f};
254 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
255 if ( $patrons->count > 0) {
257 $check_member = $patrons->next->borrowernumber;
261 #Attempt to delete guarantors
262 my @delete_guarantor = $input->multi_param('delete_guarantor');
263 if (@delete_guarantor) {
264 if ( C4::Context->preference('ChildNeedsGuarantor')
265 && 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 'cud-save' || $op eq 'cud-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 'cud-save' || $op eq 'cud-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 'cud-save' || $op eq 'cud-insert'){
305 # If the cardnumber is blank, treat it as null.
306 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
308 my $new_barcode = $newdata{'cardnumber'};
309 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
311 $newdata{'cardnumber'} = $new_barcode;
313 my $is_valid = Koha::Policy::Patrons::Cardnumber->is_valid($newdata{cardnumber}, $patron );
315 for my $m ( @{ $is_valid->messages } ) {
316 my $message = $m->message;
317 if ( $message eq 'already_exists' ) {
318 $template->param( ERROR_cardnumber_already_exists => 1 );
319 } elsif ( $message eq 'invalid_length' ) {
320 $template->param( ERROR_cardnumber_length => 1 );
326 if ($op eq 'cud-save' && $step == 3) {
327 $dateofbirth = $patron->dateofbirth;
330 $dateofbirth = $newdata{dateofbirth};
333 if ( $dateofbirth ) {
334 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
335 my $age = $patron->get_age;
336 my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
337 if (($high && ($age > $high)) or ($age < $low)) {
338 push @errors, 'ERROR_age_limitations';
339 $template->param( age_low => $low);
340 $template->param( age_high => $high);
344 if (C4::Context->preference("IndependentBranches")) {
345 unless ( C4::Context->IsSuperLibrarian() ){
346 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
347 push @errors, "ERROR_branch";
352 # Bug 32426 removed the userid unique-check here. Postpone it to patron->store.
354 my $password = $input->param('password');
355 my $password2 = $input->param('password2');
356 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
358 if ( $password and $password ne '****' ) {
359 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
360 unless ( $is_valid ) {
361 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
362 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
363 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
368 my $emailprimary = $input->param('cud-email');
369 my $emailsecondary = $input->param('emailpro');
370 my $emailalt = $input->param('B_email');
373 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
375 if ($emailsecondary) {
376 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
379 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
382 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
383 $extended_patron_attributes = parse_extended_patron_attributes($input);
384 for my $attr ( @$extended_patron_attributes ) {
385 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
386 my $attribute = Koha::Patron::Attribute->new($attr);
387 if ( !$attribute->unique_ok ) {
388 push @errors, "ERROR_extended_unique_id_failed";
389 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
391 ERROR_extended_unique_id_failed_code => $attr->{code},
392 ERROR_extended_unique_id_failed_value => $attr->{attribute},
393 ERROR_extended_unique_id_failed_description => $attr_type->description()
399 elsif ( $borrowernumber ) {
400 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
403 if ( ($op eq 'modify' || $op eq 'cud-insert' || $op eq 'cud-save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
404 unless ($newdata{'dateexpiry'}){
405 $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
409 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
410 my $sms = $input->param('SMSnumber');
411 if ( defined $sms ) {
412 $newdata{smsalertnumber} = $sms;
415 ### Error checks should happen before this line.
416 $nok = $nok || scalar(@errors);
417 if ((!$nok) and $nodouble and ($op eq 'cud-insert' or $op eq 'cud-save')){
419 if ($op eq 'cud-insert'){
420 # we know it's not a duplicate borrowernumber or there would already be an error
421 delete $newdata{password2};
424 Koha::Patron->new( \%newdata )->store( { guarantors => \@guarantors } );
428 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
429 push @errors, "ERROR_login_exist";
431 # FIXME Urgent error handling here, we cannot fail without relevant feedback
432 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
433 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
434 push @messages, {error => 'error_on_insert_patron'};
441 add_guarantors( $patron, $input );
442 $borrowernumber = $patron->borrowernumber;
443 $newdata{'borrowernumber'} = $borrowernumber;
444 delete $newdata{password};
447 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
448 if ( $patron && C4::Context->preference("AutoEmailNewUser") ) {
449 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
450 my $emailaddr = $patron->notice_email_address;
451 # if we manage to find a valid email address, send notice
454 my $letter = GetPreparedLetter(
456 letter_code => 'WELCOME',
457 branchcode => $patron->branchcode,,
458 lang => $patron->lang || 'default',
460 'branches' => $patron->branchcode,
461 'borrowers' => $patron->borrowernumber,
466 my $message_id = EnqueueLetter(
469 borrowernumber => $patron->id,
470 to_address => $emailaddr,
471 message_transport_type => 'cud-email'
474 SendQueuedMessages( { message_id => $message_id } ) if $message_id;
477 $template->param( error_alert => $@ );
482 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
483 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
486 # Create HouseboundRole if necessary.
487 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
488 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
489 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
490 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
491 # Only create a HouseboundRole if patron has a role.
492 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
493 Koha::Patron::HouseboundRole->new({
494 borrowernumber_id => $borrowernumber,
495 housebound_chooser => $hsbnd_chooser,
496 housebound_deliverer => $hsbnd_deliverer,
500 } elsif ($op eq 'cud-save') {
502 if ($NoUpdateLogin) {
503 delete $newdata{'password'};
504 delete $newdata{'userid'};
507 $patron = Koha::Patrons->find( $borrowernumber );
509 if ($NoUpdateEmail) {
510 delete $newdata{'cud-email'};
511 delete $newdata{'emailpro'};
512 delete $newdata{'B_email'};
515 delete $newdata{password2};
518 $patron->set( \%newdata )->store( { guarantors => \@guarantors } ) if scalar( keys %newdata ) > 1;
519 # bug 4508 - avoid crash if we're not updating any columns in the borrowers table (editing patron attrs or msg prefs)
524 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
525 push @errors, "ERROR_login_exist";
527 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
528 push @messages, {error => 'error_on_update_patron'};
535 # Update or create our HouseboundRole if necessary.
536 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
537 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
538 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
539 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
540 if ( $housebound_role ) {
541 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
542 # Update our HouseboundRole.
544 ->housebound_chooser($hsbnd_chooser)
545 ->housebound_deliverer($hsbnd_deliverer)
548 $housebound_role->delete; # No longer needed.
551 # Only create a HouseboundRole if patron has a role.
552 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
553 $housebound_role = Koha::Patron::HouseboundRole->new({
554 borrowernumber_id => $borrowernumber,
555 housebound_chooser => $hsbnd_chooser,
556 housebound_deliverer => $hsbnd_deliverer,
561 # should never raise an exception as password validity is checked above
562 my $password = $newdata{password};
563 if ( $password and $password ne '****' ) {
564 $patron->set_password({ password => $password });
567 add_guarantors( $patron, $input );
568 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
569 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
575 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
576 $patron->extended_attributes->filter_by_branch_limitations->delete;
577 $patron->extended_attributes($extended_patron_attributes);
580 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
581 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
582 $destination = 'not_circ';
584 print scalar( $destination eq "circ" )
586 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
588 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
590 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
595 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
596 exit; # same as above
599 if ($nok or !$nodouble){
600 $op="cud-add" if ($op eq "cud-insert");
601 $op="modify" if ($op eq "cud-save");
603 $template->param( updtype => ($op eq 'cud-add' ?'I':'M')); # used to check for $op eq "cud-insert"... but we just changed $op!
605 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
608 if (C4::Context->preference("IndependentBranches")) {
609 my $userenv = C4::Context->userenv;
610 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
611 unless ($userenv->{branch} eq $data{'branchcode'}){
612 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
618 # Define the fields to be pre-filled in guarantee records
619 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
620 my @prefill_fields=split(/\,/,$prefillguarantorfields);
622 if ($op eq 'cud-add'){
624 foreach (@prefill_fields) {
625 $newdata{$_} = $guarantor->$_;
628 $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);
630 if ($op eq "modify") {
631 $template->param( updtype => 'M',modify => 1 );
632 $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;
634 $template->param( categorycode => $borrower_data->{'categorycode'} );
637 if ( $op eq "duplicate" ) {
638 $template->param( updtype => 'I' );
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;
640 $data{'cardnumber'} = "";
643 if(!defined($data{'sex'})){
644 $template->param( none => 1);
645 } elsif($data{'sex'} eq 'F'){
646 $template->param( female => 1);
647 } elsif ($data{'sex'} eq 'M'){
648 $template->param( male => 1);
649 } elsif ($data{'sex'} eq 'O') {
650 $template->param( other => 1);
652 $template->param( none => 1);
655 ##Now all the data to modify a member.
657 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
659 category_type => [qw(C A S P I X)],
660 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
662 { order_by => ['categorycode'] }
664 my $no_categories = ! $patron_categories->count;
666 my @patron_categories = $patron_categories->as_list;
667 # When adding a guarantor we don't have a category yet, and only want to choose from the eligible categories
668 unless ( !$category || $patron_categories->find( $category->id ) ){
669 $template->param( limited_category => 1 );
670 push @patron_categories, $category;
672 foreach my $patron_category ( @patron_categories ) {
673 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
677 patron_categories => $categories,
678 no_categories => $no_categories,
681 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
686 my $default_borrowertitle = '';
687 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
689 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
691 while (@relationships) {
692 my $relship = shift @relationships || '';
693 my %row = ('relationship' => $relship);
694 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
695 $row{'selected'}=' selected';
699 push(@relshipdata, \%row);
703 # in modify mod: userbranch value comes from borrowers table
704 # in add mod: userbranch value comes from branches table (ip correspondence)
707 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
708 $userbranch = C4::Context->userenv->{'branch'};
711 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'cud-add' && $category->category_type eq 'C' ) )) {
712 $userbranch = $data{'branchcode'};
714 $template->param( userbranch => $userbranch );
717 if ( Koha::Libraries->search->count < 1 ){
719 $template->param(no_branches => 1);
723 $template->param(no_categories => 1);
725 $template->param(no_add => $no_add);
726 # --------------------------------------------------------------------------------------------------------
728 $template->param( sort1 => $data{'sort1'});
729 $template->param( sort2 => $data{'sort2'});
730 $template->param( autorenew => $data{'autorenew'});
733 foreach my $error (@errors) {
734 $template->param($error) || $template->param( $error => 1);
736 $template->param(nok => 1);
738 #Prevent losing guarantor data if error occurs
740 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
741 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
742 foreach my $gid ( @new_guarantor_id ) {
743 my $patron = Koha::Patrons->find( $gid );
744 my $relationship = shift( @new_guarantor_relationship );
746 my $g = { patron => $patron, relationship => $relationship };
747 push( @new_guarantors, $g );
749 $template->param( new_guarantors => \@new_guarantors );
752 #Formatting data for display
754 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
755 $data{'dateenrolled'} = dt_from_string;
757 if ( $op eq 'duplicate' ) {
758 $data{'dateenrolled'} = dt_from_string;
759 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
761 if (C4::Context->preference('uppercasesurnames')) {
762 $data{'surname'} &&= uc( $data{'surname'} );
763 $data{'contactname'} &&= uc( $data{'contactname'} );
766 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
767 patron_attributes_form( $template, $extended_patron_attributes, $op );
770 if (C4::Context->preference('EnhancedMessagingPreferences')) {
771 if ($op eq 'cud-add') {
772 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
774 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
776 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
777 $template->param(SMSnumber => $data{'smsalertnumber'} );
778 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
781 $template->param( borrower_data => \%data );
782 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
783 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
784 $template->param( step => $step ) if $step; # associate with step to know where u are
787 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
788 destination => $destination,#to know where u come from and where u must go in redirect
789 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
793 patron => $patron ? $patron : \%newdata, # Used by address include templates now
794 nodouble => $nodouble,
795 borrowernumber => $borrowernumber, #register number
796 relshiploop => \@relshipdata,
797 btitle=> $default_borrowertitle,
799 nok => $nok,#flag to know if an error
800 NoUpdateLogin => $NoUpdateLogin,
801 NoUpdateEmail => $NoUpdateEmail,
802 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
805 # HouseboundModule data
807 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
810 if(defined($data{'flags'})){
811 $template->param(flags=>$data{'flags'});
813 if(defined($data{'contacttitle'})){
814 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
818 my ( $min, $max ) = Koha::Policy::Patrons::Cardnumber->get_valid_length();
819 if ( defined $min ) {
821 minlength_cardnumber => $min,
822 maxlength_cardnumber => $max
826 if ( C4::Context->preference('TranslateNotices') ) {
827 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
828 $template->param( languages => $translated_languages );
831 $template->param( messages => \@messages );
832 output_html_with_http_headers $input, $cookie, $template->output;
834 sub parse_extended_patron_attributes {
836 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
840 foreach my $key (@patron_attr) {
841 my $value = $input->param($key);
842 next unless defined($value) and $value ne '';
843 my $code = $input->param("${key}_code");
844 next if exists $dups{$code}->{$value};
845 $dups{$code}->{$value} = 1;
846 push @attr, { code => $code, attribute => $value };
851 sub patron_attributes_form {
852 my $template = shift;
853 my $attributes = shift;
856 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
857 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
858 if ( $attribute_types->count == 0 ) {
859 $template->param(no_patron_attribute_types => 1);
863 # map patron's attributes into a more convenient structure
865 foreach my $attr (@$attributes) {
866 push @{ $attr_hash{$attr->{code}} }, $attr;
869 my @attribute_loop = ();
872 while ( my ( $attr_type ) = $attribute_types->next ) {
874 class => $attr_type->class(),
875 code => $attr_type->code(),
876 description => $attr_type->description(),
877 repeatable => $attr_type->repeatable(),
878 category => $attr_type->authorised_value_category(),
879 category_code => $attr_type->category_code(),
880 mandatory => $attr_type->mandatory(),
882 if (exists $attr_hash{$attr_type->code()}) {
883 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
884 my $newentry = { %$entry };
885 $newentry->{value} = $attr->{attribute};
886 $newentry->{use_dropdown} = 0;
887 if ($attr_type->authorised_value_category()) {
888 $newentry->{use_dropdown} = 1;
889 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
892 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
893 $newentry->{form_id} = "patron_attr_$i";
894 push @{$items_by_class{$attr_type->class()}}, $newentry;
898 my $newentry = { %$entry };
899 if ($attr_type->authorised_value_category()) {
900 $newentry->{use_dropdown} = 1;
901 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
903 $newentry->{form_id} = "patron_attr_$i";
904 push @{$items_by_class{$attr_type->class()}}, $newentry;
907 for my $class ( sort keys %items_by_class ) {
908 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
909 my $lib = $av->count ? $av->next->lib : $class;
910 push @attribute_loop, {
912 items => $items_by_class{$class},
917 $template->param(patron_attributes => \@attribute_loop);
922 my ( $patron, $input ) = @_;
924 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
925 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
927 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
928 my $guarantor_id = $new_guarantor_id[$i];
929 my $relationship = $new_guarantor_relationship[$i];
931 next unless $guarantor_id;
933 $patron->add_guarantor(
935 guarantor_id => $guarantor_id,
936 relationship => $relationship,