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 $modify = $input->param('modify');
77 my $delete = $input->param('cud-delete');
78 my $op = $input->param('op') || q{};
79 my $destination = $input->param('destination');
80 my $cardnumber = $input->param('cardnumber');
81 my $check_member = $input->param('check_member');
82 my $nodouble = $input->param('nodouble');
83 my $duplicate = $input->param('duplicate');
84 my $quickadd = $input->param('quickadd');
86 $nodouble = 1 if ($op eq 'edit_form' 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 $guarantor_id = $input->param('guarantor_id');
104 my $guarantor = undef;
105 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
106 $template->param( guarantor => $guarantor );
108 #Search existing guarantor id(s) and new ones from params
110 my @new_guarantor_ids = grep { $_ ne '' } $input->multi_param('new_guarantor_id');
112 foreach my $new_guarantor_id (@new_guarantor_ids) {
113 my $new_guarantor = Koha::Patrons->find( { borrowernumber => $new_guarantor_id } );
114 push @guarantors, $new_guarantor;
117 my @existing_guarantors = $patron ? $patron->guarantor_relationships()->guarantors->as_list : ();
118 push @guarantors, @existing_guarantors;
120 ## Deal with debarments
122 restriction_types => scalar Koha::Patron::Restriction::Types->search()
124 my @debarments_to_remove = $input->multi_param('remove_debarment');
125 foreach my $d ( @debarments_to_remove ) {
128 if ( $input->param('add_debarment') ) {
130 my $expiration = $input->param('debarred_expiration');
133 ? dt_from_string($expiration)->ymd
138 borrowernumber => $borrowernumber,
139 type => scalar $input->param('debarred_type') // 'MANUAL',
140 comment => scalar $input->param('debarred_comment'),
141 expiration => $expiration,
146 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
148 # function to designate mandatory fields (visually with css)
149 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
150 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
151 foreach (@field_check) {
152 $template->param( "mandatory$_" => 1 );
154 # function to designate unwanted fields
155 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
156 @field_check=split(/\|/,$check_BorrowerUnwantedField);
157 foreach (@field_check) {
159 $template->param( "no$_" => 1 );
161 $template->param( "quickadd" => 1 ) if ( $quickadd );
162 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
163 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
164 if ( $op eq 'edit_form' or $op eq 'cud-save' or $op eq 'duplicate' ) {
165 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
166 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
168 # check permission to modify email info.
169 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
172 if ($logged_in_user->is_superlibrarian) {
173 $CanUpdatePasswordExpiration = 1;
176 $borrower_data = $patron->unblessed;
179 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
180 my $category = Koha::Patron::Categories->find($categorycode);
181 $template->param( patron_category => $category );
183 # if a add or modify is requested => check validity of data.
184 %data = %$borrower_data if ($borrower_data);
186 # initialize %newdata
187 my %newdata; # comes from $input->param()
188 if ( $op eq 'cud-insert' || $op eq 'edit_form' || $op eq 'cud-save' || $op eq 'duplicate' ) {
189 my @names = ( $borrower_data && $op ne 'cud-save' ) ? keys %$borrower_data : $input->param();
190 foreach my $key (@names) {
191 if (defined $input->param($key)) {
192 $newdata{$key} = $input->param($key);
196 # check permission to modify login info.
197 if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
202 # remove keys from %newdata that is not part of patron's attributes
204 my @keys_to_delete = (
205 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
206 qr/^BorrowerMandatoryField$/,
214 qr/^setting_extended_patron_attributes$/,
215 qr/^setting_messaging_prefs$/,
223 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^debarred_type$/, qr/^remove_debarment$/, # We already dealt with debarments previously
224 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
227 qr/^guarantor_firstname$/,
228 qr/^guarantor_surname$/,
229 qr/^delete_guarantor$/,
231 push @keys_to_delete,
233 grep { $_ ne 'dateexpiry' } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
234 push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
235 for my $regexp (@keys_to_delete) {
236 for (keys %newdata) {
237 delete($newdata{$_}) if /$regexp/;
242 # Test uniqueness of surname, firstname and dateofbirth
243 if ( ( $op eq 'cud-insert' ) and !$nodouble ) {
244 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
246 for my $f ( @dup_fields ) {
247 $conditions->{$f} = $newdata{$f} if $newdata{$f};
250 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
251 if ( $patrons->count > 0) {
253 $check_member = $patrons->next->borrowernumber;
257 #Attempt to delete guarantors
258 my @delete_guarantor = $input->multi_param('delete_guarantor');
259 if (@delete_guarantor) {
260 if ( C4::Context->preference('ChildNeedsGuarantor')
261 && scalar @guarantors - scalar @delete_guarantor == 0 )
263 push @errors, 'ERROR_cannot_delete_guarantor';
265 foreach my $id (@delete_guarantor) {
266 my $r = Koha::Patron::Relationships->find($id);
272 #Check if guarantor requirements are met
273 my $valid_guarantor = @guarantors ? @guarantors : $newdata{'contactname'};
274 if ( ( $op eq 'cud-save' || $op eq 'cud-insert' )
275 && C4::Context->preference('ChildNeedsGuarantor')
276 && ( $category->category_type eq 'C' || $category->can_be_guarantee )
277 && !$valid_guarantor )
279 push @errors, 'ERROR_child_no_guarantor';
282 foreach my $guarantor (@guarantors) {
283 if ( ( $op eq 'cud-save' || $op eq 'cud-insert' ) && $guarantor->is_child || $guarantor->category->can_be_guarantee ) {
284 push @errors, 'ERROR_guarantor_is_guarantee';
288 ###############test to take the right zipcode, country and city name ##############
289 # set only if parameter was passed from the form
290 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
291 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
292 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
294 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
296 # Bug 32426 removed the fake_patron code here that filled $newdata{userid}. We should leave it now to patron->store.
298 my $extended_patron_attributes;
299 if ($op eq 'cud-save' || $op eq 'cud-insert'){
301 # If the cardnumber is blank, treat it as null.
302 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
304 my $new_barcode = $newdata{'cardnumber'};
305 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
307 $newdata{'cardnumber'} = $new_barcode;
309 my $is_valid = Koha::Policy::Patrons::Cardnumber->is_valid($newdata{cardnumber}, $patron );
311 for my $m ( @{ $is_valid->messages } ) {
312 my $message = $m->message;
313 if ( $message eq 'already_exists' ) {
314 $template->param( ERROR_cardnumber_already_exists => 1 );
315 } elsif ( $message eq 'invalid_length' ) {
316 $template->param( ERROR_cardnumber_length => 1 );
322 if ($op eq 'cud-save' && $step == 3) {
323 $dateofbirth = $patron->dateofbirth;
326 $dateofbirth = $newdata{dateofbirth};
329 if ( $dateofbirth ) {
330 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
331 my $age = $patron->get_age;
332 my ($low,$high) = ($category->dateofbirthrequired, $category->upperagelimit);
333 if (($high && ($age > $high)) or ($age < $low)) {
334 push @errors, 'ERROR_age_limitations';
335 $template->param( age_low => $low);
336 $template->param( age_high => $high);
340 if (C4::Context->preference("IndependentBranches")) {
341 unless ( C4::Context->IsSuperLibrarian() ){
342 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
343 push @errors, "ERROR_branch";
348 # Bug 32426 removed the userid unique-check here. Postpone it to patron->store.
350 my $password = $input->param('password');
351 my $password2 = $input->param('password2');
352 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
354 if ( $password and $password ne '****' ) {
355 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category );
356 unless ( $is_valid ) {
357 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
358 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
359 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
364 my $emailprimary = $input->param('email');
365 my $emailsecondary = $input->param('emailpro');
366 my $emailalt = $input->param('B_email');
369 push (@errors, "ERROR_bad_email") unless Koha::Email->is_valid($emailprimary);
371 if ($emailsecondary) {
372 push (@errors, "ERROR_bad_email_secondary") unless Koha::Email->is_valid($emailsecondary);
375 push (@errors, "ERROR_bad_email_alternative") unless Koha::Email->is_valid($emailalt);
378 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
379 $extended_patron_attributes = parse_extended_patron_attributes($input);
380 for my $attr ( @$extended_patron_attributes ) {
381 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
382 my $attribute = Koha::Patron::Attribute->new($attr);
383 if ( !$attribute->unique_ok ) {
384 push @errors, "ERROR_extended_unique_id_failed";
385 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
387 ERROR_extended_unique_id_failed_code => $attr->{code},
388 ERROR_extended_unique_id_failed_value => $attr->{attribute},
389 ERROR_extended_unique_id_failed_description => $attr_type->description()
395 elsif ( $borrowernumber ) {
396 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
399 if ( ($op eq 'edit_form' || $op eq 'cud-insert' || $op eq 'cud-save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
400 unless ($newdata{'dateexpiry'}){
401 $newdata{'dateexpiry'} = $category->get_expiry_date( $newdata{dateenrolled} ) if $category;
405 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
406 my $sms = $input->param('SMSnumber');
407 if ( defined $sms ) {
408 $newdata{smsalertnumber} = $sms;
411 ### Error checks should happen before this line.
412 $nok = $nok || scalar(@errors);
413 if ((!$nok) and $nodouble and ($op eq 'cud-insert' or $op eq 'cud-save')){
415 if ($op eq 'cud-insert'){
416 # we know it's not a duplicate borrowernumber or there would already be an error
417 delete $newdata{password2};
420 Koha::Patron->new( \%newdata )->store( { guarantors => \@guarantors } );
424 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
425 push @errors, "ERROR_login_exist";
427 # FIXME Urgent error handling here, we cannot fail without relevant feedback
428 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
429 warn "Patron creation failed! - $_"; # Maybe we must die instead of just warn
430 push @messages, {error => 'error_on_insert_patron'};
437 add_guarantors( $patron, $input );
438 $borrowernumber = $patron->borrowernumber;
439 $newdata{'borrowernumber'} = $borrowernumber;
440 delete $newdata{password};
443 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
444 if ( $patron && C4::Context->preference("AutoEmailNewUser") ) {
445 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
446 my $emailaddr = $patron->notice_email_address;
447 # if we manage to find a valid email address, send notice
450 my $letter = GetPreparedLetter(
452 letter_code => 'WELCOME',
453 branchcode => $patron->branchcode,,
454 lang => $patron->lang || 'default',
456 'branches' => $patron->branchcode,
457 'borrowers' => $patron->borrowernumber,
462 my $message_id = EnqueueLetter(
465 borrowernumber => $patron->id,
466 to_address => $emailaddr,
467 message_transport_type => 'email'
470 SendQueuedMessages( { message_id => $message_id } ) if $message_id;
473 $template->param( error_alert => $@ );
478 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
479 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
482 # Create HouseboundRole if necessary.
483 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
484 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
485 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
486 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
487 # Only create a HouseboundRole if patron has a role.
488 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
489 Koha::Patron::HouseboundRole->new({
490 borrowernumber_id => $borrowernumber,
491 housebound_chooser => $hsbnd_chooser,
492 housebound_deliverer => $hsbnd_deliverer,
496 } elsif ($op eq 'cud-save') {
498 if ($NoUpdateLogin) {
499 delete $newdata{'password'};
500 delete $newdata{'userid'};
503 $patron = Koha::Patrons->find( $borrowernumber );
505 if ($NoUpdateEmail) {
506 delete $newdata{'email'};
507 delete $newdata{'emailpro'};
508 delete $newdata{'B_email'};
511 delete $newdata{password2};
514 $patron->set( \%newdata )->store( { guarantors => \@guarantors } ) if scalar( keys %newdata ) > 1;
515 # bug 4508 - avoid crash if we're not updating any columns in the borrowers table (editing patron attrs or msg prefs)
520 if( ref($_) eq 'Koha::Exceptions::Patron::InvalidUserid' ) {
521 push @errors, "ERROR_login_exist";
523 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
524 push @messages, {error => 'error_on_update_patron'};
531 # Update or create our HouseboundRole if necessary.
532 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
533 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
534 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
535 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
536 if ( $housebound_role ) {
537 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
538 # Update our HouseboundRole.
540 ->housebound_chooser($hsbnd_chooser)
541 ->housebound_deliverer($hsbnd_deliverer)
544 $housebound_role->delete; # No longer needed.
547 # Only create a HouseboundRole if patron has a role.
548 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
549 $housebound_role = Koha::Patron::HouseboundRole->new({
550 borrowernumber_id => $borrowernumber,
551 housebound_chooser => $hsbnd_chooser,
552 housebound_deliverer => $hsbnd_deliverer,
557 # should never raise an exception as password validity is checked above
558 my $password = $newdata{password};
559 if ( $password and $password ne '****' ) {
560 $patron->set_password({ password => $password });
563 add_guarantors( $patron, $input );
564 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
565 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
571 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
572 $patron->extended_attributes->filter_by_branch_limitations->delete;
573 $patron->extended_attributes($extended_patron_attributes);
576 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
577 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
578 $destination = 'not_circ';
580 print scalar( $destination eq "circ" )
582 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
584 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
586 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
591 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
592 exit; # same as above
595 if ($nok or !$nodouble){
596 $op = 'add_form' if ( $op eq 'cud-insert' );
597 $op = 'edit_form' if ( $op eq 'cud-save' );
600 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
604 $template->param( "op" => $op );
606 if (C4::Context->preference("IndependentBranches")) {
607 my $userenv = C4::Context->userenv;
608 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
609 unless ($userenv->{branch} eq $data{'branchcode'}){
610 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
616 # Define the fields to be pre-filled in guarantee records
617 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
618 my @prefill_fields=split(/\,/,$prefillguarantorfields);
620 prefill_fields => \@prefill_fields,
621 to_api_mapping => Koha::Patron->new->to_api_mapping
624 if ($op eq 'add_form'){
626 foreach (@prefill_fields) {
627 $newdata{$_} = $guarantor->$_;
630 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1);
632 if ($op eq 'edit_form') {
633 $template->param( updtype => 'M',modify => 1 );
634 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1) unless $step;
636 $template->param( categorycode => $borrower_data->{'categorycode'} );
639 if ( $op eq "duplicate" ) {
640 $template->param( updtype => 'I' );
641 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 ) unless $step;
642 $data{'cardnumber'} = "";
645 if(!defined($data{'sex'})){
646 $template->param( none => 1);
647 } elsif($data{'sex'} eq 'F'){
648 $template->param( female => 1);
649 } elsif ($data{'sex'} eq 'M'){
650 $template->param( male => 1);
651 } elsif ($data{'sex'} eq 'O') {
652 $template->param( other => 1);
654 $template->param( none => 1);
657 ##Now all the data to modify a member.
659 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
661 category_type => [qw(C A S P I X)],
662 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
664 { order_by => ['categorycode'] }
666 my $no_categories = ! $patron_categories->count;
668 my @patron_categories = $patron_categories->as_list;
669 # When adding a guarantor we don't have a category yet, and only want to choose from the eligible categories
670 unless ( !$category || $patron_categories->find( $category->id ) ){
671 $template->param( limited_category => 1 );
672 push @patron_categories, $category;
674 foreach my $patron_category ( @patron_categories ) {
675 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
679 patron_categories => $categories,
680 no_categories => $no_categories,
683 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
688 my $default_borrowertitle = '';
689 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
691 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
693 while (@relationships) {
694 my $relship = shift @relationships || '';
695 my %row = ('relationship' => $relship);
696 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
697 $row{'selected'}=' selected';
701 push(@relshipdata, \%row);
705 # in modify mod: userbranch value comes from borrowers table
706 # in add mod: userbranch value comes from branches table (ip correspondence)
709 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
710 $userbranch = C4::Context->userenv->{'branch'};
713 if (defined ($data{'branchcode'}) and ( $op eq 'edit_form' || $op eq 'duplicate' || ( $op eq 'add_form' && $category->category_type eq 'C' ) )) {
714 $userbranch = $data{'branchcode'};
716 $template->param( userbranch => $userbranch );
719 if ( Koha::Libraries->search->count < 1 ){
721 $template->param(no_branches => 1);
725 $template->param(no_categories => 1);
727 $template->param(no_add => $no_add);
728 # --------------------------------------------------------------------------------------------------------
730 $template->param( sort1 => $data{'sort1'});
731 $template->param( sort2 => $data{'sort2'});
732 $template->param( autorenew => $data{'autorenew'});
735 foreach my $error (@errors) {
736 $template->param($error) || $template->param( $error => 1);
738 $template->param(nok => 1);
740 #Prevent losing guarantor data if error occurs
742 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
743 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
744 foreach my $gid ( @new_guarantor_id ) {
745 my $patron = Koha::Patrons->find( $gid );
746 my $relationship = shift( @new_guarantor_relationship );
748 my $g = { patron => $patron, relationship => $relationship };
749 push( @new_guarantors, $g );
751 $template->param( new_guarantors => \@new_guarantors );
754 #Formatting data for display
756 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
757 $data{'dateenrolled'} = dt_from_string;
759 if ( $op eq 'duplicate' ) {
760 $data{'dateenrolled'} = dt_from_string;
761 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
763 if (C4::Context->preference('uppercasesurnames')) {
764 $data{'surname'} &&= uc( $data{'surname'} );
765 $data{'contactname'} &&= uc( $data{'contactname'} );
768 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
769 patron_attributes_form( $template, $extended_patron_attributes, $op );
772 if (C4::Context->preference('EnhancedMessagingPreferences')) {
773 if ($op eq 'add_form') {
774 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
776 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
778 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
779 $template->param(SMSnumber => $data{'smsalertnumber'} );
780 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
783 $template->param( borrower_data => \%data );
784 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
785 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
786 $template->param( step => $step ) if $step; # associate with step to know where u are
789 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
790 destination => $destination,#to know where u come from and where u must go in redirect
791 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
795 patron => $patron ? $patron : \%newdata, # Used by address include templates now
796 nodouble => $nodouble,
797 borrowernumber => $borrowernumber, #register number
798 relshiploop => \@relshipdata,
799 btitle=> $default_borrowertitle,
801 nok => $nok,#flag to know if an error
802 NoUpdateLogin => $NoUpdateLogin,
803 NoUpdateEmail => $NoUpdateEmail,
804 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
807 # HouseboundModule data
809 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
812 if(defined($data{'flags'})){
813 $template->param(flags=>$data{'flags'});
815 if(defined($data{'contacttitle'})){
816 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
820 my ( $min, $max ) = Koha::Policy::Patrons::Cardnumber->get_valid_length();
821 if ( defined $min ) {
823 minlength_cardnumber => $min,
824 maxlength_cardnumber => $max
828 if ( C4::Context->preference('TranslateNotices') ) {
829 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
830 $template->param( languages => $translated_languages );
833 $template->param( messages => \@messages );
834 output_html_with_http_headers $input, $cookie, $template->output;
836 sub parse_extended_patron_attributes {
838 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
842 foreach my $key (@patron_attr) {
843 my $value = $input->param($key);
844 next unless defined($value) and $value ne '';
845 my $code = $input->param("${key}_code");
846 next if exists $dups{$code}->{$value};
847 $dups{$code}->{$value} = 1;
848 push @attr, { code => $code, attribute => $value };
853 sub patron_attributes_form {
854 my $template = shift;
855 my $attributes = shift;
858 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
859 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
860 if ( $attribute_types->count == 0 ) {
861 $template->param(no_patron_attribute_types => 1);
865 # map patron's attributes into a more convenient structure
867 foreach my $attr (@$attributes) {
868 push @{ $attr_hash{$attr->{code}} }, $attr;
871 my @attribute_loop = ();
874 while ( my ( $attr_type ) = $attribute_types->next ) {
876 class => $attr_type->class(),
877 code => $attr_type->code(),
878 description => $attr_type->description(),
879 repeatable => $attr_type->repeatable(),
880 category => $attr_type->authorised_value_category(),
881 category_code => $attr_type->category_code(),
882 mandatory => $attr_type->mandatory(),
884 if (exists $attr_hash{$attr_type->code()}) {
885 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
886 my $newentry = { %$entry };
887 $newentry->{value} = $attr->{attribute};
888 $newentry->{use_dropdown} = 0;
889 if ($attr_type->authorised_value_category()) {
890 $newentry->{use_dropdown} = 1;
891 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
894 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
895 $newentry->{form_id} = "patron_attr_$i";
896 push @{$items_by_class{$attr_type->class()}}, $newentry;
900 my $newentry = { %$entry };
901 if ($attr_type->authorised_value_category()) {
902 $newentry->{use_dropdown} = 1;
903 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
905 $newentry->{form_id} = "patron_attr_$i";
906 push @{$items_by_class{$attr_type->class()}}, $newentry;
909 for my $class ( sort keys %items_by_class ) {
910 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
911 my $lib = $av->count ? $av->next->lib : $class;
912 push @attribute_loop, {
914 items => $items_by_class{$class},
919 $template->param(patron_attributes => \@attribute_loop);
924 my ( $patron, $input ) = @_;
926 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
927 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
929 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
930 my $guarantor_id = $new_guarantor_id[$i];
931 my $relationship = $new_guarantor_relationship[$i];
933 next unless $guarantor_id;
935 $patron->add_guarantor(
937 guarantor_id => $guarantor_id,
938 relationship => $relationship,