3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
28 use C4::Auth qw( get_template_and_user haspermission );
30 use C4::Output qw( output_and_exit output_and_exit_if_error output_html_with_http_headers );
31 use C4::Members qw( checkcardnumber get_cardnumber_length );
32 use C4::Koha qw( GetAuthorisedValues );
33 use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages );
34 use C4::Form::MessagingPreferences;
36 use Koha::AuthorisedValues;
38 use Koha::Patron::Debarments qw( AddDebarment DelDebarment GetDebarments );
40 use Koha::DateUtils qw( dt_from_string );
43 use Koha::Patron::Attribute::Types;
44 use Koha::Patron::Categories;
45 use Koha::Patron::HouseboundRole;
46 use Koha::Patron::HouseboundRoles;
49 use Koha::SMS::Providers;
54 my $dbh = C4::Context->dbh;
56 my ($template, $loggedinuser, $cookie)
57 = get_template_and_user({template_name => "members/memberentrygen.tt",
60 flagsrequired => {borrowers => 'edit_borrowers'},
63 my $borrowernumber = $input->param('borrowernumber');
64 my $patron = Koha::Patrons->find($borrowernumber);
66 if ( $borrowernumber and not $patron ) {
67 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
70 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
71 my @providers = Koha::SMS::Providers->search( {}, { order_by => 'name' } )->as_list;
72 $template->param( sms_providers => \@providers );
75 my $actionType = $input->param('actionType') || '';
76 my $modify = $input->param('modify');
77 my $delete = $input->param('delete');
78 my $op = $input->param('op');
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');
85 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
86 # modifying an existing patron, it ipso facto
87 # isn't a duplicate. Marking FIXME because this
88 # script needs to be refactored.
89 my $nok = $input->param('nok');
90 my $step = $input->param('step') || 0;
95 my $CanUpdatePasswordExpiration;
96 my $userenv = C4::Context->userenv;
99 ## Deal with guarantor stuff
100 $template->param( relationships => $patron->guarantor_relationships ) if $patron;
102 my @relations = split /\|/, C4::Context->preference('borrowerRelationship'), -1;
103 @relations = ('') unless @relations;
104 my $empty_relationship_allowed = grep {$_ eq ""} @relations;
105 $template->param( empty_relationship_allowed => $empty_relationship_allowed );
107 my $guarantor_id = $input->param('guarantor_id');
108 my $guarantor = undef;
109 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
110 $template->param( guarantor => $guarantor );
112 my @delete_guarantor = $input->multi_param('delete_guarantor');
113 foreach my $id ( @delete_guarantor ) {
114 my $r = Koha::Patron::Relationships->find( $id );
118 ## Deal with debarments
120 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
121 my @debarments_to_remove = $input->multi_param('remove_debarment');
122 foreach my $d ( @debarments_to_remove ) {
125 if ( $input->param('add_debarment') ) {
127 my $expiration = $input->param('debarred_expiration');
130 ? dt_from_string($expiration)->ymd
135 borrowernumber => $borrowernumber,
137 comment => scalar $input->param('debarred_comment'),
138 expiration => $expiration,
143 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
145 # function to designate mandatory fields (visually with css)
146 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
147 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
148 foreach (@field_check) {
149 $template->param( "mandatory$_" => 1 );
151 # function to designate unwanted fields
152 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
153 @field_check=split(/\|/,$check_BorrowerUnwantedField);
154 foreach (@field_check) {
156 $template->param( "no$_" => 1 );
158 $template->param( "add" => 1 ) if ( $op eq 'add' );
159 $template->param( "quickadd" => 1 ) if ( $quickadd );
160 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
161 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
162 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
163 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
164 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
166 # check permission to modify email info.
167 if ( $patron->is_superlibrarian && !$logged_in_user->is_superlibrarian ) {
170 if ($logged_in_user->is_superlibrarian) {
171 $CanUpdatePasswordExpiration = 1;
174 $borrower_data = $patron->unblessed;
177 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
178 my $category = Koha::Patron::Categories->find($categorycode);
179 $template->param( patron_category => $category );
181 # if a add or modify is requested => check validity of data.
182 %data = %$borrower_data if ($borrower_data);
184 # initialize %newdata
185 my %newdata; # comes from $input->param()
186 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
187 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
188 foreach my $key (@names) {
189 if (defined $input->param($key)) {
190 $newdata{$key} = $input->param($key);
194 # check permission to modify login info.
195 if (ref($borrower_data) && ($category->category_type eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
200 # remove keys from %newdata that is not part of patron's attributes
202 my @keys_to_delete = (
203 qr/^(borrowernumber|date_renewed|debarred|debarredcomment|flags|privacy|updated_on|lastseen|login_attempts|overdrive_auth_token|anonymized)$/, # Bug 28935
204 qr/^BorrowerMandatoryField$/,
212 qr/^setting_extended_patron_attributes$/,
213 qr/^setting_messaging_prefs$/,
221 qr/^add_debarment$/, qr/^debarred_comment$/,qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
222 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
225 qr/^guarantor_firstname$/,
226 qr/^guarantor_surname$/,
227 qr/^delete_guarantor$/,
229 push @keys_to_delete, map { qr/^$_$/ } split( /\s*\|\s*/, C4::Context->preference('BorrowerUnwantedField') || q{} );
230 push @keys_to_delete, qr/^password_expiration_date$/ unless $CanUpdatePasswordExpiration;
231 for my $regexp (@keys_to_delete) {
232 for (keys %newdata) {
233 delete($newdata{$_}) if /$regexp/;
238 # Test uniqueness of surname, firstname and dateofbirth
239 if ( ( $op eq 'insert' ) and !$nodouble ) {
240 my @dup_fields = split '\|', C4::Context->preference('PatronDuplicateMatchingAddFields');
242 for my $f ( @dup_fields ) {
243 $conditions->{$f} = $newdata{$f} if $newdata{$f};
246 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
247 if ( $patrons->count > 0) {
249 $check_member = $patrons->next->borrowernumber;
253 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
254 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
255 foreach my $gid ( @new_guarantor_id ) {
256 my $patron = Koha::Patrons->find( $gid );
257 my $relationship = shift( @new_guarantor_relationship );
259 my $g = { patron => $patron, relationship => $relationship };
260 push( @new_guarantors, $g );
262 $template->param( new_guarantors => \@new_guarantors );
266 ###############test to take the right zipcode, country and city name ##############
267 # set only if parameter was passed from the form
268 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
269 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
270 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
272 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
274 # builds default userid
275 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
276 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
277 my $fake_patron = Koha::Patron->new;
278 $fake_patron->userid($patron->userid) if $patron; # editing
279 if ( ( defined $newdata{'firstname'} || $category->category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
280 # Full page edit, firstname and surname input zones are present
281 $fake_patron->firstname($newdata{firstname});
282 $fake_patron->surname($newdata{surname});
283 $fake_patron->generate_userid;
284 $newdata{'userid'} = $fake_patron->userid;
286 elsif ( ( defined $data{'firstname'} || $category->category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
287 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
288 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
289 # FIXME clean thiscode newdata vs data is very confusing
290 $fake_patron->firstname($data{firstname});
291 $fake_patron->surname($data{surname});
292 $fake_patron->generate_userid;
293 $newdata{'userid'} = $fake_patron->userid;
296 $newdata{'userid'} = $data{'userid'};
300 my $extended_patron_attributes;
301 if ($op eq 'save' || $op eq 'insert'){
303 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
304 unless Koha::Token->new->check_csrf({
305 session_id => scalar $input->cookie('CGISESSID'),
306 token => scalar $input->param('csrf_token'),
309 # If the cardnumber is blank, treat it as null.
310 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
312 my $new_barcode = $newdata{'cardnumber'};
313 Koha::Plugins->call( 'patron_barcode_transform', \$new_barcode );
315 $newdata{'cardnumber'} = $new_barcode;
317 if (my $error_code = checkcardnumber( $newdata{cardnumber}, $borrowernumber )){
318 push @errors, $error_code == 1
319 ? 'ERROR_cardnumber_already_exists'
321 ? 'ERROR_cardnumber_length'
326 if ($op eq '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";
351 # Check if the 'userid' is unique. 'userid' might not always be present in
352 # the edited values list when editing certain sub-forms. Get it straight
353 # from the DB if absent.
354 my $userid = $newdata{ userid } // $borrower_data->{ userid };
355 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new();
356 $p->userid( $userid );
357 unless ( $p->has_valid_userid ) {
358 push @errors, "ERROR_login_exist";
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};
429 $patron = eval { Koha::Patron->new(\%newdata)->store };
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'};
438 add_guarantors( $patron, $input );
439 $borrowernumber = $patron->borrowernumber;
440 $newdata{'borrowernumber'} = $borrowernumber;
441 delete $newdata{password};
444 # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
445 if ( C4::Context->preference("AutoEmailNewUser") ) {
446 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
447 my $emailaddr = $patron->notice_email_address;
448 # if we manage to find a valid email address, send notice
451 my $letter = GetPreparedLetter(
453 letter_code => 'WELCOME',
454 branchcode => $patron->branchcode,,
455 lang => $patron->lang || 'default',
457 'branches' => $patron->branchcode,
458 'borrowers' => $patron->borrowernumber,
463 my $message_id = EnqueueLetter(
466 borrowernumber => $patron->id,
467 to_address => $emailaddr,
468 message_transport_type => 'email'
471 SendQueuedMessages({ message_id => $message_id });
474 $template->param( error_alert => $@ );
479 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
480 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
483 # Create HouseboundRole if necessary.
484 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
485 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
486 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
487 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
488 # Only create a HouseboundRole if patron has a role.
489 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
490 Koha::Patron::HouseboundRole->new({
491 borrowernumber_id => $borrowernumber,
492 housebound_chooser => $hsbnd_chooser,
493 housebound_deliverer => $hsbnd_deliverer,
497 } elsif ($op eq 'save') {
499 if ($NoUpdateLogin) {
500 delete $newdata{'password'};
501 delete $newdata{'userid'};
504 $patron = Koha::Patrons->find( $borrowernumber );
506 if ($NoUpdateEmail) {
507 delete $newdata{'email'};
508 delete $newdata{'emailpro'};
509 delete $newdata{'B_email'};
512 delete $newdata{password2};
515 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
516 # updating any columns in the borrowers table,
517 # which can happen if we're only editing the
518 # patron attributes or messaging preferences sections
521 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
522 push @messages, {error => 'error_on_update_patron'};
527 # Update or create our HouseboundRole if necessary.
528 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
529 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
530 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
531 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
532 if ( $housebound_role ) {
533 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
534 # Update our HouseboundRole.
536 ->housebound_chooser($hsbnd_chooser)
537 ->housebound_deliverer($hsbnd_deliverer)
540 $housebound_role->delete; # No longer needed.
543 # Only create a HouseboundRole if patron has a role.
544 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
545 $housebound_role = Koha::Patron::HouseboundRole->new({
546 borrowernumber_id => $borrowernumber,
547 housebound_chooser => $hsbnd_chooser,
548 housebound_deliverer => $hsbnd_deliverer,
553 # should never raise an exception as password validity is checked above
554 my $password = $newdata{password};
555 if ( $password and $password ne '****' ) {
556 $patron->set_password({ password => $password });
559 add_guarantors( $patron, $input );
560 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
561 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
567 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
568 $patron->extended_attributes->filter_by_branch_limitations->delete;
569 $patron->extended_attributes($extended_patron_attributes);
572 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
573 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
574 $destination = 'not_circ';
576 print scalar( $destination eq "circ" )
578 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
580 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
582 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
587 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
588 exit; # same as above
591 if ($nok or !$nodouble){
592 $op="add" if ($op eq "insert");
593 $op="modify" if ($op eq "save");
595 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
597 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
600 if (C4::Context->preference("IndependentBranches")) {
601 my $userenv = C4::Context->userenv;
602 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
603 unless ($userenv->{branch} eq $data{'branchcode'}){
604 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
610 # Define the fields to be pre-filled in guarantee records
611 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
612 my @prefill_fields=split(/\,/,$prefillguarantorfields);
616 foreach (@prefill_fields) {
617 $newdata{$_} = $guarantor->$_;
620 $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);
622 if ($op eq "modify") {
623 $template->param( updtype => 'M',modify => 1 );
624 $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;
626 $template->param( categorycode => $borrower_data->{'categorycode'} );
629 if ( $op eq "duplicate" ) {
630 $template->param( updtype => 'I' );
631 $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;
632 $data{'cardnumber'} = "";
635 if(!defined($data{'sex'})){
636 $template->param( none => 1);
637 } elsif($data{'sex'} eq 'F'){
638 $template->param( female => 1);
639 } elsif ($data{'sex'} eq 'M'){
640 $template->param( male => 1);
641 } elsif ($data{'sex'} eq 'O') {
642 $template->param( other => 1);
644 $template->param( none => 1);
647 ##Now all the data to modify a member.
649 my $patron_categories = Koha::Patron::Categories->search_with_library_limits(
651 category_type => [qw(C A S P I X)],
652 ( $guarantor_id ? ( can_be_guarantee => 1 ) : () )
654 { order_by => ['categorycode'] }
656 my $no_categories = ! $patron_categories->count;
658 foreach my $patron_category ($patron_categories->as_list ) {
659 push @{ $categories->{ $patron_category->category_type } }, $patron_category;
663 patron_categories => $categories,
664 no_categories => $no_categories,
667 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
672 my $default_borrowertitle = '';
673 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
675 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
677 while (@relationships) {
678 my $relship = shift @relationships || '';
679 my %row = ('relationship' => $relship);
680 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
681 $row{'selected'}=' selected';
685 push(@relshipdata, \%row);
689 'gonenoaddress' => ['gonenoaddress'],
694 foreach ( keys(%flags) ) {
698 'name' => $flags{$key}[0]
701 $row{'yes'} = ' checked';
706 $row{'no'} = ' checked';
708 push @flagdata, \%row;
712 # in modify mod: userbranch value comes from borrowers table
713 # in add mod: userbranch value comes from branches table (ip correspondence)
716 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
717 $userbranch = C4::Context->userenv->{'branch'};
720 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category->category_type eq 'C' ) )) {
721 $userbranch = $data{'branchcode'};
723 $template->param( userbranch => $userbranch );
726 if ( Koha::Libraries->search->count < 1 ){
728 $template->param(no_branches => 1);
732 $template->param(no_categories => 1);
734 $template->param(no_add => $no_add);
735 # --------------------------------------------------------------------------------------------------------
737 $template->param( sort1 => $data{'sort1'});
738 $template->param( sort2 => $data{'sort2'});
739 $template->param( autorenew => $data{'autorenew'});
742 foreach my $error (@errors) {
743 $template->param($error) || $template->param( $error => 1);
745 $template->param(nok => 1);
748 #Formatting data for display
750 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
751 $data{'dateenrolled'} = dt_from_string;
753 if ( $op eq 'duplicate' ) {
754 $data{'dateenrolled'} = dt_from_string;
755 $data{dateexpiry} = $category->get_expiry_date( $data{dateenrolled} );
757 if (C4::Context->preference('uppercasesurnames')) {
758 $data{'surname'} &&= uc( $data{'surname'} );
759 $data{'contactname'} &&= uc( $data{'contactname'} );
762 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
763 patron_attributes_form( $template, $extended_patron_attributes, $op );
766 if (C4::Context->preference('EnhancedMessagingPreferences')) {
768 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
770 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
772 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
773 $template->param(SMSnumber => $data{'smsalertnumber'} );
774 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
777 $template->param( borrower_data => \%data );
778 $template->param( "show_guarantor" => $category ? $category->can_be_guarantee : 1); # associate with step to know where you are
779 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
780 $template->param( step => $step ) if $step; # associate with step to know where u are
783 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
784 destination => $destination,#to know where u come from and where u must go in redirect
785 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
789 patron => $patron ? $patron : \%newdata, # Used by address include templates now
790 nodouble => $nodouble,
791 borrowernumber => $borrowernumber, #register number
792 relshiploop => \@relshipdata,
793 btitle=> $default_borrowertitle,
794 flagloop => \@flagdata,
796 nok => $nok,#flag to know if an error
797 NoUpdateLogin => $NoUpdateLogin,
798 NoUpdateEmail => $NoUpdateEmail,
799 CanUpdatePasswordExpiration => $CanUpdatePasswordExpiration,
802 # Generate CSRF token
803 $template->param( csrf_token =>
804 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
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 ) = C4::Members::get_cardnumber_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,